@arcgis/portal-components 5.2.0-next.10 → 5.2.0-next.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/cdn/2CA7QHVV.js +2 -0
  2. package/dist/cdn/{ZTHTFEYA.js → 2V5S6KBL.js} +1 -1
  3. package/dist/cdn/{E7DG4PTT.js → 2X4VWQ5E.js} +1 -1
  4. package/dist/cdn/{LAFNDBTQ.js → 4BGBBW4V.js} +1 -1
  5. package/dist/cdn/4VRIZNFA.js +2 -0
  6. package/dist/cdn/6AGZRMJC.js +2 -0
  7. package/dist/cdn/6W2IHKCA.js +2 -0
  8. package/dist/cdn/{DHHSKOUY.js → BMUU2S5H.js} +1 -1
  9. package/dist/cdn/{462NPCQK.js → CTVWAEEO.js} +1 -1
  10. package/dist/cdn/{WOZDQW3S.js → DB6O5DIG.js} +1 -1
  11. package/dist/cdn/{RNLVNDGG.js → G3AK2CRM.js} +1 -1
  12. package/dist/cdn/{T7NAWRYB.js → GS6MPCDK.js} +1 -1
  13. package/dist/cdn/{BEX567FX.js → IKOAI6C7.js} +1 -1
  14. package/dist/cdn/JVKWYKZR.js +2 -0
  15. package/dist/cdn/{546F7RE5.js → KL4LVBFR.js} +188 -88
  16. package/dist/cdn/{SBMN77ZZ.js → MLPVRTHY.js} +1 -1
  17. package/dist/cdn/{SJC3537M.js → OMD65KRY.js} +1 -1
  18. package/dist/cdn/{BLB544VG.js → QGFU75HM.js} +1 -1
  19. package/dist/cdn/{5ZNQZDQO.js → QN3ZQLFB.js} +1 -1
  20. package/dist/cdn/{C4D4PGO3.js → ROCZLAYA.js} +1 -1
  21. package/dist/cdn/{QB34ACZ2.js → SB25M4FP.js} +1 -1
  22. package/dist/cdn/{GT26WGJS.js → SXZRHHXC.js} +1 -1
  23. package/dist/cdn/{53MSUMA3.js → TBYTYYJJ.js} +16 -0
  24. package/dist/cdn/{SIN2A4UX.js → VHSATYO4.js} +1 -1
  25. package/dist/cdn/{46Q4UJRT.js → VQU2EEJR.js} +1 -1
  26. package/dist/cdn/{RXSGAKUU.js → W3ZB6MHE.js} +1 -1
  27. package/dist/cdn/{UPEVTVNZ.js → WSNLUGEP.js} +1 -1
  28. package/dist/cdn/{SV2O3ZZ7.js → XFFD6YY5.js} +1 -1
  29. package/dist/cdn/{XHASDTZ3.js → XLHPYPQY.js} +1 -1
  30. package/dist/cdn/{L46YEW4Y.js → YKHMRMUE.js} +1 -1
  31. package/dist/cdn/{QNUYUNEY.js → Z73H62GB.js} +1 -1
  32. package/dist/cdn/assets/portal-item-type/icons/parquetfeaturelayer16.svg +1 -0
  33. package/dist/cdn/assets/portal-item-type/icons/parquetfeaturelayer32.svg +1 -0
  34. package/dist/cdn/assets/portal-item-type/icons/storymapframe16.svg +1 -0
  35. package/dist/cdn/assets/portal-item-type/icons/storymapframe32.svg +1 -0
  36. package/dist/cdn/assets/portal-item-type/t9n/messages.en.json +1 -1
  37. package/dist/cdn/index.js +1 -1
  38. package/dist/chunks/groups.js +7 -83
  39. package/dist/chunks/groups2.js +86 -0
  40. package/dist/chunks/portal.js +48 -8
  41. package/dist/components/arcgis-portal-ai-assistant/customElement.js +640 -335
  42. package/dist/components/arcgis-portal-group-badges/customElement.js +23 -31
  43. package/dist/components/arcgis-portal-item-type/customElement.d.ts +2 -0
  44. package/dist/components/arcgis-portal-item-type/customElement.js +45 -37
  45. package/dist/components/arcgis-portal-mentionable-text-area/customElement.js +1 -1
  46. package/dist/components/arcgis-portal-replacement-item-redirect/customElement.js +52 -40
  47. package/dist/components/arcgis-portal-voice-input/customElement.d.ts +1 -1
  48. package/dist/docs/api.json +1 -1
  49. package/dist/docs/docs.json +1 -1
  50. package/dist/docs/vscode.html-custom-data.json +1 -1
  51. package/dist/docs/web-types.json +1 -1
  52. package/package.json +4 -4
  53. package/dist/cdn/5VSDGPHH.js +0 -2
  54. package/dist/cdn/IHKNWGHP.js +0 -2
  55. package/dist/cdn/OLRMKR7F.js +0 -2
  56. package/dist/cdn/UFM62DQ3.js +0 -2
@@ -1,17 +1,17 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import a from"./RNLVNDGG.js";import"./5VSDGPHH.js";import{a as so,b as il}from"./V2EOXGK2.js";import{a as al}from"./L46YEW4Y.js";import"./T7NAWRYB.js";import{H as no,I as oo,J as ol,P as sl,h as tl,j as Mr,m as rl,v as nl}from"./DHHSKOUY.js";import{$ as De,$a as $,Aa as wt,Ba as Ue,Ca as is,D as cl,Da as Sl,E as Xe,Ea as kl,F as dl,Fa as ls,G as Xo,Ga as Cl,H as wa,Ha as $r,I as ba,Ia as Sa,J as es,Ja as El,K as Aa,Ka as Ol,L as io,La as co,M as q,Ma as Ml,N as xa,Na as po,O as pl,Oa as mo,P as R,Pa as x,Q as gt,Qa as D,R as et,Ra as ka,S as ts,T as ml,U as fl,V as Ia,W as xe,X as rs,Y as hl,Z as ns,_ as gl,a as he,aa as lo,b as B,ba as yl,ca as va,da as _l,ea as uo,f as ge,fa as yt,fb as Pl,g as ll,ga as wl,ha as bl,ia as Al,j as ne,ja as Pr,k as ue,ka as xl,la as tt,ma as Il,mb as bt,na as _t,nb as Ca,oa as os,ob as Ie,pa as rt,q as Yo,qa as ss,qb as fo,ra as vl,rb as us,sa as as,sb as ho,t as ul,ta as Tl,tb as cs,u as ao,ua as U,ub as ye,va as b,wa as Ta,xa as Fe,ya as Rr,za as Ce}from"./B7633S2A.js";import"./YIMNOUTF.js";export default $arcgis.t(([fq,gq,Jh,$d,sg,Aq,Iq,_2,vb,Gd,Er,ep,,Hd,Li,ug,{addressToLocations:cg},dg,pg,tp,{createRenderer:mg},{getSchemesByTag:fg,getSchemes:hg},{getBackgroundColorTheme:Jd},{createAgeRenderer:gg,createContinuousRenderer:yg},{getSchemesByTag:Ki},{createContinuousRenderer:_g},{createRenderer:wg},{getSchemesByTag:bg},{createRenderer:Ag},{getSchemesByTag:xg},{createRenderer:Ig},{getSchemesByTag:vg},{createRenderer:Tg},{getSchemesByTag:Sg},{createAgeRenderer:kg,createContinuousRenderer:Cg},{createRenderer:Eg},{getSchemesByTag:Og},Mg,rp,np,{formatDateOnly:Pg,convertDateFormatToIntlOptions:la,formatTimeOnly:Rg,formatDate:Zd},$g,Ng,jg,Lg,zg,op,,{fetchKnowledgeGraph:Qd,executeQueryStreaming:Dg,executeSearchStreaming:Fg},Ug,,,,,,,,,,,,,,,,,,,,,IW,TW,,,,,,,,,,,Tb,_p,{a:Rl,b:$l,c:Nl,d:jl,e:Ll}])=>{var d=x;async function Ea(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
2
+ import{a as Wl,b as Vl,d as Hl,e as Jl,f as Zl}from"./6AGZRMJC.js";import a from"./G3AK2CRM.js";import"./6W2IHKCA.js";import{a as uo,b as hl}from"./V2EOXGK2.js";import{a as fl}from"./YKHMRMUE.js";import"./GS6MPCDK.js";import{H as io,I as lo,J as pl,P as ml,h as ul,j as Rr,m as cl,v as dl}from"./BMUU2S5H.js";import{$ as De,$a as O,Aa as bt,Ba as qe,Ca as us,D as wl,Da as $l,E as Xe,Ea as Nl,F as _l,Fa as cs,G as ts,Ga as jl,H as Ta,Ha as jr,I as Sa,Ia as Pa,J as rs,Ja as zl,K as ka,Ka as Ll,L as po,La as ho,M as B,Ma as Dl,N as Ca,Na as zr,O as bl,Oa as go,P as $,Pa as I,Q as yt,Qa as D,R as et,Ra,S as ns,T as xl,U as Al,V as Ea,W as Ie,X as os,Y as Il,Z as ss,_ as vl,a as ue,aa as mo,b as q,ba as Tl,ca as Ma,da as Sl,ea as fo,f as we,fa as wt,fb as Fl,g as gl,ga as kl,ha as Cl,ia as El,j as re,ja as $r,k as ce,ka as Ml,la as tt,ma as Ol,mb as xt,na as _t,nb as $a,oa as as,ob as ve,pa as rt,q as es,qa as is,qb as yo,ra as Pl,rb as ds,sa as ls,sb as wo,t as yl,ta as Rl,tb as ps,u as co,ua as U,ub as de,va as x,wa as Oa,xa as Fe,ya as Nr,za as Ee}from"./B7633S2A.js";import"./YIMNOUTF.js";export default $arcgis.t(([tB,nB,Vd,ig,lg,xg,uB,dB,bW,Fb,ap,Er,Bi,mp,,ip,Tg,{addressToLocations:Sg},kg,Cg,fp,{createRenderer:Eg},{getSchemesByTag:Mg,getSchemes:Og},{getBackgroundColorTheme:lp},{createAgeRenderer:Pg,createContinuousRenderer:Rg},{getSchemesByTag:Xi},{createContinuousRenderer:$g},{createRenderer:Ng},{getSchemesByTag:jg},{createRenderer:zg},{getSchemesByTag:Lg},{createRenderer:Dg},{getSchemesByTag:Fg},{createRenderer:qg},{getSchemesByTag:Ug},{createAgeRenderer:Bg,createContinuousRenderer:Kg},{createRenderer:Gg},{getSchemesByTag:Wg},Vg,hp,gp,{formatDateOnly:Hg,convertDateFormatToIntlOptions:ca,formatTimeOnly:Jg,formatDate:up},Zg,Qg,Yg,Xg,ey,yp,,{fetchKnowledgeGraph:cp,executeQueryStreaming:ty,executeSearchStreaming:ry},ny,,,,,,,,,,,,,,,,,,,,,,,,,b2,A2,,,,,,,,,,,,,qb,kp,{a:ql,b:Ul,c:Bl,d:Kl,e:Gl}])=>{var d=I;async function Na(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
3
 
4
4
  If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
5
 
6
6
  Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
7
7
  |`,`
8
8
  \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
9
- `].join(" "));let n=await gl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var ps={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"}},Dl=Object.keys(ps);async function Rp(t,e){let r;if(e)r=ps[e];else{let n=Object.entries(ps).find(([,o])=>o.className===t);r=n?n[1]:void 0}if(r)try{return(await import(r.package))[r.className]}catch(n){let o=n;if("code"in o&&o.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in o&&typeof o.message=="string"){let s=(o.message.startsWith("Error: ")?o.message.slice(7):o.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function $p(t,e,r={}){let n=e||Np(t);if(!n)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);let o=ps[n];if(!o){let i=Dl.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
9
+ `].join(" "));let n=await vl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var ee=async(t,e)=>{await Na("trace_message",t,e)},_e=async(t,e)=>{await Na("graph_ux_suggestion",t,e)};var fs={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"}},Yl=Object.keys(fs);async function Gp(t,e){let r;if(e)r=fs[e];else{let n=Object.entries(fs).find(([,o])=>o.className===t);r=n?n[1]:void 0}if(r)try{return(await import(r.package))[r.className]}catch(n){let o=n;if("code"in o&&o.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in o&&typeof o.message=="string"){let s=(o.message.startsWith("Error: ")?o.message.slice(7):o.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function Wp(t,e,r={}){let n=e||Vp(t);if(!n)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);let o=fs[n];if(!o){let i=Yl.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
10
10
 
11
- Supported model providers are: ${i}`)}let{modelProvider:s,...a}=r;return new(await Rp(o.className,n))({model:t,...a})}function Np(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var zl=class ds extends co{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(e){let r=this._getCacheKey(e),n=this._modelInstanceCache.get(r);if(n)return n;let o={...this._defaultConfig,...this._modelParams(e)},s=await $p(o.model,o.modelProvider,o);for(let[a,i]of Object.entries(this._queuedMethodOperations))a in s&&typeof s[a]=="function"&&(s=await s[a](...i));return this._modelInstanceCache.set(r,s),s}async _generate(e,r,n){return(await this._getModelInstance(r))._generate(e,r??{},n)}bindTools(e,r){let n={...this._queuedMethodOperations};return n.bindTools=[e,r],new ds({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(e,...r)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[e,...r],new ds({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(e){let r=e?.configurable??{},n={};for(let[o,s]of Object.entries(r))if(o.startsWith(this._configPrefix)){let a=this._removePrefix(o,this._configPrefix);n[a]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([o])=>this._configurableFields.includes(o)))),n}_removePrefix(e,r){return e.startsWith(r)?e.slice(r.length):e}withConfig(e){let r={...e||{}},n=this._modelParams(r),o=Object.fromEntries(Object.entries(r).filter(([s])=>s!=="configurable"));return o.configurable=Object.fromEntries(Object.entries(r.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new Ce({config:r,bound:new ds({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,r){let n=await this._getModelInstance(r),o=lo(r);return n.invoke(e,o)}async stream(e,r){let n=new _l({generator:await(await this._getModelInstance(r)).stream(e,r),config:r});return await n.setup,va.fromAsyncGenerator(n)}async batch(e,r,n){return super.batch(e,r,n)}async*transform(e,r){let n=await this._getModelInstance(r),o=lo(r);yield*n.transform(e,o)}async*streamLog(e,r,n){let o=await this._getModelInstance(r),s=lo(r);yield*o.streamLog(e,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,r,n){let o=this;async function*s(){let a=await o._getModelInstance(r),i=lo(r),u=a.streamEvents(e,i,n);for await(let l of u)yield l}return va.fromAsyncGenerator(s())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let r=e??{};if(r.configurable){let{configurable:n}=r,o={};for(let[s,a]of Object.entries(n))s.startsWith("__pregel_")||(o[s]=a);r={...r,configurable:o}}return JSON.stringify(r)}};async function At(t,e){let{configurableFields:r,configPrefix:n,modelProvider:o,profile:s,...a}={configPrefix:"",...e??{}};if(o===void 0&&t?.includes(":")){let[c,...p]=t.split(":"),m=p.length===0?[c]:[c,p.join(":")];Dl.includes(m[0])&&([o,t]=m)}let i=Array.isArray(r)?[...r]:r;!t&&i===void 0&&(i=["model","modelProvider"]),n&&i===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...a},l;return i===void 0?l=new zl({defaultConfig:{...u,model:t,modelProvider:o},configPrefix:n,profile:s}):(t&&(u.model=t),o&&(u.modelProvider=o),l=new zl({defaultConfig:u,configPrefix:n,configurableFields:i,profile:s})),await l._getModelInstance(),l}var ms=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},fs=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},Oa=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(r=>`
12
- - ${r}`).join("")}.`),this.toolName=t,this.errors=e}},hs=class extends Error{toolCall;toolError;constructor(t,e){let r=t instanceof Error?t:new Error(String(t)),n=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${n} with error: ${r.stack}
13
- Please fix the error and try again.`),this.toolCall=e,this.toolError=r}},go=class Fl extends Error{static"~brand"="MiddlewareError";constructor(e,r){let n=e instanceof Error?e.message:String(e);super(n),this.name=e instanceof Error?e.name:`${r[0].toUpperCase()+r.slice(1)}Error`,e instanceof Error&&(this.cause=e)}static wrap(e,r){return ul(e)?e:new Fl(e,r)}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="MiddlewareError"}};function yo(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function Nr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}var Ul=!0,jp=0,Ee=class Ma{constructor(e,r,n){this.schema=e,this.tool=r,this.options=n}get name(){return this.tool.function.name}static fromSchema(e,r){function n(s){return s??`extract-${++jp}`}if(yt(e)||tt(e)){let s=Fe(e);return new Ma(s,{type:"function",function:{name:n(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},r)}let o;return typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?o=e:o={name:n(e.title),description:e.description??"",parameters:e.schema||e},new Ma(Fe(e),{type:"function",function:o},r)}parse(e){let r=new Ta(this.schema).validate(e);if(!r.valid)throw new Oa(this.name,r.errors.map(n=>n.error));return e}},xt=class ql{_schemaType;schema;strict;constructor(e,r){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){let n=e;this.schema=n.schema,this.strict=n.strict??Ul}else this.schema=e,this.strict=r??Ul}static fromSchema(e,r){return new ql(Fe(e),r)}parse(e){let r;if(typeof e.content=="string")r=e.content;else if(Array.isArray(e.content)){for(let n of e.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){r=n.text;break}}if(!(!r||r===""))try{let n=JSON.parse(r);return new Ta(this.schema).validate(n).valid?n:void 0}catch{}}};function Bl(t,e,r){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(o=>o instanceof Ee||o instanceof xt))return t;if(t.every(o=>yt(o)))return t.map(o=>Ee.fromSchema(o,e));if(t.every(o=>rt(o)))return t.map(o=>Ee.fromSchema(o,e));if(t.every(o=>typeof o=="object"&&o!==null&&!rt(o)&&!yt(o)))return t.map(o=>Ee.fromSchema(o,e));throw new Error(`Invalid response format: list contains mixed types.
14
- All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(t instanceof Ee||t instanceof xt)return[t];let n=Lp(r);if(yt(t))return n?[xt.fromSchema(t)]:[Ee.fromSchema(t,e)];if(rt(t))return n?[xt.fromSchema(t)]:[Ee.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return n?[xt.fromSchema(t)]:[Ee.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function Lp(t){return!t||!yo(t)||!("profile"in t)||typeof t.profile!="object"||!t.profile?!1:"structuredOutput"in t.profile&&t.profile.structuredOutput===!0}function qe(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function It(t){return typeof t=="function"?t:t.hook}var Pa=Symbol.for("langgraph-zod");Pa in globalThis||(globalThis[Pa]=new WeakSet);function Kl(t){let e=globalThis[Pa];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return cs(r,{jsonSchemaExtra:n})},reducer(n,o){return cs(r,{default:as(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{Kl(b.ZodType.prototype),Kl(x.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 Wl=class extends bl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=as(t);n!=null&&(r.default=n)}return super.add(t,...e)}},Dp=new Wl(ho);function Vl(t=!0,e,r=[]){let n={jumpTo:new Ca},o={},s={},a=i=>{if(Ie.isInstance(i)){for(let[l,c]of Object.entries(i.fields))if(!(l in n)){if(n[l]=c,l.startsWith("_"))continue;bt.isInstance(c)?(o[l]=c.inputSchema||c.valueSchema,s[l]=c.valueSchema):(o[l]=c,s[l]=c)}return}let u=ss(i);for(let[l,c]of Object.entries(u)){let p=l.startsWith("_");if(!(l in n)){if(Pr(c)){let m=ho.get(c);if(m?.reducer){m.reducer.schema?(n[l]=new bt(c,{inputSchema:m.reducer.schema,reducer:m.reducer.fn}),p||(o[l]=m.reducer.schema,s[l]=c)):(n[l]=new bt(c,{reducer:m.reducer.fn}),p||(o[l]=c,s[l]=c));continue}}n[l]=c,p||(o[l]=c,s[l]=c)}}};e&&(Ie.isInstance(e)||rt(e))&&a(e);for(let i of r)i.stateSchema&&(Ie.isInstance(i.stateSchema)||rt(i.stateSchema))&&a(i.stateSchema);return t&&(s.structuredResponse=new Ca),{state:new Ie({messages:us,...n}),input:new Ie({messages:us,...o}),output:new Ie({messages:us,...s})}}var Ra=/<name>(.*?)<\/name>/s,$a=/<content>(.*?)<\/content>/s;function Fp(t,e){if(Ie.isInstance(t)){let r={};for(let n of Object.keys(t.fields))n in e&&(r[n]=e[n]);return r}if(tt(t))return _t(t,e);throw new Error(`Invalid state schema type: ${typeof t}`)}function Hl(t){if(!R.isInstance(t)||et.isInstance(t)||!t.name)return t;let{name:e}=t;if(typeof t.content=="string")return new R({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});let r=[],n=0;for(let o of t.content)typeof o=="string"?(n+=1,r.push(`<name>${e}</name><content>${o}</content>`)):typeof o=="object"&&"type"in o&&o.type==="text"?(n+=1,r.push({...o,text:`<name>${e}</name><content>${o.text}</content>`})):r.push(o);return n||r.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new R({...t.lc_kwargs,content:r,name:void 0})}function Jl(t){if(!R.isInstance(t)||!t.content)return t;let e=[],r;if(Array.isArray(t.content))e=t.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(Ra),s=n.text.match($a);return o&&(!s||s[1]==="")?(r=o[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(Ra),s=n.text.match($a);return!o||!s?n:(r=o[1],{...n,text:s[1]})}return n});else{let n=t.content,o=n.match(Ra),s=n.match($a);if(!o||!s)return t;r=o[1],e=s[1]}return new R({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:r})}function Ht(t){return Rr.isRunnable(t)}function Gl(t){return yo(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}var Na=(t,e,r={})=>{if(Gl(t))return t.bindTools(e,r);if(Ce.isRunnableBinding(t)&&Gl(t.bound)){let n=t.bound.bindTools(e,r);return Ce.isRunnableBinding(n)?new Ce({bound:n.bound,config:{...t.config,...n.config},kwargs:{...t.kwargs,...n.kwargs},configFactories:n.configFactories??t.configFactories}):new Ce({bound:n,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function gs(t){if(typeof t=="function")return;let e=t;if(wt.isRunnableSequence(e)&&(e=e.steps.find(r=>Ce.isRunnableBinding(r))||e),!Nr(e)){if(Ce.isRunnableBinding(e)){let r=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,n=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(r||n)throw new ms}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new ms}}function ja(t){return!!(R.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Zl(t){if(t==null)return new xe("");if(xe.isInstance(t))return t;if(typeof t=="string")return new xe({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function Ql(t,e,r={}){let n=Na(t,e,r);if(n)return n;if(Nr(t)){let o=Na(await t._getModelInstance(),e,r);if(o)return o}if(wt.isRunnableSequence(t)){let o=t.steps.findIndex(s=>Ce.isRunnableBinding(s)||yo(s)||Nr(s));if(o>=0){let s=Na(t.steps[o],e,r);if(s){let a=t.steps.slice();return a.splice(o,1,s),wt.from(a)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Up(t){if(t.length===0)return;if(t.length===1)return t[0];function e(n,o){return async(s,a)=>n(s,async u=>o(u,a))}let r=t[t.length-1];for(let n=t.length-2;n>=0;n--)r=e(t[n],r);return r}function Yl(t){let e=t.filter(r=>r.wrapToolCall);if(e.length!==0)return Up(e.map(r=>{let n=r.wrapToolCall;return async(s,a)=>{let i=s.state,u=async l=>{let c={...i,...l.state};return a({...l,state:c})};try{let l=await n({...s,state:{messages:i.messages,...r.stateSchema?Fp(r.stateSchema,{...i}):{}}},u);if(!q.isInstance(l)&&!ue(l))throw new Error(`Invalid response from "wrapToolCall" in middleware "${r.name}": expected ToolMessage or Command, got ${typeof l}`);return l}catch(l){throw go.wrap(l,r.name)}}}))}async function Xl(t,e){let r={};for(let n of t){if(!n.stateSchema)continue;let o=n.stateSchema;if(Ie.isInstance(n.stateSchema)){let i={};for(let[u,l]of Object.entries(n.stateSchema.fields))bt.isInstance(l)?i[u]=l.inputSchema||l.valueSchema:i[u]=l;o=x.object(i)}let s=await Il(Tl(o,i=>i.startsWith("_")),e);if(s.success){Object.assign(r,s.data);continue}let a=s.error.issues.filter(i=>i.code==="invalid_type").map(i=>` - ${i.path.join(".")}: Required`).join(`
11
+ Supported model providers are: ${i}`)}let{modelProvider:s,...a}=r;return new(await Gp(o.className,n))({model:t,...a})}function Vp(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var Ql=class ms extends ho{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(e){let r=this._getCacheKey(e),n=this._modelInstanceCache.get(r);if(n)return n;let o={...this._defaultConfig,...this._modelParams(e)},s=await Wp(o.model,o.modelProvider,o);for(let[a,i]of Object.entries(this._queuedMethodOperations))a in s&&typeof s[a]=="function"&&(s=await s[a](...i));return this._modelInstanceCache.set(r,s),s}async _generate(e,r,n){return(await this._getModelInstance(r))._generate(e,r??{},n)}bindTools(e,r){let n={...this._queuedMethodOperations};return n.bindTools=[e,r],new ms({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(e,...r)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[e,...r],new ms({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(e){let r=e?.configurable??{},n={};for(let[o,s]of Object.entries(r))if(o.startsWith(this._configPrefix)){let a=this._removePrefix(o,this._configPrefix);n[a]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([o])=>this._configurableFields.includes(o)))),n}_removePrefix(e,r){return e.startsWith(r)?e.slice(r.length):e}withConfig(e){let r={...e||{}},n=this._modelParams(r),o=Object.fromEntries(Object.entries(r).filter(([s])=>s!=="configurable"));return o.configurable=Object.fromEntries(Object.entries(r.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new Ee({config:r,bound:new ms({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,r){let n=await this._getModelInstance(r),o=mo(r);return n.invoke(e,o)}async stream(e,r){let n=new Sl({generator:await(await this._getModelInstance(r)).stream(e,r),config:r});return await n.setup,Ma.fromAsyncGenerator(n)}async batch(e,r,n){return super.batch(e,r,n)}async*transform(e,r){let n=await this._getModelInstance(r),o=mo(r);yield*n.transform(e,o)}async*streamLog(e,r,n){let o=await this._getModelInstance(r),s=mo(r);yield*o.streamLog(e,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,r,n){let o=this;async function*s(){let a=await o._getModelInstance(r),i=mo(r),u=a.streamEvents(e,i,n);for await(let l of u)yield l}return Ma.fromAsyncGenerator(s())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let r=e??{};if(r.configurable){let{configurable:n}=r,o={};for(let[s,a]of Object.entries(n))s.startsWith("__pregel_")||(o[s]=a);r={...r,configurable:o}}return JSON.stringify(r)}};async function At(t,e){let{configurableFields:r,configPrefix:n,modelProvider:o,profile:s,...a}={configPrefix:"",...e??{}};if(o===void 0&&t?.includes(":")){let[c,...p]=t.split(":"),m=p.length===0?[c]:[c,p.join(":")];Yl.includes(m[0])&&([o,t]=m)}let i=Array.isArray(r)?[...r]:r;!t&&i===void 0&&(i=["model","modelProvider"]),n&&i===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...a},l;return i===void 0?l=new Ql({defaultConfig:{...u,model:t,modelProvider:o},configPrefix:n,profile:s}):(t&&(u.model=t),o&&(u.modelProvider=o),l=new Ql({defaultConfig:u,configPrefix:n,configurableFields:i,profile:s})),await l._getModelInstance(),l}var hs=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},gs=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},ja=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(r=>`
12
+ - ${r}`).join("")}.`),this.toolName=t,this.errors=e}},ys=class extends Error{toolCall;toolError;constructor(t,e){let r=t instanceof Error?t:new Error(String(t)),n=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${n} with error: ${r.stack}
13
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=r}},_o=class Xl extends Error{static"~brand"="MiddlewareError";constructor(e,r){let n=e instanceof Error?e.message:String(e);super(n),this.name=e instanceof Error?e.name:`${r[0].toUpperCase()+r.slice(1)}Error`,e instanceof Error&&(this.cause=e)}static wrap(e,r){return yl(e)?e:new Xl(e,r)}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="MiddlewareError"}};function bo(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function Lr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}var eu=!0,Hp=0,Me=class za{constructor(e,r,n){this.schema=e,this.tool=r,this.options=n}get name(){return this.tool.function.name}static fromSchema(e,r){function n(s){return s??`extract-${++Hp}`}if(wt(e)||tt(e)){let s=Fe(e);return new za(s,{type:"function",function:{name:n(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},r)}let o;return typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?o=e:o={name:n(e.title),description:e.description??"",parameters:e.schema||e},new za(Fe(e),{type:"function",function:o},r)}parse(e){let r=new Oa(this.schema).validate(e);if(!r.valid)throw new ja(this.name,r.errors.map(n=>n.error));return e}},It=class tu{_schemaType;schema;strict;constructor(e,r){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){let n=e;this.schema=n.schema,this.strict=n.strict??eu}else this.schema=e,this.strict=r??eu}static fromSchema(e,r){return new tu(Fe(e),r)}parse(e){let r;if(typeof e.content=="string")r=e.content;else if(Array.isArray(e.content)){for(let n of e.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){r=n.text;break}}if(!(!r||r===""))try{let n=JSON.parse(r);return new Oa(this.schema).validate(n).valid?n:void 0}catch{}}};function ru(t,e,r){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(o=>o instanceof Me||o instanceof It))return t;if(t.every(o=>wt(o)))return t.map(o=>Me.fromSchema(o,e));if(t.every(o=>rt(o)))return t.map(o=>Me.fromSchema(o,e));if(t.every(o=>typeof o=="object"&&o!==null&&!rt(o)&&!wt(o)))return t.map(o=>Me.fromSchema(o,e));throw new Error(`Invalid response format: list contains mixed types.
14
+ All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(t instanceof Me||t instanceof It)return[t];let n=Jp(r);if(wt(t))return n?[It.fromSchema(t)]:[Me.fromSchema(t,e)];if(rt(t))return n?[It.fromSchema(t)]:[Me.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return n?[It.fromSchema(t)]:[Me.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function Jp(t){return!t||!bo(t)||!("profile"in t)||typeof t.profile!="object"||!t.profile?!1:"structuredOutput"in t.profile&&t.profile.structuredOutput===!0}function Ue(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function vt(t){return typeof t=="function"?t:t.hook}var La=Symbol.for("langgraph-zod");La in globalThis||(globalThis[La]=new WeakSet);function nu(t){let e=globalThis[La];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return ps(r,{jsonSchemaExtra:n})},reducer(n,o){return ps(r,{default:ls(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{nu(x.ZodType.prototype),nu(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 ou=class extends Cl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=ls(t);n!=null&&(r.default=n)}return super.add(t,...e)}},Qp=new ou(wo);function su(t=!0,e,r=[]){let n={jumpTo:new $a},o={},s={},a=i=>{if(ve.isInstance(i)){for(let[l,c]of Object.entries(i.fields))if(!(l in n)){if(n[l]=c,l.startsWith("_"))continue;xt.isInstance(c)?(o[l]=c.inputSchema||c.valueSchema,s[l]=c.valueSchema):(o[l]=c,s[l]=c)}return}let u=is(i);for(let[l,c]of Object.entries(u)){let p=l.startsWith("_");if(!(l in n)){if($r(c)){let m=wo.get(c);if(m?.reducer){m.reducer.schema?(n[l]=new xt(c,{inputSchema:m.reducer.schema,reducer:m.reducer.fn}),p||(o[l]=m.reducer.schema,s[l]=c)):(n[l]=new xt(c,{reducer:m.reducer.fn}),p||(o[l]=c,s[l]=c));continue}}n[l]=c,p||(o[l]=c,s[l]=c)}}};e&&(ve.isInstance(e)||rt(e))&&a(e);for(let i of r)i.stateSchema&&(ve.isInstance(i.stateSchema)||rt(i.stateSchema))&&a(i.stateSchema);return t&&(s.structuredResponse=new $a),{state:new ve({messages:ds,...n}),input:new ve({messages:ds,...o}),output:new ve({messages:ds,...s})}}var Da=/<name>(.*?)<\/name>/s,Fa=/<content>(.*?)<\/content>/s;function Yp(t,e){if(ve.isInstance(t)){let r={};for(let n of Object.keys(t.fields))n in e&&(r[n]=e[n]);return r}if(tt(t))return _t(t,e);throw new Error(`Invalid state schema type: ${typeof t}`)}function iu(t){if(!$.isInstance(t)||et.isInstance(t)||!t.name)return t;let{name:e}=t;if(typeof t.content=="string")return new $({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});let r=[],n=0;for(let o of t.content)typeof o=="string"?(n+=1,r.push(`<name>${e}</name><content>${o}</content>`)):typeof o=="object"&&"type"in o&&o.type==="text"?(n+=1,r.push({...o,text:`<name>${e}</name><content>${o.text}</content>`})):r.push(o);return n||r.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new $({...t.lc_kwargs,content:r,name:void 0})}function lu(t){if(!$.isInstance(t)||!t.content)return t;let e=[],r;if(Array.isArray(t.content))e=t.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(Da),s=n.text.match(Fa);return o&&(!s||s[1]==="")?(r=o[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(Da),s=n.text.match(Fa);return!o||!s?n:(r=o[1],{...n,text:s[1]})}return n});else{let n=t.content,o=n.match(Da),s=n.match(Fa);if(!o||!s)return t;r=o[1],e=s[1]}return new $({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:r})}function Jt(t){return Nr.isRunnable(t)}function au(t){return bo(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}var qa=(t,e,r={})=>{if(au(t))return t.bindTools(e,r);if(Ee.isRunnableBinding(t)&&au(t.bound)){let n=t.bound.bindTools(e,r);return Ee.isRunnableBinding(n)?new Ee({bound:n.bound,config:{...t.config,...n.config},kwargs:{...t.kwargs,...n.kwargs},configFactories:n.configFactories??t.configFactories}):new Ee({bound:n,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function ws(t){if(typeof t=="function")return;let e=t;if(bt.isRunnableSequence(e)&&(e=e.steps.find(r=>Ee.isRunnableBinding(r))||e),!Lr(e)){if(Ee.isRunnableBinding(e)){let r=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,n=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(r||n)throw new hs}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new hs}}function Ua(t){return!!($.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function uu(t){if(t==null)return new Ie("");if(Ie.isInstance(t))return t;if(typeof t=="string")return new Ie({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function cu(t,e,r={}){let n=qa(t,e,r);if(n)return n;if(Lr(t)){let o=qa(await t._getModelInstance(),e,r);if(o)return o}if(bt.isRunnableSequence(t)){let o=t.steps.findIndex(s=>Ee.isRunnableBinding(s)||bo(s)||Lr(s));if(o>=0){let s=qa(t.steps[o],e,r);if(s){let a=t.steps.slice();return a.splice(o,1,s),bt.from(a)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Xp(t){if(t.length===0)return;if(t.length===1)return t[0];function e(n,o){return async(s,a)=>n(s,async u=>o(u,a))}let r=t[t.length-1];for(let n=t.length-2;n>=0;n--)r=e(t[n],r);return r}function du(t){let e=t.filter(r=>r.wrapToolCall);if(e.length!==0)return Xp(e.map(r=>{let n=r.wrapToolCall;return async(s,a)=>{let i=s.state,u=async l=>{let c={...i,...l.state};return a({...l,state:c})};try{let l=await n({...s,state:{messages:i.messages,...r.stateSchema?Yp(r.stateSchema,{...i}):{}}},u);if(!B.isInstance(l)&&!ce(l))throw new Error(`Invalid response from "wrapToolCall" in middleware "${r.name}": expected ToolMessage or Command, got ${typeof l}`);return l}catch(l){throw _o.wrap(l,r.name)}}}))}async function pu(t,e){let r={};for(let n of t){if(!n.stateSchema)continue;let o=n.stateSchema;if(ve.isInstance(n.stateSchema)){let i={};for(let[u,l]of Object.entries(n.stateSchema.fields))xt.isInstance(l)?i[u]=l.inputSchema||l.valueSchema:i[u]=l;o=I.object(i)}let s=await Ol(Rl(o,i=>i.startsWith("_")),e);if(s.success){Object.assign(r,s.data);continue}let a=s.error.issues.filter(i=>i.code==="invalid_type").map(i=>` - ${i.path.join(".")}: Required`).join(`
15
15
  `);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
16
16
  ${a}
17
17
 
@@ -30,9 +30,9 @@ To fix this, either:
30
30
  agent.invoke({
31
31
  messages: [...],
32
32
  ${s.error.issues[0]?.path.join(".")}: "value"
33
- })`)}return r}function eu(t){let e={messages:x.custom(()=>[]),structuredResponse:x.any().optional()};if(!t)return x.object(e);let r;if(Ie.isInstance(t)){r={};for(let[o,s]of Object.entries(t.fields))bt.isInstance(s)?r[o]=s.inputSchema||s.valueSchema:r[o]=s}else r=ss(t);let n={...e};for(let[o,s]of Object.entries(r))o.startsWith("_")?n[o]=s.optional():n[o]=s;return x.object(n)}function tu(t){if(rt(t))return vl(t);if(Ie.isInstance(t)){let e={};for(let[r,n]of Object.entries(t.fields)){let o;bt.isInstance(n)?o=n.inputSchema||n.valueSchema:o=n,e[r]=Pr(o)?o.optional():x.any().optional()}return x.object(e)}return x.object({})}function Oe(t){if(t){if(["model_request","tools",B].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return B;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function ys(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var jr=class extends Rr{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){let r=De(this.config,e),n=await ns.runWithConfig(r,async()=>this.func(t,r));return Rr.isRunnable(n)&&this.recurse?await ns.runWithConfig(r,async()=>n.invoke(t,r)):(this.#e=n,n)}};function ru(t,e){let r,n;if(e==="inline")r=Hl,n=Jl;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function o(s){return s.map(r)}return wt.from([Ue.from(o),t,Ue.from(n)])}function qp(t){return R.isInstance(t)||ue(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}var ae="model_request",nu=class extends jr{#e;#r;constructor(t){super({name:t.name??"model",func:(e,r)=>this.#t(e,r)}),this.#e=t,this.#r=t.systemMessage}async#s(t,e=this.#e.responseFormat){if(!e)return;let r;Nr(t)?r=await t._getModelInstance():typeof t!="string"&&(r=t);let n=Bl(e,void 0,r);if(n.length!==0)return n.every(o=>o instanceof xt)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(o=>o instanceof Ee).reduce((o,s)=>(o[s.name]=s,o),{})}}async#t(t,e){let r=t.messages.at(-1);if(r&&q.isInstance(r)&&r.name&&this.#e.shouldReturnDirect.has(r.name))return[new ne({update:{messages:[]}})];let{response:n,lastAiMessage:o,collectedCommands:s}=await this.#a(t,e);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:l}=n;return{messages:[...t.messages,...l],structuredResponse:u}}let a=[],i=R.isInstance(n)?n:o;return i&&(i.name=this.name,i.lc_kwargs.name=this.name,this.#o(t,i)?a.push(new ne({update:{messages:[new R({content:"Sorry, need more steps to process this request.",name:this.name,id:i.id})]}})):a.push(new ne({update:{messages:[i]}}))),ue(n)&&!s.includes(n)&&a.push(n),a.push(...s),a}#n(){if(typeof this.#e.model=="string")return At(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(t,e,r={}){let n=await this.#n(),o=e,s=this.#r,a=null,i=[],u=async m=>{gs(m.model);let h=await this.#s(m.model,m.responseFormat),_=await this.#c(m.model,m,h),I=[...s.text===""?[]:[s],...m.messages],C=ys(this.#e.signal,e.signal),g=await yl(_.invoke(I,{...e,signal:C}),C);if(a=g,h?.type==="native"){let L=h.strategy.parse(g);return L?{structuredResponse:L,messages:[g]}:g}if(!h||!g.tool_calls)return g;let A=g.tool_calls.filter(L=>L.name in h.tools);if(A.length===0)return g;if(A.length>1)return this.#l(g,A,h);let k=h.tools[A[0].name]?.options?.toolMessageContent;return this.#u(g,A[0],h,k??r.lastMessage)},l=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let m=l.length-1;m>=0;m--){let[h,_]=l[m];if(h.wrapModelCall){let I=c,C=h,g=_;c=async A=>{let k=s,L=C.contextSchema?_t(C.contextSchema,o?.context||{}):o?.context,Q=Object.freeze({context:L,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal}),G={...A,state:{...h.stateSchema?_t(tu(h.stateSchema),t):{},...g(),messages:t.messages},runtime:Q},K=async z=>{s=k;let T=z.tools??[],E=new Map(this.#e.toolClasses.filter(Ht).map(fe=>[fe.name,fe])),F=T.filter(fe=>Ht(fe)&&!E.has(fe.name)),J=T.filter(fe=>{if(!Ht(fe))return!1;let el=E.get(fe.name);return el!=null&&el!==fe});if(F.length>0&&!this.#e.middleware?.some(fe=>fe.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${C.name}": ${F.map(fe=>fe.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(J.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${C.name}": ${J.map(fe=>fe.name).join(", ")}. This is not supported.`);let Z=z,N=z.systemPrompt!==s.text,W=z.systemMessage!==s;if(N&&W)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");N&&(s=new xe({content:[{type:"text",text:z.systemPrompt}]}),Z={...z,systemPrompt:s.text,systemMessage:s}),W&&(s=new xe({...z.systemMessage}),Z={...z,systemPrompt:s.text,systemMessage:s});let Qo=await I(Z);return ue(Qo)&&a?(i.includes(Qo)||i.push(Qo),a):Qo};if(!C.wrapModelCall)return K(G);try{let z=await C.wrapModelCall(G,K);if(!qp(z))throw new Error(`Invalid response from "wrapModelCall" in middleware "${C.name}": expected AIMessage or Command, got ${typeof z}`);return R.isInstance(z)?a=z:ue(z)&&i.push(z),z}catch(z){throw go.wrap(z,C.name)}}}}s=this.#r;let p={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:o?.context,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal})};return{response:await c(p),lastAiMessage:a,collectedCommands:i}}#l(t,e,r){let n=new fs(e.map(o=>o.name));return this.#i(n,t,e[0],r)}#u(t,e,r,n){let o=r.tools[e.name];try{let s=o.parse(e.args);return{structuredResponse:s,messages:[t,new q({tool_call_id:e.id??"",content:JSON.stringify(s),name:e.name}),new R(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#i(s,t,e,r)}}async#i(t,e,r,n){let o=Object.values(n.tools).at(0)?.options?.handleError,s=r.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(o===!1)throw t;if(o===void 0||typeof o=="boolean"&&o||Array.isArray(o)&&o.some(a=>a instanceof fs))return new ne({update:{messages:[e,new q({content:t.message,tool_call_id:s})]},goto:ae});if(typeof o=="string")return new ne({update:{messages:[e,new q({content:o,tool_call_id:s})]},goto:ae});if(typeof o=="function"){let a=await o(t);if(typeof a!="string")throw new Error("Error handler must return a string.");return new ne({update:{messages:[e,new q({content:a,tool_call_id:s})]},goto:ae})}return new ne({update:{messages:[e,new q({content:t.message,tool_call_id:s})]},goto:ae})}#o(t,e){let r=R.isInstance(e)&&e.tool_calls?.every(o=>this.#e.shouldReturnDirect.has(o.name)),n="remainingSteps"in t?t.remainingSteps:void 0;return!!(n&&(n<1&&r||n<2&&ja(t.messages.at(-1))))}async#c(t,e,r){let n={},o=Object.values(r&&"tools"in r?r.tools:{}),s=[...e?.tools??this.#e.toolClasses,...o.map(u=>u.tool)],a=e?.toolChoice||(o.length>0?"any":void 0);if(r?.type==="native"){let u=e?.modelSettings?.strict??r?.strategy?.strict??!0,l={name:r.strategy.schema?.name??"extract",description:os(r.strategy.schema),schema:r.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:l},outputConfig:{format:{type:"json_schema",schema:r.strategy.schema}},responseSchema:r.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:r.strategy.schema},strict:u})}let i=await Ql(t,s,{...n,...e?.modelSettings,tool_choice:a});return this.#e.includeAgentName==="inline"?ru(i,this.#e.includeAgentName):i}getState(){let t=super.getState();return{messages:[],...t&&!ue(t)?t:{}}}};var ou=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,_e="tools",su=t=>Array.isArray(t)&&t.every(Aa.isInstance),Bp=t=>typeof t=="object"&&t!=null&&"messages"in t&&su(t.messages),Kp=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Wp(t,e){return t instanceof hs?new q({content:t.message,tool_call_id:e.id,name:e.name}):new q({content:`${t}
34
- Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var au=class extends jr{tools;trace=!1;signal;handleToolErrors=Wp;wrapToolCall;constructor(t,e){let{name:r,tags:n,handleToolErrors:o,signal:s,wrapToolCall:a}=e??{};super({name:r,tags:n,func:(i,u)=>this.run(i,u)}),this.options=e,this.tools=t,this.handleToolErrors=o??this.handleToolErrors,this.signal=s,this.wrapToolCall=a}#e(t,e,r){if(ao(t)||this.signal?.aborted||r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(t,e);if(n&&q.isInstance(n))return n;throw t}else if(this.handleToolErrors)return new q({name:e.name,content:`${t}
35
- Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,r){let n=e,o={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===t.name),a=async u=>{let{toolCall:l,tool:c}=u,p=c??this.tools.find(h=>h.name===l.name);if(p===void 0){let h=this.tools.map(_=>_.name);return new q({content:ou(l.name,h),tool_call_id:l.id,name:l.name,status:"error"})}let m=p;try{let h=await m.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:ys(this.signal,e.signal)});return q.isInstance(h)||ue(h)?h:new q({name:m.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:l.id})}catch(h){throw h instanceof pl?new hs(h,l):h}},i={toolCall:t,tool:s,state:r,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(i,a)}catch(u){return this.#e(u,t,!0)}if(!s){let u=this.tools.map(l=>l.name);return new q({content:ou(t.name,u),tool_call_id:t.id,name:t.name,status:"error"})}try{return await a(i)}catch(u){return this.#e(u,t,!1)}}async run(t,e){let r;if(Kp(t)){let{lg_tool_call:s,jumpTo:a,...i}=t;r=[await this.runTool(t.lg_tool_call,e,i)]}else{let s;if(su(t))s=t;else if(Bp(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(R.isInstance(l)){i=l;break}}if(!R.isInstance(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===ne.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Vp(a))?o?o.goto.push(...s.goto):o=new ne({graph:ne.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};function Vp(t){return t instanceof ge}var Gp=class{},Hp=class{},Tt=class extends jr{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let r={};if(this.middleware.contextSchema){let u=this.middleware.contextSchema?.shape;if(u){let l={},c=e?.context||{};for(let p of Object.keys(u))p in c&&(l[p]=c[p]);r=_t(this.middleware.contextSchema,l)}}let n={...this.#e.getState(),...t,messages:t.messages},o={context:r,store:e?.store,configurable:e?.configurable,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new Hp,{...o,context:Object.freeze(Object.assign(new Gp,r))})));if(!s)return{jumpTo:void 0};let a,i;if(this.name?.startsWith("BeforeAgentNode_")?(a=qe(this.middleware.beforeAgent),i="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=qe(this.middleware.beforeModel),i="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=qe(this.middleware.afterAgent),i="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=qe(this.middleware.afterModel),i="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:i?`no ${i} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:eu(this.middleware.stateSchema)}}};var iu=class extends Tt{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return It(this.middleware.beforeAgent)(t,e)}};var lu=class extends Tt{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return It(this.middleware.beforeModel)(t,e)}};var uu=class extends Tt{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return It(this.middleware.afterModel)(t,e)}};var cu=class extends Tt{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return It(this.middleware.afterAgent)(t,e)}};var du=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){let e=(this.#e.get(t)??[]).reduce((r,n)=>({...r,...n.getState()??{}}),{});return delete e.jumpTo,e}};var pu=class mu{#e;#r="v2";#s;#t=new du;#n;constructor(e,r){if(this.options=e,this.#n=De(r??{},{metadata:{ls_integration:"langchain_create_agent"}}),e.name&&(this.#n=De(this.#n,{metadata:{lc_agent_name:e.name}})),this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&gs(e.model);let n=this.options.middleware?.filter(T=>T.tools).flatMap(T=>T.tools)??[],o=[...e.tools??[],...n],s=new Set(o.filter(Ht).filter(T=>"returnDirect"in T&&T.returnDirect).map(T=>T.name)),a=!!this.options.middleware?.some(T=>T.wrapModelCall),{state:i,input:u,output:l}=Vl(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new ye(i,{input:u,output:l,context:this.options.contextSchema}),p=[],m=[],h=[],_=[],I=[];this.#s=new nu({model:this.options.model,systemMessage:Zl(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:o,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:I});let C=new Set,g=this.options.middleware??[];for(let T=0;T<g.length;T++){let E,F,J,Z,N=g[T];if(C.has(N.name))throw new Error(`Middleware ${N.name} is defined multiple times`);if(C.add(N.name),N.beforeAgent){E=new iu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,E);let W=`${N.name}.before_agent`;p.push({index:T,name:W,allowed:qe(N.beforeAgent)}),c.addNode(W,E,E.nodeOptions)}if(N.beforeModel){F=new lu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,F);let W=`${N.name}.before_model`;m.push({index:T,name:W,allowed:qe(N.beforeModel)}),c.addNode(W,F,F.nodeOptions)}if(N.afterModel){J=new uu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,J);let W=`${N.name}.after_model`;h.push({index:T,name:W,allowed:qe(N.afterModel)}),c.addNode(W,J,J.nodeOptions)}if(N.afterAgent){Z=new cu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,Z);let W=`${N.name}.after_agent`;_.push({index:T,name:W,allowed:qe(N.afterAgent)}),c.addNode(W,Z,Z.nodeOptions)}N.wrapModelCall&&I.push([N,()=>this.#t.getState(N.name)])}c.addNode(ae,this.#s);let A=g.some(T=>T.wrapToolCall),k=o.filter(Ht);if(k.length>0||A){let T=new au(k,{signal:this.options.signal,wrapToolCall:Yl(g)});c.addNode(_e,T)}let L;p.length>0?L=p[0].name:m.length>0?L=m[0].name:L=ae;let Q=m.length>0?m[0].name:ae,G=_.length>0?_[_.length-1].name:B;c.addEdge(he,L);let K=k.length>0||A;for(let T=0;T<p.length;T++){let E=p[T],F=E.name,J=T===p.length-1?Q:p[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),N=Array.from(new Set([J,...Z.map(W=>W===B?G:W)]));c.addConditionalEdges(F,this.#c(k,J,G,K),N)}else c.addEdge(F,J)}for(let T=0;T<m.length;T++){let E=m[T],F=E.name,J=T===m.length-1?ae:m[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),N=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#p(k,J,K),N)}else c.addEdge(F,J)}let z=h.at(-1);if(h.length>0&&z)c.addEdge(ae,z.name);else{let T=this.#a(k,!1,K).map(E=>E===B?G:E);T.length===1?c.addEdge(ae,T[0]):c.addConditionalEdges(ae,this.#u(G),T)}for(let T=h.length-1;T>0;T--){let E=h[T],F=E.name,J=h[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),N=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(k,E.allowed,J,K),N)}else c.addEdge(F,J)}if(h.length>0){let T=h[0],E=T.name,F=this.#a(k,!0,K).filter(N=>N!=="tools"||K),J=!!(T.allowed&&T.allowed.length>0),Z=F.map(N=>N===B?G:N);c.addConditionalEdges(E,this.#i(k,J,G,K),Z)}for(let T=_.length-1;T>0;T--){let E=_[T],F=E.name,J=_[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),N=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(k,E.allowed,J,K),N)}else c.addEdge(F,J)}if(_.length>0){let T=_[0],E=T.name;if(T.allowed&&T.allowed.length>0){let F=T.allowed.map(Z=>Oe(Z)).filter(Z=>Z!=="tools"||K),J=Array.from(new Set([B,...F]));c.addConditionalEdges(E,this.#o(k,T.allowed,B,K),J)}else c.addEdge(E,B)}if(K){let T=Q;s.size>0?c.addConditionalEdges(_e,this.#l(s,G,T),[T,G]):c.addEdge(_e,T)}this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(e){this.#e.checkpointer=e}get store(){return this.#e.store}set store(e){this.#e.store=e}withConfig(e){return new mu(this.options,De(this.#n,e))}#a(e,r=!1,n=e.length>0){let o=[];return n&&o.push(_e),r&&o.push(ae),o.push(B),o}#l(e,r,n){return o=>{let s=o.messages,a=s[s.length-1];return q.isInstance(a)&&a.name&&e.has(a.name)?this.options.responseFormat?n:r:n}}#u(e=B){return r=>{let n=r.messages.at(-1);if(!R.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return e;if(this.#r==="v1")return _e;let o=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return o.length===0?e:o.map(s=>new ge(_e,{...r,lg_tool_call:s}))}}#i(e,r,n,o=e.length>0){let s=!!this.options.responseFormat;return a=>{let i=a,u=i.messages,l=u.at(-1);if(R.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(r&&i.jumpTo){let g=Oe(i.jumpTo);return g===B?n:g==="tools"?o?new ge(_e,{...a,jumpTo:void 0}):n:new ge(ae,{...a,jumpTo:void 0})}let c=u.filter(q.isInstance),p=u.filter(R.isInstance).at(-1),m=p?.tool_calls?.filter(g=>!c.some(A=>A.tool_call_id===g.id));if(m&&m.length>0)return this.#r==="v1"?_e:m.map(g=>new ge(_e,{...a,lg_tool_call:g}));let h=p?.tool_calls?.some(g=>g.name.startsWith("extract-"));if(m&&m.length===0&&!h&&s)return ae;if(!R.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;let _=l.tool_calls.every(g=>g.name.startsWith("extract-")),I=l.tool_calls.some(g=>!g.name.startsWith("extract-"));if(_||!I)return n;if(this.#r==="v1")return _e;let C=l.tool_calls.filter(g=>!g.name.startsWith("extract-"));return C.length===0?n:C.map(g=>new ge(_e,{...a,lg_tool_call:g}))}}#o(e,r,n,o=e.length>0){let s=new Set(r.map(a=>Oe(a)));return a=>{let i=a;if(i.jumpTo){let u=Oe(i.jumpTo);if(u===B&&s.has(B))return B;if(u==="tools"&&s.has("tools"))return o?new ge(_e,{...a,jumpTo:void 0}):B;if(u==="model_request"&&s.has("model_request"))return new ge(ae,{...a,jumpTo:void 0})}return n}}#c(e,r,n,o=e.length>0){return s=>{let a=s;if(!a.jumpTo)return r;let i=Oe(a.jumpTo);return i===B?n:i==="tools"?o?new ge(_e,{...s,jumpTo:void 0}):n:new ge(ae,{...s,jumpTo:void 0})}}#p(e,r,n=e.length>0){return o=>{let s=o;if(!s.jumpTo)return r;let a=Oe(s.jumpTo);return a===B?B:a==="tools"?n?new ge(_e,{...o,jumpTo:void 0}):B:new ge(ae,{...o,jumpTo:void 0})}}async#d(e,r){if(!this.options.middleware||this.options.middleware.length===0||e instanceof ne||!e)return e;let n=await Xl(this.options.middleware,e),o={...(await this.#e.getState(r).catch(()=>({values:{}}))).values,...e};if(!o)return o;for(let[s,a]of Object.entries(n))s in o||(o[s]=a);return o}async invoke(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.invoke(o,n)}async stream(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.stream(o,n)}async drawMermaidPng(e){let r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,r,n){let o=De(this.#n,r);return this.#e.streamEvents(e,{...o,version:r?.version??"v2"},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,r){return this.#e.getState(e,r)}getStateHistory(e,r){return this.#e.getStateHistory(e,r)}getSubgraphs(e,r){return this.#e.getSubgraphs(e,r)}getSubgraphsAsync(e,r){return this.#e.getSubgraphsAsync(e,r)}updateState(e,r,n){return this.#e.updateState(e,r,n)}get builder(){return this.#e.builder}};function _o(t){return new pu(t)}var Jp=b.function().args(b.custom(),b.custom(),b.custom()).returns(b.union([b.string(),b.promise(b.string())])),Zp=["approve","edit","reject"],Qp=b.enum(Zp),Yp=b.object({allowedDecisions:b.array(Qp),description:b.union([b.string(),Jp]).optional(),argsSchema:b.record(b.any()).optional()}),lv=b.object({interruptOn:b.record(b.union([b.boolean(),Yp])).optional(),descriptionPrefix:b.string().default("Tool execution requires approval")});var rm=`<role>
33
+ })`)}return r}function mu(t){let e={messages:I.custom(()=>[]),structuredResponse:I.any().optional()};if(!t)return I.object(e);let r;if(ve.isInstance(t)){r={};for(let[o,s]of Object.entries(t.fields))xt.isInstance(s)?r[o]=s.inputSchema||s.valueSchema:r[o]=s}else r=is(t);let n={...e};for(let[o,s]of Object.entries(r))o.startsWith("_")?n[o]=s.optional():n[o]=s;return I.object(n)}function fu(t){if(rt(t))return Pl(t);if(ve.isInstance(t)){let e={};for(let[r,n]of Object.entries(t.fields)){let o;xt.isInstance(n)?o=n.inputSchema||n.valueSchema:o=n,e[r]=$r(o)?o.optional():I.any().optional()}return I.object(e)}return I.object({})}function Oe(t){if(t){if(["model_request","tools",q].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return q;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function _s(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var Dr=class extends Nr{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){let r=De(this.config,e),n=await ss.runWithConfig(r,async()=>this.func(t,r));return Nr.isRunnable(n)&&this.recurse?await ss.runWithConfig(r,async()=>n.invoke(t,r)):(this.#e=n,n)}};function hu(t,e){let r,n;if(e==="inline")r=iu,n=lu;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function o(s){return s.map(r)}return bt.from([qe.from(o),t,qe.from(n)])}function em(t){return $.isInstance(t)||ce(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}var ae="model_request",gu=class extends Dr{#e;#r;constructor(t){super({name:t.name??"model",func:(e,r)=>this.#t(e,r)}),this.#e=t,this.#r=t.systemMessage}async#s(t,e=this.#e.responseFormat){if(!e)return;let r;Lr(t)?r=await t._getModelInstance():typeof t!="string"&&(r=t);let n=ru(e,void 0,r);if(n.length!==0)return n.every(o=>o instanceof It)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(o=>o instanceof Me).reduce((o,s)=>(o[s.name]=s,o),{})}}async#t(t,e){let r=t.messages.at(-1);if(r&&B.isInstance(r)&&r.name&&this.#e.shouldReturnDirect.has(r.name))return[new re({update:{messages:[]}})];let{response:n,lastAiMessage:o,collectedCommands:s}=await this.#a(t,e);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:l}=n;return{messages:[...t.messages,...l],structuredResponse:u}}let a=[],i=$.isInstance(n)?n:o;return i&&(i.name=this.name,i.lc_kwargs.name=this.name,this.#o(t,i)?a.push(new re({update:{messages:[new $({content:"Sorry, need more steps to process this request.",name:this.name,id:i.id})]}})):a.push(new re({update:{messages:[i]}}))),ce(n)&&!s.includes(n)&&a.push(n),a.push(...s),a}#n(){if(typeof this.#e.model=="string")return At(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(t,e,r={}){let n=await this.#n(),o=e,s=this.#r,a=null,i=[],u=async m=>{ws(m.model);let h=await this.#s(m.model,m.responseFormat),y=await this.#c(m.model,m,h),A=[...s.text===""?[]:[s],...m.messages],C=_s(this.#e.signal,e.signal),g=await Tl(y.invoke(A,{...e,signal:C}),C);if(a=g,h?.type==="native"){let z=h.strategy.parse(g);return z?{structuredResponse:z,messages:[g]}:g}if(!h||!g.tool_calls)return g;let b=g.tool_calls.filter(z=>z.name in h.tools);if(b.length===0)return g;if(b.length>1)return this.#l(g,b,h);let k=h.tools[b[0].name]?.options?.toolMessageContent;return this.#u(g,b[0],h,k??r.lastMessage)},l=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let m=l.length-1;m>=0;m--){let[h,y]=l[m];if(h.wrapModelCall){let A=c,C=h,g=y;c=async b=>{let k=s,z=C.contextSchema?_t(C.contextSchema,o?.context||{}):o?.context,Q=Object.freeze({context:z,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal}),V={...b,state:{...h.stateSchema?_t(fu(h.stateSchema),t):{},...g(),messages:t.messages},runtime:Q},K=async L=>{s=k;let T=L.tools??[],E=new Map(this.#e.toolClasses.filter(Jt).map(ye=>[ye.name,ye])),F=T.filter(ye=>Jt(ye)&&!E.has(ye.name)),J=T.filter(ye=>{if(!Jt(ye))return!1;let ll=E.get(ye.name);return ll!=null&&ll!==ye});if(F.length>0&&!this.#e.middleware?.some(ye=>ye.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${C.name}": ${F.map(ye=>ye.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(J.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${C.name}": ${J.map(ye=>ye.name).join(", ")}. This is not supported.`);let Z=L,N=L.systemPrompt!==s.text,G=L.systemMessage!==s;if(N&&G)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");N&&(s=new Ie({content:[{type:"text",text:L.systemPrompt}]}),Z={...L,systemPrompt:s.text,systemMessage:s}),G&&(s=new Ie({...L.systemMessage}),Z={...L,systemPrompt:s.text,systemMessage:s});let Xo=await A(Z);return ce(Xo)&&a?(i.includes(Xo)||i.push(Xo),a):Xo};if(!C.wrapModelCall)return K(V);try{let L=await C.wrapModelCall(V,K);if(!em(L))throw new Error(`Invalid response from "wrapModelCall" in middleware "${C.name}": expected AIMessage or Command, got ${typeof L}`);return $.isInstance(L)?a=L:ce(L)&&i.push(L),L}catch(L){throw _o.wrap(L,C.name)}}}}s=this.#r;let p={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:o?.context,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal})};return{response:await c(p),lastAiMessage:a,collectedCommands:i}}#l(t,e,r){let n=new gs(e.map(o=>o.name));return this.#i(n,t,e[0],r)}#u(t,e,r,n){let o=r.tools[e.name];try{let s=o.parse(e.args);return{structuredResponse:s,messages:[t,new B({tool_call_id:e.id??"",content:JSON.stringify(s),name:e.name}),new $(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#i(s,t,e,r)}}async#i(t,e,r,n){let o=Object.values(n.tools).at(0)?.options?.handleError,s=r.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(o===!1)throw t;if(o===void 0||typeof o=="boolean"&&o||Array.isArray(o)&&o.some(a=>a instanceof gs))return new re({update:{messages:[e,new B({content:t.message,tool_call_id:s})]},goto:ae});if(typeof o=="string")return new re({update:{messages:[e,new B({content:o,tool_call_id:s})]},goto:ae});if(typeof o=="function"){let a=await o(t);if(typeof a!="string")throw new Error("Error handler must return a string.");return new re({update:{messages:[e,new B({content:a,tool_call_id:s})]},goto:ae})}return new re({update:{messages:[e,new B({content:t.message,tool_call_id:s})]},goto:ae})}#o(t,e){let r=$.isInstance(e)&&e.tool_calls?.every(o=>this.#e.shouldReturnDirect.has(o.name)),n="remainingSteps"in t?t.remainingSteps:void 0;return!!(n&&(n<1&&r||n<2&&Ua(t.messages.at(-1))))}async#c(t,e,r){let n={},o=Object.values(r&&"tools"in r?r.tools:{}),s=[...e?.tools??this.#e.toolClasses,...o.map(u=>u.tool)],a=e?.toolChoice||(o.length>0?"any":void 0);if(r?.type==="native"){let u=e?.modelSettings?.strict??r?.strategy?.strict??!0,l={name:r.strategy.schema?.name??"extract",description:as(r.strategy.schema),schema:r.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:l},outputConfig:{format:{type:"json_schema",schema:r.strategy.schema}},responseSchema:r.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:r.strategy.schema},strict:u})}let i=await cu(t,s,{...n,...e?.modelSettings,tool_choice:a});return this.#e.includeAgentName==="inline"?hu(i,this.#e.includeAgentName):i}getState(){let t=super.getState();return{messages:[],...t&&!ce(t)?t:{}}}};var yu=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,be="tools",wu=t=>Array.isArray(t)&&t.every(ka.isInstance),tm=t=>typeof t=="object"&&t!=null&&"messages"in t&&wu(t.messages),rm=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function nm(t,e){return t instanceof ys?new B({content:t.message,tool_call_id:e.id,name:e.name}):new B({content:`${t}
34
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var _u=class extends Dr{tools;trace=!1;signal;handleToolErrors=nm;wrapToolCall;constructor(t,e){let{name:r,tags:n,handleToolErrors:o,signal:s,wrapToolCall:a}=e??{};super({name:r,tags:n,func:(i,u)=>this.run(i,u)}),this.options=e,this.tools=t,this.handleToolErrors=o??this.handleToolErrors,this.signal=s,this.wrapToolCall=a}#e(t,e,r){if(co(t)||this.signal?.aborted||r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(t,e);if(n&&B.isInstance(n))return n;throw t}else if(this.handleToolErrors)return new B({name:e.name,content:`${t}
35
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,r){let n=e,o={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===t.name),a=async u=>{let{toolCall:l,tool:c}=u,p=c??this.tools.find(h=>h.name===l.name);if(p===void 0){let h=this.tools.map(y=>y.name);return new B({content:yu(l.name,h),tool_call_id:l.id,name:l.name,status:"error"})}let m=p;try{let h=await m.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:_s(this.signal,e.signal)});return B.isInstance(h)||ce(h)?h:new B({name:m.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:l.id})}catch(h){throw h instanceof bl?new ys(h,l):h}},i={toolCall:t,tool:s,state:r,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(i,a)}catch(u){return this.#e(u,t,!0)}if(!s){let u=this.tools.map(l=>l.name);return new B({content:yu(t.name,u),tool_call_id:t.id,name:t.name,status:"error"})}try{return await a(i)}catch(u){return this.#e(u,t,!1)}}async run(t,e){let r;if(rm(t)){let{lg_tool_call:s,jumpTo:a,...i}=t;r=[await this.runTool(t.lg_tool_call,e,i)]}else{let s;if(wu(t))s=t;else if(tm(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if($.isInstance(l)){i=l;break}}if(!$.isInstance(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(ce))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ce(s)?s.graph===re.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>om(a))?o?o.goto.push(...s.goto):o=new re({graph:re.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};function om(t){return t instanceof we}var sm=class{},am=class{},St=class extends Dr{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let r={};if(this.middleware.contextSchema){let u=this.middleware.contextSchema?.shape;if(u){let l={},c=e?.context||{};for(let p of Object.keys(u))p in c&&(l[p]=c[p]);r=_t(this.middleware.contextSchema,l)}}let n={...this.#e.getState(),...t,messages:t.messages},o={context:r,store:e?.store,configurable:e?.configurable,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new am,{...o,context:Object.freeze(Object.assign(new sm,r))})));if(!s)return{jumpTo:void 0};let a,i;if(this.name?.startsWith("BeforeAgentNode_")?(a=Ue(this.middleware.beforeAgent),i="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=Ue(this.middleware.beforeModel),i="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=Ue(this.middleware.afterAgent),i="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=Ue(this.middleware.afterModel),i="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:i?`no ${i} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:mu(this.middleware.stateSchema)}}};var bu=class extends St{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.beforeAgent)(t,e)}};var xu=class extends St{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.beforeModel)(t,e)}};var Au=class extends St{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.afterModel)(t,e)}};var Iu=class extends St{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.afterAgent)(t,e)}};var vu=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){let e=(this.#e.get(t)??[]).reduce((r,n)=>({...r,...n.getState()??{}}),{});return delete e.jumpTo,e}};var Tu=class Su{#e;#r="v2";#s;#t=new vu;#n;constructor(e,r){if(this.options=e,this.#n=De(r??{},{metadata:{ls_integration:"langchain_create_agent"}}),e.name&&(this.#n=De(this.#n,{metadata:{lc_agent_name:e.name}})),this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&ws(e.model);let n=this.options.middleware?.filter(T=>T.tools).flatMap(T=>T.tools)??[],o=[...e.tools??[],...n],s=new Set(o.filter(Jt).filter(T=>"returnDirect"in T&&T.returnDirect).map(T=>T.name)),a=!!this.options.middleware?.some(T=>T.wrapModelCall),{state:i,input:u,output:l}=su(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new de(i,{input:u,output:l,context:this.options.contextSchema}),p=[],m=[],h=[],y=[],A=[];this.#s=new gu({model:this.options.model,systemMessage:uu(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:o,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:A});let C=new Set,g=this.options.middleware??[];for(let T=0;T<g.length;T++){let E,F,J,Z,N=g[T];if(C.has(N.name))throw new Error(`Middleware ${N.name} is defined multiple times`);if(C.add(N.name),N.beforeAgent){E=new bu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,E);let G=`${N.name}.before_agent`;p.push({index:T,name:G,allowed:Ue(N.beforeAgent)}),c.addNode(G,E,E.nodeOptions)}if(N.beforeModel){F=new xu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,F);let G=`${N.name}.before_model`;m.push({index:T,name:G,allowed:Ue(N.beforeModel)}),c.addNode(G,F,F.nodeOptions)}if(N.afterModel){J=new Au(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,J);let G=`${N.name}.after_model`;h.push({index:T,name:G,allowed:Ue(N.afterModel)}),c.addNode(G,J,J.nodeOptions)}if(N.afterAgent){Z=new Iu(N,{getState:()=>this.#t.getState(N.name)}),this.#t.addNode(N,Z);let G=`${N.name}.after_agent`;y.push({index:T,name:G,allowed:Ue(N.afterAgent)}),c.addNode(G,Z,Z.nodeOptions)}N.wrapModelCall&&A.push([N,()=>this.#t.getState(N.name)])}c.addNode(ae,this.#s);let b=g.some(T=>T.wrapToolCall),k=o.filter(Jt);if(k.length>0||b){let T=new _u(k,{signal:this.options.signal,wrapToolCall:du(g)});c.addNode(be,T)}let z;p.length>0?z=p[0].name:m.length>0?z=m[0].name:z=ae;let Q=m.length>0?m[0].name:ae,V=y.length>0?y[y.length-1].name:q;c.addEdge(ue,z);let K=k.length>0||b;for(let T=0;T<p.length;T++){let E=p[T],F=E.name,J=T===p.length-1?Q:p[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(G=>Oe(G)).filter(G=>G!=="tools"||K),N=Array.from(new Set([J,...Z.map(G=>G===q?V:G)]));c.addConditionalEdges(F,this.#c(k,J,V,K),N)}else c.addEdge(F,J)}for(let T=0;T<m.length;T++){let E=m[T],F=E.name,J=T===m.length-1?ae:m[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(G=>Oe(G)).filter(G=>G!=="tools"||K),N=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#p(k,J,K),N)}else c.addEdge(F,J)}let L=h.at(-1);if(h.length>0&&L)c.addEdge(ae,L.name);else{let T=this.#a(k,!1,K).map(E=>E===q?V:E);T.length===1?c.addEdge(ae,T[0]):c.addConditionalEdges(ae,this.#u(V),T)}for(let T=h.length-1;T>0;T--){let E=h[T],F=E.name,J=h[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(G=>Oe(G)).filter(G=>G!=="tools"||K),N=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(k,E.allowed,J,K),N)}else c.addEdge(F,J)}if(h.length>0){let T=h[0],E=T.name,F=this.#a(k,!0,K).filter(N=>N!=="tools"||K),J=!!(T.allowed&&T.allowed.length>0),Z=F.map(N=>N===q?V:N);c.addConditionalEdges(E,this.#i(k,J,V,K),Z)}for(let T=y.length-1;T>0;T--){let E=y[T],F=E.name,J=y[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(G=>Oe(G)).filter(G=>G!=="tools"||K),N=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(k,E.allowed,J,K),N)}else c.addEdge(F,J)}if(y.length>0){let T=y[0],E=T.name;if(T.allowed&&T.allowed.length>0){let F=T.allowed.map(Z=>Oe(Z)).filter(Z=>Z!=="tools"||K),J=Array.from(new Set([q,...F]));c.addConditionalEdges(E,this.#o(k,T.allowed,q,K),J)}else c.addEdge(E,q)}if(K){let T=Q;s.size>0?c.addConditionalEdges(be,this.#l(s,V,T),[T,V]):c.addEdge(be,T)}this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(e){this.#e.checkpointer=e}get store(){return this.#e.store}set store(e){this.#e.store=e}withConfig(e){return new Su(this.options,De(this.#n,e))}#a(e,r=!1,n=e.length>0){let o=[];return n&&o.push(be),r&&o.push(ae),o.push(q),o}#l(e,r,n){return o=>{let s=o.messages,a=s[s.length-1];return B.isInstance(a)&&a.name&&e.has(a.name)?this.options.responseFormat?n:r:n}}#u(e=q){return r=>{let n=r.messages.at(-1);if(!$.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return e;if(this.#r==="v1")return be;let o=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return o.length===0?e:o.map(s=>new we(be,{...r,lg_tool_call:s}))}}#i(e,r,n,o=e.length>0){let s=!!this.options.responseFormat;return a=>{let i=a,u=i.messages,l=u.at(-1);if($.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(r&&i.jumpTo){let g=Oe(i.jumpTo);return g===q?n:g==="tools"?o?new we(be,{...a,jumpTo:void 0}):n:new we(ae,{...a,jumpTo:void 0})}let c=u.filter(B.isInstance),p=u.filter($.isInstance).at(-1),m=p?.tool_calls?.filter(g=>!c.some(b=>b.tool_call_id===g.id));if(m&&m.length>0)return this.#r==="v1"?be:m.map(g=>new we(be,{...a,lg_tool_call:g}));let h=p?.tool_calls?.some(g=>g.name.startsWith("extract-"));if(m&&m.length===0&&!h&&s)return ae;if(!$.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;let y=l.tool_calls.every(g=>g.name.startsWith("extract-")),A=l.tool_calls.some(g=>!g.name.startsWith("extract-"));if(y||!A)return n;if(this.#r==="v1")return be;let C=l.tool_calls.filter(g=>!g.name.startsWith("extract-"));return C.length===0?n:C.map(g=>new we(be,{...a,lg_tool_call:g}))}}#o(e,r,n,o=e.length>0){let s=new Set(r.map(a=>Oe(a)));return a=>{let i=a;if(i.jumpTo){let u=Oe(i.jumpTo);if(u===q&&s.has(q))return q;if(u==="tools"&&s.has("tools"))return o?new we(be,{...a,jumpTo:void 0}):q;if(u==="model_request"&&s.has("model_request"))return new we(ae,{...a,jumpTo:void 0})}return n}}#c(e,r,n,o=e.length>0){return s=>{let a=s;if(!a.jumpTo)return r;let i=Oe(a.jumpTo);return i===q?n:i==="tools"?o?new we(be,{...s,jumpTo:void 0}):n:new we(ae,{...s,jumpTo:void 0})}}#p(e,r,n=e.length>0){return o=>{let s=o;if(!s.jumpTo)return r;let a=Oe(s.jumpTo);return a===q?q:a==="tools"?n?new we(be,{...o,jumpTo:void 0}):q:new we(ae,{...o,jumpTo:void 0})}}async#d(e,r){if(!this.options.middleware||this.options.middleware.length===0||e instanceof re||!e)return e;let n=await pu(this.options.middleware,e),o={...(await this.#e.getState(r).catch(()=>({values:{}}))).values,...e};if(!o)return o;for(let[s,a]of Object.entries(n))s in o||(o[s]=a);return o}async invoke(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.invoke(o,n)}async stream(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.stream(o,n)}async drawMermaidPng(e){let r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,r,n){let o=De(this.#n,r);return this.#e.streamEvents(e,{...o,version:r?.version??"v2"},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,r){return this.#e.getState(e,r)}getStateHistory(e,r){return this.#e.getStateHistory(e,r)}getSubgraphs(e,r){return this.#e.getSubgraphs(e,r)}getSubgraphsAsync(e,r){return this.#e.getSubgraphsAsync(e,r)}updateState(e,r,n){return this.#e.updateState(e,r,n)}get builder(){return this.#e.builder}};function Fr(t){return new Tu(t)}var im=x.function().args(x.custom(),x.custom(),x.custom()).returns(x.union([x.string(),x.promise(x.string())])),lm=["approve","edit","reject"],um=x.enum(lm),cm=x.object({allowedDecisions:x.array(um),description:x.union([x.string(),im]).optional(),argsSchema:x.record(x.any()).optional()}),Hv=x.object({interruptOn:x.record(x.union([x.boolean(),cm])).optional(),descriptionPrefix:x.string().default("Tool execution requires approval")});var fm=`<role>
36
36
  Context Extraction Assistant
37
37
  </role>
38
38
 
@@ -58,23 +58,23 @@ Respond ONLY with the extracted context. Do not include any additional informati
58
58
  <messages>
59
59
  Messages to summarize:
60
60
  {messages}
61
- </messages>`;var nm=b.function().args(b.array(b.custom())).returns(b.union([b.number(),b.promise(b.number())])),La=b.object({fraction:b.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:b.number().positive("Tokens must be greater than 0").optional(),messages:b.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"}),hu=b.object({fraction:b.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:b.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:b.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"}),vv=b.object({model:b.custom(),trigger:b.union([La,b.array(La)]).optional(),keep:hu.optional(),tokenCounter:nm.optional(),summaryPrompt:b.string().default(rm),trimTokensToSummarize:b.number().optional(),summaryPrefix:b.string().optional(),maxTokensBeforeSummary:b.number().optional(),messagesToKeep:b.number().optional()});var $v=b.object({model:b.string().or(b.instanceof(Sl)).optional(),systemPrompt:b.string().optional(),maxTools:b.number().optional(),alwaysInclude:b.array(b.string()).optional()});var Uv=b.object({applyToInput:b.boolean().optional(),applyToOutput:b.boolean().optional(),applyToToolResults:b.boolean().optional()});var Vv=b.object({rules:b.record(b.string(),b.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var om=["continue","error","end"],sm="continue";var am=b.enum(om).default(sm);b.object({toolName:b.string().optional(),threadLimit:b.number().optional(),runLimit:b.number().optional(),exitBehavior:am});var nT=b.object({threadToolCallCount:b.record(b.string(),b.number()).default({}),runToolCallCount:b.record(b.string(),b.number()).default({})});var im=b.enum(["pending","in_progress","completed"]).describe("Status of the todo"),lm=b.object({content:b.string().describe("Content of the todo item"),status:im}),dT=b.object({todos:b.array(lm).default([])});var gT=b.object({threadLimit:b.number().optional(),runLimit:b.number().optional(),exitBehavior:b.enum(["error","end"]).optional()}),yT=b.object({threadModelCallCount:b.number().default(0),runModelCallCount:b.number().default(0)});var _s=b.object({maxRetries:b.number().min(0).default(2),retryOn:b.union([b.function().args(b.instanceof(Error)).returns(b.boolean()),b.array(b.custom())]).default(()=>()=>!0),backoffFactor:b.number().min(0).default(2),initialDelayMs:b.number().min(0).default(1e3),maxDelayMs:b.number().min(0).default(6e4),jitter:b.boolean().default(!0)});var MT=b.object({onFailure:b.union([b.literal("error"),b.literal("continue"),b.function().args(b.instanceof(Error)).returns(b.string())]).default("continue")}).merge(_s);var DT=b.object({tools:b.array(b.union([b.custom(),b.custom(),b.string()])).optional(),onFailure:b.union([b.literal("error"),b.literal("continue"),b.literal("raise"),b.literal("return_message"),b.function().args(b.instanceof(Error)).returns(b.string())]).default("continue")}).merge(_s);var QT=b.object({enableCaching:b.boolean().optional(),ttl:b.enum(["5m","1h"]).optional(),minMessagesToCache:b.number().optional(),unsupportedModelBehavior:b.enum(["ignore","warn","raise"]).optional()});function wo(t,e){return t.lc_error_code=e,t.message=`${t.message}
61
+ </messages>`;var hm=x.function().args(x.array(x.custom())).returns(x.union([x.number(),x.promise(x.number())])),Ba=x.object({fraction:x.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().positive("Tokens must be greater than 0").optional(),messages:x.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Cu=x.object({fraction:x.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:x.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),cT=x.object({model:x.custom(),trigger:x.union([Ba,x.array(Ba)]).optional(),keep:Cu.optional(),tokenCounter:hm.optional(),summaryPrompt:x.string().default(fm),trimTokensToSummarize:x.number().optional(),summaryPrefix:x.string().optional(),maxTokensBeforeSummary:x.number().optional(),messagesToKeep:x.number().optional()});var bT=x.object({model:x.string().or(x.instanceof($l)).optional(),systemPrompt:x.string().optional(),maxTools:x.number().optional(),alwaysInclude:x.array(x.string()).optional()});var kT=x.object({applyToInput:x.boolean().optional(),applyToOutput:x.boolean().optional(),applyToToolResults:x.boolean().optional()});var PT=x.object({rules:x.record(x.string(),x.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var gm=["continue","error","end"],ym="continue";var wm=x.enum(gm).default(ym);x.object({toolName:x.string().optional(),threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:wm});var BT=x.object({threadToolCallCount:x.record(x.string(),x.number()).default({}),runToolCallCount:x.record(x.string(),x.number()).default({})});var _m=x.enum(["pending","in_progress","completed"]).describe("Status of the todo"),bm=x.object({content:x.string().describe("Content of the todo item"),status:_m}),QT=x.object({todos:x.array(bm).default([])});var rS=x.object({threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:x.enum(["error","end"]).optional()}),nS=x.object({threadModelCallCount:x.number().default(0),runModelCallCount:x.number().default(0)});var bs=x.object({maxRetries:x.number().min(0).default(2),retryOn:x.union([x.function().args(x.instanceof(Error)).returns(x.boolean()),x.array(x.custom())]).default(()=>()=>!0),backoffFactor:x.number().min(0).default(2),initialDelayMs:x.number().min(0).default(1e3),maxDelayMs:x.number().min(0).default(6e4),jitter:x.boolean().default(!0)});var yS=x.object({onFailure:x.union([x.literal("error"),x.literal("continue"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(bs);var TS=x.object({tools:x.array(x.union([x.custom(),x.custom(),x.string()])).optional(),onFailure:x.union([x.literal("error"),x.literal("continue"),x.literal("raise"),x.literal("return_message"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(bs);var zS=x.object({enableCaching:x.boolean().optional(),ttl:x.enum(["5m","1h"]).optional(),minMessagesToCache:x.number().optional(),unsupportedModelBehavior:x.enum(["ignore","warn","raise"]).optional()});function xo(t,e){return t.lc_error_code=e,t.message=`${t.message}
62
62
 
63
63
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
64
- `,t}function O(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function w(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 za=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return za=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 bo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Ao=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 S=class extends Error{},Y=class t extends S{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new St({message:n,cause:Ao(r)});let s=r?.error;return e===400?new Lr(e,s,n,o):e===401?new zr(e,s,n,o):e===403?new Dr(e,s,n,o):e===404?new Fr(e,s,n,o):e===409?new Ur(e,s,n,o):e===422?new qr(e,s,n,o):e===429?new Br(e,s,n,o):e>=500?new Kr(e,s,n,o):new t(e,s,n,o)}},X=class extends Y{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},St=class extends Y{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Be=class extends St{constructor({message:e}={}){super({message:e??"Request timed out."})}},Lr=class extends Y{},zr=class extends Y{},Dr=class extends Y{},Fr=class extends Y{},Ur=class extends Y{},qr=class extends Y{},Br=class extends Y{},Kr=class extends Y{},Wr=class extends S{constructor(){super("Could not parse response content as the length limit was reached")}},Vr=class extends S{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ke=class extends Error{constructor(e){super(e)}},Jt=class extends Y{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},xo=class extends S{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var ym=/^[a-z][a-z0-9+.-]*:/i,gu=t=>ym.test(t),de=t=>(de=Array.isArray,de(t)),Da=de;function ws(t){return typeof t!="object"?{}:t??{}}function Fa(t){if(!t)return!0;for(let e in t)return!1;return!0}function yu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Io(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var _u=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new S(`${t} must be an integer`);if(e<0)throw new S(`${t} must be a positive integer`);return e};var wu=t=>{try{return JSON.parse(t)}catch{return}};var We=t=>new Promise(e=>setTimeout(e,t));var kt="6.37.0";var Iu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function _m(){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 wm=()=>{let t=_m();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kt,"X-Stainless-OS":Au(Deno.build.os),"X-Stainless-Arch":bu(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":kt,"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":kt,"X-Stainless-OS":Au(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=bm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kt,"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":kt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function bm(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var bu=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Au=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"),xu,vu=()=>xu??(xu=wm());function bs(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ua(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function As(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ua({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function qa(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 Ba(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 Su=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ka="RFC3986",Wa=t=>String(t),Va={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Wa},ku="RFC1738";var xs=(t,e)=>(xs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xs(t,e)),Ve=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Ga=1024,Cu=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=Ga){let u=s.length>=Ga?s.slice(i,i+Ga):s,l=[];for(let c=0;c<u.length;++c){let p=u.charCodeAt(c);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===ku&&(p===40||p===41)){l[l.length]=u.charAt(c);continue}if(p<128){l[l.length]=Ve[p];continue}if(p<2048){l[l.length]=Ve[192|p>>6]+Ve[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Ve[224|p>>12]+Ve[128|p>>6&63]+Ve[128|p&63];continue}c+=1,p=65536+((p&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=Ve[240|p>>18]+Ve[128|p>>12&63]+Ve[128|p>>6&63]+Ve[128|p&63]}a+=l.join("")}return a};function Eu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Ha(t,e){if(de(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Mu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Pu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},Ou,oe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Cu,encodeValuesOnly:!1,format:Ka,formatter:Wa,indices:!1,serializeDate(t){return(Ou??(Ou=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function xm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Ja={};function Ru(t,e,r,n,o,s,a,i,u,l,c,p,m,h,_,I,C,g){let A=t,k=g,L=0,Q=!1;for(;(k=k.get(Ja))!==void 0&&!Q;){let E=k.get(t);if(L+=1,typeof E<"u"){if(E===L)throw new RangeError("Cyclic object value");Q=!0}typeof k.get(Ja)>"u"&&(L=0)}if(typeof l=="function"?A=l(e,A):A instanceof Date?A=m?.(A):r==="comma"&&de(A)&&(A=Ha(A,function(E){return E instanceof Date?m?.(E):E})),A===null){if(s)return u&&!I?u(e,oe.encoder,C,"key",h):e;A=""}if(xm(A)||Eu(A)){if(u){let E=I?e:u(e,oe.encoder,C,"key",h);return[_?.(E)+"="+_?.(u(A,oe.encoder,C,"value",h))]}return[_?.(e)+"="+_?.(String(A))]}let G=[];if(typeof A>"u")return G;let K;if(r==="comma"&&de(A))I&&u&&(A=Ha(A,u)),K=[{value:A.length>0?A.join(",")||null:void 0}];else if(de(l))K=l;else{let E=Object.keys(A);K=c?E.sort(c):E}let z=i?String(e).replace(/\./g,"%2E"):String(e),T=n&&de(A)&&A.length===1?z+"[]":z;if(o&&de(A)&&A.length===0)return T+"[]";for(let E=0;E<K.length;++E){let F=K[E],J=typeof F=="object"&&typeof F.value<"u"?F.value:A[F];if(a&&J===null)continue;let Z=p&&i?F.replace(/\./g,"%2E"):F,N=de(A)?typeof r=="function"?r(T,Z):T:T+(p?"."+Z:"["+Z+"]");g.set(t,L);let W=new WeakMap;W.set(Ja,g),Pu(G,Ru(J,N,r,n,o,s,a,i,r==="comma"&&I&&de(A)?null:u,l,c,p,m,h,_,I,C,W))}return G}function Im(t=oe){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||oe.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=Ka;if(typeof t.format<"u"){if(!xs(Va,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Va[r],o=oe.filter;(typeof t.filter=="function"||de(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Mu?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=oe.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:oe.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:oe.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:oe.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:oe.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?oe.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:oe.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:oe.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:oe.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:oe.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:oe.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:oe.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:oe.strictNullHandling}}function $u(t,e={}){let r=t,n=Im(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):de(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=Mu[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let m=0;m<o.length;++m){let h=o[m];n.skipNulls&&r[h]===null||Pu(a,Ru(r[h],h,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let c=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),c.length>0?p+c:""}function Nu(t){return $u(t,{arrayFormat:"brackets"})}function zu(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 ju;function Gr(t){let e;return(ju??(e=new globalThis.TextEncoder,ju=e.encode.bind(e)))(t)}var Lu;function Za(t){let e;return(Lu??(e=new globalThis.TextDecoder,Lu=e.decode.bind(e)))(t)}var ve,Te,Zt=class{constructor(){ve.set(this,void 0),Te.set(this,void 0),O(this,ve,new Uint8Array,"f"),O(this,Te,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Gr(e):e;O(this,ve,zu([w(this,ve,"f"),r]),"f");let n=[],o;for(;(o=Tm(w(this,ve,"f"),w(this,Te,"f")))!=null;){if(o.carriage&&w(this,Te,"f")==null){O(this,Te,o.index,"f");continue}if(w(this,Te,"f")!=null&&(o.index!==w(this,Te,"f")+1||o.carriage)){n.push(Za(w(this,ve,"f").subarray(0,w(this,Te,"f")-1))),O(this,ve,w(this,ve,"f").subarray(w(this,Te,"f")),"f"),O(this,Te,null,"f");continue}let s=w(this,Te,"f")!==null?o.preceding-1:o.preceding,a=Za(w(this,ve,"f").subarray(0,s));n.push(a),O(this,ve,w(this,ve,"f").subarray(o.index),"f"),O(this,Te,null,"f")}return n}flush(){return w(this,ve,"f").length?this.decode(`
65
- `):[]}};ve=new WeakMap,Te=new WeakMap;Zt.NEWLINE_CHARS=new Set([`
66
- `,"\r"]);Zt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Tm(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 Du(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var vs={off:0,error:200,warn:300,info:400,debug:500},Qa=(t,e,r)=>{if(t){if(yu(vs,t))return t;ee(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(vs))}`)}};function vo(){}function Is(t,e,r){return!e||vs[t]>vs[r]?vo:e[t].bind(e)}var Sm={error:vo,warn:vo,info:vo,debug:vo},Fu=new WeakMap;function ee(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Sm;let n=Fu.get(e);if(n&&n[0]===r)return n[1];let o={error:Is("error",e,r),warn:Is("warn",e,r),info:Is("info",e,r),debug:Is("debug",e,r)};return Fu.set(e,[r,o]),o}var nt=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 To,Ge=class t{constructor(e,r,n){this.iterator=e,To.set(this,void 0),this.controller=r,O(this,To,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,a=n?ee(n):console;async function*i(){if(s)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of km(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(c&&c.error)throw new Y(void 0,c.error,void 0,e.headers);yield o?{event:l.event,data:c}:c}else{let c;try{c=JSON.parse(l.data)}catch(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new Y(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}u=!0}catch(l){if(bo(l))return;throw l}finally{u||r.abort()}}return new t(i,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let i=new Zt,u=qa(e);for await(let l of u)for(let c of i.decode(l))yield c;for(let l of i.flush())yield l}async function*a(){if(o)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(bo(u))return;throw u}finally{i||r.abort()}}return new t(a,r,n)}[(To=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>o(e),this.controller,w(this,To,"f")),new t(()=>o(r),this.controller,w(this,To,"f"))]}toReadableStream(){let e=this,r;return Ua({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let a=Gr(JSON.stringify(o)+`
67
- `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*km(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new S("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 S("Attempted to iterate over a response with no body");let r=new Ya,n=new Zt,o=qa(t.body);for await(let s of Cm(o))for(let a of n.decode(s)){let i=r.decode(a);i&&(yield i)}for(let s of n.flush()){let a=r.decode(s);a&&(yield a)}}async function*Cm(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"?Gr(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Du(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Ya=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
68
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Em(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Em(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Ts(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return ee(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):Ge.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let m=await r.json();return Xa(m,r)}return await r.text()})();return ee(t).debug(`[${n}] response parsed`,nt({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function Xa(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 So,Qt=class t extends Promise{constructor(e,r,n=Ts){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,So.set(this,void 0),O(this,So,e,"f")}_thenUnwrap(e){return new t(w(this,So,"f"),this.responsePromise,async(r,n)=>Xa(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(w(this,So,"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)}};So=new WeakMap;var Ss,Hr=class{constructor(e,r,n,o){Ss.set(this,void 0),O(this,Ss,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new S("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,Ss,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ss=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},ko=class extends Qt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await Ts(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends Hr{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}},j=class extends Hr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...ws(this.options.query),after:r}}:null}},H=class extends Hr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ws(this.options.query),after:e}}:null}},te=class extends Hr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ws(this.options.query),after:e}}:null}};var Mm={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Pm="urn:ietf:params:oauth:grant-type:token-exchange",ks=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??bs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:Pm,client_id:this.config.clientId,subject_token:e,subject_token_type:Mm[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!r.ok){let a=await r.text(),i;try{i=JSON.parse(a)}catch{}throw r.status===400||r.status===401||r.status===403?new Jt(r.status,i,r.headers):Y.generate(r.status,i,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json(),o=n.expires_in||3600,s=Date.now()+o*1e3;return this.cachedToken={token:n.access_token,expiresAt:s},n.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 ri=()=>{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 Jr(t,e,r){return ri(),new File(t,e??"unknown_file",r)}function Co(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 Cs=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Ct=async(t,e)=>ei(t.body)?{...t,body:await qu(t.body,e)}:t,me=async(t,e)=>({...t,body:await qu(t.body,e)}),Uu=new WeakMap;function Rm(t){let e=typeof t=="function"?t:t.fetch,r=Uu.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 Uu.set(e,n),n}var qu=async(t,e)=>{if(!await Rm(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])=>ti(r,n,o))),r},Bu=t=>t instanceof Blob&&"name"in t,$m=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Cs(t)||Bu(t)),ei=t=>{if($m(t))return!0;if(Array.isArray(t))return t.some(ei);if(t&&typeof t=="object"){for(let e in t)if(ei(t[e]))return!0}return!1},ti=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,Jr([await r.blob()],Co(r)));else if(Cs(r))t.append(e,Jr([await new Response(As(r)).blob()],Co(r)));else if(Bu(r))t.append(e,r,Co(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ti(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>ti(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 Ku=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",Nm=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Ku(t),jm=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Eo(t,e,r){if(ri(),t=await t,Nm(t))return t instanceof File?t:Jr([await t.arrayBuffer()],t.name);if(jm(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Jr(await ni(o),e,r)}let n=await ni(t);if(e||(e=Co(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Jr(n,e,r)}async function ni(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Ku(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Cs(t))for await(let r of t)e.push(...await ni(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Lm(t)}`)}return e}function Lm(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var y=class{constructor(e){this._client=e}};function Vu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Wu=Object.freeze(Object.create(null)),Dm=(t=Vu)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],a=r.reduce((c,p,m)=>{/[?#]/.test(p)&&(o=!0);let h=n[m],_=(o?encodeURIComponent:t)(""+h);return m!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Wu)??Wu)?.toString)&&(_=h+"",s.push({start:c.length+p.length,length:_.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),c+p+(m===n.length?"":_)},""),i=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(i))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((c,p)=>c.start-p.start),s.length>0){let c=0,p=s.reduce((m,h)=>{let _=" ".repeat(h.start-c),I="^".repeat(h.length);return c=h.start+h.length,m+_+I},"");throw new S(`Path parameters result in path with invalid segments:
64
+ `,t}function M(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 Ka=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Ka=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 Ao(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Io=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 S=class extends Error{},Y=class t extends S{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 kt({message:n,cause:Io(r)});let s=r?.error;return e===400?new qr(e,s,n,o):e===401?new Ur(e,s,n,o):e===403?new Br(e,s,n,o):e===404?new Kr(e,s,n,o):e===409?new Gr(e,s,n,o):e===422?new Wr(e,s,n,o):e===429?new Vr(e,s,n,o):e>=500?new Hr(e,s,n,o):new t(e,s,n,o)}},X=class extends Y{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},kt=class extends Y{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Be=class extends kt{constructor({message:e}={}){super({message:e??"Request timed out."})}},qr=class extends Y{},Ur=class extends Y{},Br=class extends Y{},Kr=class extends Y{},Gr=class extends Y{},Wr=class extends Y{},Vr=class extends Y{},Hr=class extends Y{},Jr=class extends S{constructor(){super("Could not parse response content as the length limit was reached")}},Zr=class extends S{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ke=class extends Error{constructor(e){super(e)}},Zt=class extends Y{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},vo=class extends S{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Em=/^[a-z][a-z0-9+.-]*:/i,Eu=t=>Em.test(t),me=t=>(me=Array.isArray,me(t)),Ga=me;function xs(t){return typeof t!="object"?{}:t??{}}function Wa(t){if(!t)return!0;for(let e in t)return!1;return!0}function Mu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function To(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Ou=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new S(`${t} must be an integer`);if(e<0)throw new S(`${t} must be a positive integer`);return e};var Pu=t=>{try{return JSON.parse(t)}catch{return}};var Ge=t=>new Promise(e=>setTimeout(e,t));var Ct="6.37.0";var ju=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Mm(){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 Om=()=>{let t=Mm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":$u(Deno.build.os),"X-Stainless-Arch":Ru(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":$u(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ru(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Pm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Pm(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var Ru=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$u=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"),Nu,zu=()=>Nu??(Nu=Om());function As(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Va(...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 Va({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Ha(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 Ja(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 Du=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Za="RFC3986",Qa=t=>String(t),Ya={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Qa},Fu="RFC1738";var vs=(t,e)=>(vs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),vs(t,e)),We=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Xa=1024,qu=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=Xa){let u=s.length>=Xa?s.slice(i,i+Xa):s,l=[];for(let c=0;c<u.length;++c){let p=u.charCodeAt(c);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===Fu&&(p===40||p===41)){l[l.length]=u.charAt(c);continue}if(p<128){l[l.length]=We[p];continue}if(p<2048){l[l.length]=We[192|p>>6]+We[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=We[224|p>>12]+We[128|p>>6&63]+We[128|p&63];continue}c+=1,p=65536+((p&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=We[240|p>>18]+We[128|p>>12&63]+We[128|p>>6&63]+We[128|p&63]}a+=l.join("")}return a};function Uu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ei(t,e){if(me(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Ku={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Gu=function(t,e){Array.prototype.push.apply(t,me(e)?e:[e])},Bu,oe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:qu,encodeValuesOnly:!1,format:Za,formatter:Qa,indices:!1,serializeDate(t){return(Bu??(Bu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function $m(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var ti={};function Wu(t,e,r,n,o,s,a,i,u,l,c,p,m,h,y,A,C,g){let b=t,k=g,z=0,Q=!1;for(;(k=k.get(ti))!==void 0&&!Q;){let E=k.get(t);if(z+=1,typeof E<"u"){if(E===z)throw new RangeError("Cyclic object value");Q=!0}typeof k.get(ti)>"u"&&(z=0)}if(typeof l=="function"?b=l(e,b):b instanceof Date?b=m?.(b):r==="comma"&&me(b)&&(b=ei(b,function(E){return E instanceof Date?m?.(E):E})),b===null){if(s)return u&&!A?u(e,oe.encoder,C,"key",h):e;b=""}if($m(b)||Uu(b)){if(u){let E=A?e:u(e,oe.encoder,C,"key",h);return[y?.(E)+"="+y?.(u(b,oe.encoder,C,"value",h))]}return[y?.(e)+"="+y?.(String(b))]}let V=[];if(typeof b>"u")return V;let K;if(r==="comma"&&me(b))A&&u&&(b=ei(b,u)),K=[{value:b.length>0?b.join(",")||null:void 0}];else if(me(l))K=l;else{let E=Object.keys(b);K=c?E.sort(c):E}let L=i?String(e).replace(/\./g,"%2E"):String(e),T=n&&me(b)&&b.length===1?L+"[]":L;if(o&&me(b)&&b.length===0)return T+"[]";for(let E=0;E<K.length;++E){let F=K[E],J=typeof F=="object"&&typeof F.value<"u"?F.value:b[F];if(a&&J===null)continue;let Z=p&&i?F.replace(/\./g,"%2E"):F,N=me(b)?typeof r=="function"?r(T,Z):T:T+(p?"."+Z:"["+Z+"]");g.set(t,z);let G=new WeakMap;G.set(ti,g),Gu(V,Wu(J,N,r,n,o,s,a,i,r==="comma"&&A&&me(b)?null:u,l,c,p,m,h,y,A,C,G))}return V}function Nm(t=oe){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||oe.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=Za;if(typeof t.format<"u"){if(!vs(Ya,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Ya[r],o=oe.filter;(typeof t.filter=="function"||me(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Ku?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=oe.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:oe.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:oe.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:oe.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:oe.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?oe.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:oe.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:oe.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:oe.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:oe.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:oe.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:oe.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:oe.strictNullHandling}}function Vu(t,e={}){let r=t,n=Nm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):me(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=Ku[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let m=0;m<o.length;++m){let h=o[m];n.skipNulls&&r[h]===null||Gu(a,Wu(r[h],h,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let c=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),c.length>0?p+c:""}function Hu(t){return Vu(t,{arrayFormat:"brackets"})}function Qu(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 Ju;function Qr(t){let e;return(Ju??(e=new globalThis.TextEncoder,Ju=e.encode.bind(e)))(t)}var Zu;function ri(t){let e;return(Zu??(e=new globalThis.TextDecoder,Zu=e.decode.bind(e)))(t)}var Te,Se,Qt=class{constructor(){Te.set(this,void 0),Se.set(this,void 0),M(this,Te,new Uint8Array,"f"),M(this,Se,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Qr(e):e;M(this,Te,Qu([_(this,Te,"f"),r]),"f");let n=[],o;for(;(o=zm(_(this,Te,"f"),_(this,Se,"f")))!=null;){if(o.carriage&&_(this,Se,"f")==null){M(this,Se,o.index,"f");continue}if(_(this,Se,"f")!=null&&(o.index!==_(this,Se,"f")+1||o.carriage)){n.push(ri(_(this,Te,"f").subarray(0,_(this,Se,"f")-1))),M(this,Te,_(this,Te,"f").subarray(_(this,Se,"f")),"f"),M(this,Se,null,"f");continue}let s=_(this,Se,"f")!==null?o.preceding-1:o.preceding,a=ri(_(this,Te,"f").subarray(0,s));n.push(a),M(this,Te,_(this,Te,"f").subarray(o.index),"f"),M(this,Se,null,"f")}return n}flush(){return _(this,Te,"f").length?this.decode(`
65
+ `):[]}};Te=new WeakMap,Se=new WeakMap;Qt.NEWLINE_CHARS=new Set([`
66
+ `,"\r"]);Qt.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 Yu(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 Ss={off:0,error:200,warn:300,info:400,debug:500},ni=(t,e,r)=>{if(t){if(Mu(Ss,t))return t;te(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Ss))}`)}};function So(){}function Ts(t,e,r){return!e||Ss[t]>Ss[r]?So:e[t].bind(e)}var Lm={error:So,warn:So,info:So,debug:So},Xu=new WeakMap;function te(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Lm;let n=Xu.get(e);if(n&&n[0]===r)return n[1];let o={error:Ts("error",e,r),warn:Ts("warn",e,r),info:Ts("info",e,r),debug:Ts("debug",e,r)};return Xu.set(e,[r,o]),o}var nt=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 ko,Ve=class t{constructor(e,r,n){this.iterator=e,ko.set(this,void 0),this.controller=r,M(this,ko,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,a=n?te(n):console;async function*i(){if(s)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of Dm(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(c&&c.error)throw new Y(void 0,c.error,void 0,e.headers);yield o?{event:l.event,data:c}:c}else{let c;try{c=JSON.parse(l.data)}catch(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new Y(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}u=!0}catch(l){if(Ao(l))return;throw l}finally{u||r.abort()}}return new t(i,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let i=new Qt,u=Ha(e);for await(let l of u)for(let c of i.decode(l))yield c;for(let l of i.flush())yield l}async function*a(){if(o)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(Ao(u))return;throw u}finally{i||r.abort()}}return new t(a,r,n)}[(ko=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>o(e),this.controller,_(this,ko,"f")),new t(()=>o(r),this.controller,_(this,ko,"f"))]}toReadableStream(){let e=this,r;return Va({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let a=Qr(JSON.stringify(o)+`
67
+ `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Dm(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new S("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 S("Attempted to iterate over a response with no body");let r=new oi,n=new Qt,o=Ha(t.body);for await(let s of Fm(o))for(let a of n.decode(s)){let i=r.decode(a);i&&(yield i)}for(let s of n.flush()){let a=r.decode(s);a&&(yield a)}}async function*Fm(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"?Qr(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Yu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var oi=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
68
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=qm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function qm(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ks(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return te(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):Ve.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let m=await r.json();return si(m,r)}return await r.text()})();return te(t).debug(`[${n}] response parsed`,nt({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function si(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,Yt=class t extends Promise{constructor(e,r,n=ks){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Co.set(this,void 0),M(this,Co,e,"f")}_thenUnwrap(e){return new t(_(this,Co,"f"),this.responsePromise,async(r,n)=>si(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 Cs,Yr=class{constructor(e,r,n,o){Cs.set(this,void 0),M(this,Cs,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 S("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,Cs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Cs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Eo=class extends Yt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await ks(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},fe=class extends Yr{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}},j=class extends Yr{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:{...xs(this.options.query),after:r}}:null}},H=class extends Yr{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:{...xs(this.options.query),after:e}}:null}},ne=class extends Yr{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:{...xs(this.options.query),after:e}}:null}};var Bm={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Km="urn:ietf:params:oauth:grant-type:token-exchange",Es=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??As()}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=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:Km,client_id:this.config.clientId,subject_token:e,subject_token_type:Bm[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!r.ok){let a=await r.text(),i;try{i=JSON.parse(a)}catch{}throw r.status===400||r.status===401||r.status===403?new Zt(r.status,i,r.headers):Y.generate(r.status,i,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json(),o=n.expires_in||3600,s=Date.now()+o*1e3;return this.cachedToken={token:n.access_token,expiresAt:s},n.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 li=()=>{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 Xr(t,e,r){return li(),new File(t,e??"unknown_file",r)}function Mo(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",Et=async(t,e)=>ai(t.body)?{...t,body:await tc(t.body,e)}:t,he=async(t,e)=>({...t,body:await tc(t.body,e)}),ec=new WeakMap;function Gm(t){let e=typeof t=="function"?t:t.fetch,r=ec.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 ec.set(e,n),n}var tc=async(t,e)=>{if(!await Gm(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])=>ii(r,n,o))),r},rc=t=>t instanceof Blob&&"name"in t,Wm=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Ms(t)||rc(t)),ai=t=>{if(Wm(t))return!0;if(Array.isArray(t))return t.some(ai);if(t&&typeof t=="object"){for(let e in t)if(ai(t[e]))return!0}return!1},ii=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,Xr([await r.blob()],Mo(r)));else if(Ms(r))t.append(e,Xr([await new Response(Is(r)).blob()],Mo(r)));else if(rc(r))t.append(e,r,Mo(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ii(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>ii(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 nc=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",Vm=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&nc(t),Hm=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Oo(t,e,r){if(li(),t=await t,Vm(t))return t instanceof File?t:Xr([await t.arrayBuffer()],t.name);if(Hm(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Xr(await ui(o),e,r)}let n=await ui(t);if(e||(e=Mo(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Xr(n,e,r)}async function ui(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(nc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Ms(t))for await(let r of t)e.push(...await ui(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Jm(t)}`)}return e}function Jm(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var w=class{constructor(e){this._client=e}};function sc(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var oc=Object.freeze(Object.create(null)),Qm=(t=sc)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],a=r.reduce((c,p,m)=>{/[?#]/.test(p)&&(o=!0);let h=n[m],y=(o?encodeURIComponent:t)(""+h);return m!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??oc)??oc)?.toString)&&(y=h+"",s.push({start:c.length+p.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),c+p+(m===n.length?"":y)},""),i=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(i))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((c,p)=>c.start-p.start),s.length>0){let c=0,p=s.reduce((m,h)=>{let y=" ".repeat(h.start-c),A="^".repeat(h.length);return c=h.start+h.length,m+y+A},"");throw new S(`Path parameters result in path with invalid segments:
69
69
  ${s.map(m=>m.error).join(`
70
70
  `)}
71
71
  ${a}
72
- ${p}`)}return a},f=Dm(Vu);var Yt=class extends y{list(e,r={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,j,{query:r,...n,__security:{bearerAuth:!0}})}};function Oo(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Gu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Mo(t){return t?.$brand==="auto-parseable-response-format"}function Xt(t){return t?.$brand==="auto-parseable-tool"}function Hu(t,e){return!e||!oi(e)?{...t,choices:t.choices.map(r=>(Zu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Po(t,e)}function Po(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Wr;if(n.finish_reason==="content_filter")throw new Vr;return Zu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Bm(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?qm(e,n.message.content):null}}});return{...t,choices:r}}function qm(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 Bm(t,e){let r=t.tools?.find(n=>Oo(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Xt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Ju(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>Oo(n)&&n.function?.name===e.function.name);return Oo(r)&&(Xt(r)||r?.function.strict||!1)}function oi(t){return Mo(t.response_format)?!0:t.tools?.some(e=>Xt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Zu(t){for(let e of t||[])if(e.type!=="function")throw new S(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Qu(t){for(let e of t??[]){if(e.type!=="function")throw new S(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new S(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Zr=t=>t?.role==="assistant",si=t=>t?.role==="tool";var ai,Es,Os,Ro,$o,Ms,No,ot,jo,Ps,Rs,Qr,Yu,Et=class{constructor(){ai.add(this),this.controller=new AbortController,Es.set(this,void 0),Os.set(this,()=>{}),Ro.set(this,()=>{}),$o.set(this,void 0),Ms.set(this,()=>{}),No.set(this,()=>{}),ot.set(this,{}),jo.set(this,!1),Ps.set(this,!1),Rs.set(this,!1),Qr.set(this,!1),O(this,Es,new Promise((e,r)=>{O(this,Os,e,"f"),O(this,Ro,r,"f")}),"f"),O(this,$o,new Promise((e,r)=>{O(this,Ms,e,"f"),O(this,No,r,"f")}),"f"),w(this,Es,"f").catch(()=>{}),w(this,$o,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,ai,"m",Yu).bind(this))},0)}_connected(){this.ended||(w(this,Os,"f").call(this),this._emit("connect"))}get ended(){return w(this,jo,"f")}get errored(){return w(this,Ps,"f")}get aborted(){return w(this,Rs,"f")}abort(){this.controller.abort()}on(e,r){return(w(this,ot,"f")[e]||(w(this,ot,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=w(this,ot,"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(w(this,ot,"f")[e]||(w(this,ot,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{O(this,Qr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){O(this,Qr,!0,"f"),await w(this,$o,"f")}_emit(e,...r){if(w(this,jo,"f"))return;e==="end"&&(O(this,jo,!0,"f"),w(this,Ms,"f").call(this));let n=w(this,ot,"f")[e];if(n&&(w(this,ot,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!w(this,Qr,"f")&&!n?.length&&Promise.reject(o),w(this,Ro,"f").call(this,o),w(this,No,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!w(this,Qr,"f")&&!n?.length&&Promise.reject(o),w(this,Ro,"f").call(this,o),w(this,No,"f").call(this,o),this._emit("end")}}_emitFinal(){}};Es=new WeakMap,Os=new WeakMap,Ro=new WeakMap,$o=new WeakMap,Ms=new WeakMap,No=new WeakMap,ot=new WeakMap,jo=new WeakMap,Ps=new WeakMap,Rs=new WeakMap,Qr=new WeakMap,ai=new WeakSet,Yu=function(e){if(O(this,Ps,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return O(this,Rs,!0,"f"),this._emit("abort",e);if(e instanceof S)return this._emit("error",e);if(e instanceof Error){let r=new S(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new S(String(e)))};function Xu(t){return typeof t.parse=="function"}var we,ii,$s,li,ui,ci,ec,tc,Km=10,Yr=class extends Et{constructor(){super(...arguments),we.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),si(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Zr(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 S("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),w(this,we,"m",ii).call(this)}async finalMessage(){return await this.done(),w(this,we,"m",$s).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,we,"m",li).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,we,"m",ui).call(this)}async totalUsage(){return await this.done(),w(this,we,"m",ci).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=w(this,we,"m",$s).call(this);r&&this._emit("finalMessage",r);let n=w(this,we,"m",ii).call(this);n&&this._emit("finalContent",n);let o=w(this,we,"m",li).call(this);o&&this._emit("finalFunctionToolCall",o);let s=w(this,we,"m",ui).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",w(this,we,"m",ci).call(this))}async _createChatCompletion(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),w(this,we,"m",ec).call(this,r);let s=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Po(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:a,...i}=r,u=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:l=Km}=n||{},c=r.tools.map(h=>{if(Xt(h)){if(!h.$callback)throw new S("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}),p={};for(let h of c)h.type==="function"&&(p[h.function.name||h.function.function.name]=h.function);let m="tools"in r?c.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 I=(await this._createChatCompletion(e,{...i,tool_choice:s,tools:m,messages:[...this.messages]},n)).choices[0]?.message;if(!I)throw new S("missing message in ChatCompletion response");if(!I.tool_calls?.length)return;for(let C of I.tool_calls){if(C.type!=="function")continue;let g=C.id,{name:A,arguments:k}=C.function,L=p[A];if(L){if(u&&u!==A){let z=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:o,tool_call_id:g,content:z});continue}}else{let z=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(p).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:g,content:z});continue}let Q;try{Q=Xu(L)?await L.parse(k):k}catch(z){let T=z instanceof Error?z.message:String(z);this._addMessage({role:o,tool_call_id:g,content:T});continue}let G=await L.function(Q,this),K=w(this,we,"m",tc).call(this,G);if(this._addMessage({role:o,tool_call_id:g,content:K}),u)return}}}};we=new WeakSet,ii=function(){return w(this,we,"m",$s).call(this).content??null},$s=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Zr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new S("stream ended without producing a ChatCompletionMessage with role=assistant")},li=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Zr(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},ui=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(si(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}},ci=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},ec=function(e){if(e.n!=null&&e.n>1)throw new S("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},tc=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Lo=class t extends Yr{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),Zr(e)&&e.content&&this._emit("content",e.content)}};var ie={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},di=class extends Error{},pi=class extends Error{};function Wm(t,e=ie.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Vm(t.trim(),e)}var Vm=(t,e)=>{let r=t.length,n=0,o=m=>{throw new di(`${m} at position ${n}`)},s=m=>{throw new pi(`${m} at position ${n}`)},a=()=>(p(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||ie.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ie.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ie.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ie.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ie.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ie.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):c()),i=()=>{let m=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(m,++n-Number(h)))}catch(_){s(String(_))}else if(ie.STR&e)try{return JSON.parse(t.substring(m,n-Number(h))+'"')}catch{return JSON.parse(t.substring(m,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,p();let m={};try{for(;t[n]!=="}";){if(p(),n>=r&&ie.OBJ&e)return m;let h=i();p(),n++;try{let _=a();Object.defineProperty(m,h,{value:_,writable:!0,enumerable:!0,configurable:!0})}catch(_){if(ie.OBJ&e)return m;throw _}p(),t[n]===","&&n++}}catch{if(ie.OBJ&e)return m;o("Expected '}' at end of object")}return n++,m},l=()=>{n++;let m=[];try{for(;t[n]!=="]";)m.push(a()),p(),t[n]===","&&n++}catch{if(ie.ARR&e)return m;o("Expected ']' at end of array")}return n++,m},c=()=>{if(n===0){t==="-"&&ie.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(ie.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 m=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ie.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(m,n))}catch{t.substring(m,n)==="-"&&ie.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(m,t.lastIndexOf("e")))}catch(_){s(String(_))}}},p=()=>{for(;n<r&&`
73
- \r `.includes(t[n]);)n++};return a()},mi=t=>Wm(t,ie.ALL^ie.NUM);var se,st,Xr,Ot,fi,Ns,hi,gi,yi,js,_i,rc,er=class t extends Yr{constructor(e){super(),se.add(this),st.set(this,void 0),Xr.set(this,void 0),Ot.set(this,void 0),O(this,st,e,"f"),O(this,Xr,[],"f")}get currentChatCompletionSnapshot(){return w(this,Ot,"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())),w(this,se,"m",fi).call(this);let s=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of s)w(this,se,"m",hi).call(this,a);if(s.controller.signal?.aborted)throw new X;return this._addChatCompletion(w(this,se,"m",js).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),w(this,se,"m",fi).call(this),this._connected();let o=Ge.fromReadableStream(e,this.controller),s;for await(let a of o)s&&s!==a.id&&this._addChatCompletion(w(this,se,"m",js).call(this)),w(this,se,"m",hi).call(this,a),s=a.id;if(o.controller.signal?.aborted)throw new X;return this._addChatCompletion(w(this,se,"m",js).call(this))}[(st=new WeakMap,Xr=new WeakMap,Ot=new WeakMap,se=new WeakSet,fi=function(){this.ended||O(this,Ot,void 0,"f")},Ns=function(r){let n=w(this,Xr,"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},w(this,Xr,"f")[r.index]=n,n)},hi=function(r){if(this.ended)return;let n=w(this,se,"m",rc).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index];o.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.delta.content,s.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),o.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=w(this,se,"m",Ns).call(this,s);s.finish_reason&&(w(this,se,"m",yi).call(this,s),a.current_tool_call_index!=null&&w(this,se,"m",gi).call(this,s,a.current_tool_call_index));for(let i of o.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(w(this,se,"m",yi).call(this,s),a.current_tool_call_index!=null&&w(this,se,"m",gi).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of o.delta.tool_calls??[]){let u=s.message.tool_calls?.[i.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:i.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:i.function?.arguments??""}):(u?.type,void 0))}}},gi=function(r,n){if(w(this,se,"m",Ns).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let a=w(this,st,"f")?.tools?.find(i=>Oo(i)&&i.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Xt(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},yi=function(r){let n=w(this,se,"m",Ns).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=w(this,se,"m",_i).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}))},js=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");let r=w(this,Ot,"f");if(!r)throw new S("request ended without sending any chunks");return O(this,Ot,void 0,"f"),O(this,Xr,[],"f"),Gm(r,w(this,st,"f"))},_i=function(){let r=w(this,st,"f")?.response_format;return Mo(r)?r:null},rc=function(r){var n,o,s,a;let i=w(this,Ot,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=O(this,Ot,{...l,choices:[]},"f");for(let{delta:c,finish_reason:p,index:m,logprobs:h=null,..._}of r.choices){let I=i.choices[m];if(I||(I=i.choices[m]={finish_reason:p,index:m,message:{},logprobs:h,..._}),h)if(!I.logprobs)I.logprobs=Object.assign({},h);else{let{content:G,refusal:K,...z}=h;Object.assign(I.logprobs,z),G&&((n=I.logprobs).content??(n.content=[]),I.logprobs.content.push(...G)),K&&((o=I.logprobs).refusal??(o.refusal=[]),I.logprobs.refusal.push(...K))}if(p&&(I.finish_reason=p,w(this,st,"f")&&oi(w(this,st,"f")))){if(p==="length")throw new Wr;if(p==="content_filter")throw new Vr}if(Object.assign(I,_),!c)continue;let{content:C,refusal:g,function_call:A,role:k,tool_calls:L,...Q}=c;if(Object.assign(I.message,Q),g&&(I.message.refusal=(I.message.refusal||"")+g),k&&(I.message.role=k),A&&(I.message.function_call?(A.name&&(I.message.function_call.name=A.name),A.arguments&&((s=I.message.function_call).arguments??(s.arguments=""),I.message.function_call.arguments+=A.arguments)):I.message.function_call=A),C&&(I.message.content=(I.message.content||"")+C,!I.message.refusal&&w(this,se,"m",_i).call(this)&&(I.message.parsed=mi(I.message.content))),L){I.message.tool_calls||(I.message.tool_calls=[]);for(let{index:G,id:K,type:z,function:T,...E}of L){let F=(a=I.message.tool_calls)[G]??(a[G]={});Object.assign(F,E),K&&(F.id=K),z&&(F.type=z),T&&(F.function??(F.function={name:T.name??"",arguments:""})),T?.name&&(F.function.name=T.name),T?.arguments&&(F.function.arguments+=T.arguments,Ju(w(this,st,"f"),F)&&(F.function.parsed_arguments=mi(F.function.arguments)))}}}return i},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ge(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Gm(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:a,...i}=t,u={...i,id:r,choices:n.map(({message:l,finish_reason:c,index:p,logprobs:m,...h})=>{if(!c)throw new S(`missing finish_reason for choice ${p}`);let{content:_=null,function_call:I,tool_calls:C,...g}=l,A=l.role;if(!A)throw new S(`missing role for choice ${p}`);if(I){let{arguments:k,name:L}=I;if(k==null)throw new S(`missing function_call.arguments for choice ${p}`);if(!L)throw new S(`missing function_call.name for choice ${p}`);return{...h,message:{content:_,function_call:{arguments:k,name:L},role:A,refusal:l.refusal??null},finish_reason:c,index:p,logprobs:m}}return C?{...h,index:p,finish_reason:c,logprobs:m,message:{...g,role:A,content:_,refusal:l.refusal??null,tool_calls:C.map((k,L)=>{let{function:Q,type:G,id:K,...z}=k,{arguments:T,name:E,...F}=Q||{};if(K==null)throw new S(`missing choices[${p}].tool_calls[${L}].id
74
- ${Ls(t)}`);if(G==null)throw new S(`missing choices[${p}].tool_calls[${L}].type
75
- ${Ls(t)}`);if(E==null)throw new S(`missing choices[${p}].tool_calls[${L}].function.name
76
- ${Ls(t)}`);if(T==null)throw new S(`missing choices[${p}].tool_calls[${L}].function.arguments
77
- ${Ls(t)}`);return{...z,id:K,type:G,function:{...F,name:E,arguments:T}}})}}:{...h,message:{...g,content:_,role:A,refusal:l.refusal??null},finish_reason:c,index:p,logprobs:m}}),created:o,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Hu(u,e)}function Ls(t){return JSON.stringify(t)}var zo=class t extends er{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 at=class extends y{constructor(){super(...arguments),this.messages=new Yt(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(f`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Qu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Po(n,e))}runTools(e,r){return e.stream?zo.runTools(this._client,e,r):Lo.runTools(this._client,e,r)}stream(e,r){return er.createChatCompletion(this._client,e,r)}};at.Messages=Yt;var Mt=class extends y{constructor(){super(...arguments),this.completions=new at(this._client)}};Mt.Completions=at;var en=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(f`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tn=class extends y{list(e={},r){return this._client.getAPIList("/organization/audit_logs",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var rn=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(f`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var nn=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(f`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var on=class extends y{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",te,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var sn=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}})}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}})}};var an=class extends y{create(e,r,n){return this._client.post(f`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/groups/${e}/roles`,te,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(f`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ln=class extends y{create(e,r,n){return this._client.post(f`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/groups/${e}/users`,te,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(f`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Pt=class extends y{constructor(){super(...arguments),this.users=new ln(this._client),this.roles=new an(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",te,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Pt.Users=ln;Pt.Roles=an;var un=class extends y{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(f`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/api_keys`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var cn=class extends y{list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/certificates`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(f`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(f`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var dn=class extends y{listRateLimits(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/rate_limits`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var pn=class extends y{create(e,r,n){return this._client.post(f`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/projects/${e}/roles`,te,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var mn=class extends y{create(e,r,n){return this._client.post(f`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(f`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/service_accounts`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var fn=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(f`/projects/${o}/groups/${e}/roles`,te,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(f`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends y{constructor(){super(...arguments),this.roles=new fn(this._client)}create(e,r,n){return this._client.post(f`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/groups`,te,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};tr.Roles=fn;var hn=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(f`/projects/${o}/users/${e}/roles`,te,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(f`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends y{constructor(){super(...arguments),this.roles=new hn(this._client)}create(e,r,n){return this._client.post(f`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(f`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/users`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};rr.Roles=hn;var Se=class extends y{constructor(){super(...arguments),this.users=new rr(this._client),this.serviceAccounts=new mn(this._client),this.apiKeys=new un(this._client),this.rateLimits=new dn(this._client),this.groups=new tr(this._client),this.roles=new pn(this._client),this.certificates=new cn(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(f`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(f`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};Se.Users=rr;Se.ServiceAccounts=mn;Se.APIKeys=un;Se.RateLimits=dn;Se.Groups=tr;Se.Roles=pn;Se.Certificates=cn;var gn=class extends y{create(e,r,n){return this._client.post(f`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/users/${e}/roles`,te,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(f`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends y{constructor(){super(...arguments),this.roles=new gn(this._client)}retrieve(e,r){return this._client.get(f`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};nr.Roles=gn;var be=class extends y{constructor(){super(...arguments),this.auditLogs=new tn(this._client),this.adminAPIKeys=new en(this._client),this.usage=new sn(this._client),this.invites=new nn(this._client),this.users=new nr(this._client),this.groups=new Pt(this._client),this.roles=new on(this._client),this.certificates=new rn(this._client),this.projects=new Se(this._client)}};be.AuditLogs=tn;be.AdminAPIKeys=en;be.Usage=sn;be.Invites=nn;be.Users=nr;be.Groups=Pt;be.Roles=on;be.Certificates=rn;be.Projects=Se;var Rt=class extends y{constructor(){super(...arguments),this.organization=new be(this._client)}};Rt.Organization=be;var nc=Symbol("brand.privateNullableHeaders");function*_f(t){if(!t)return;if(nc 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():Da(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=Da(n[1])?n[1]:[n[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,i])}}var v=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,a]of _f(n)){let i=s.toLowerCase();o.has(i)||(e.delete(s),o.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[nc]:!0,values:e,nulls:r}};var yn=class extends y{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:v([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var _n=class extends y{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var wn=class extends y{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var He=class extends y{constructor(){super(...arguments),this.transcriptions=new _n(this._client),this.translations=new wn(this._client),this.speech=new yn(this._client)}};He.Transcriptions=_n;He.Translations=wn;He.Speech=yn;var or=class extends y{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",j,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var bn=class extends y{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/assistants/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/assistants/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",j,{query:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/assistants/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var An=class extends y{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var xn=class extends y{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var $t=class extends y{constructor(){super(...arguments),this.sessions=new An(this._client),this.transcriptionSessions=new xn(this._client)}};$t.Sessions=An;$t.TranscriptionSessions=xn;var In=class extends y{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/chatkit/sessions/${e}/cancel`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var vn=class extends y{retrieve(e,r){return this._client.get(f`/chatkit/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",H,{query:e,...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/chatkit/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(f`/chatkit/threads/${e}/items`,H,{query:r,...n,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Nt=class extends y{constructor(){super(...arguments),this.sessions=new In(this._client),this.threads=new vn(this._client)}};Nt.Sessions=In;Nt.Threads=vn;var Tn=class extends y{create(e,r,n){return this._client.post(f`/threads/${e}/messages`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(f`/threads/${o}/messages/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(f`/threads/${o}/messages/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/threads/${e}/messages`,j,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(f`/threads/${o}/messages/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Sn=class extends y{retrieve(e,r,n){let{thread_id:o,run_id:s,...a}=r;return this._client.get(f`/threads/${o}/runs/${s}/steps/${e}`,{query:a,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(f`/threads/${o}/runs/${e}/steps`,j,{query:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var oc=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 Je=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,ar,wi,Ze,zs,Me,ir,kn,sr,Us,ke,Ds,Fs,Uo,Do,Fo,sc,ac,ic,lc,uc,cc,dc,it=class extends Et{constructor(){super(...arguments),le.add(this),wi.set(this,[]),Ze.set(this,{}),zs.set(this,{}),Me.set(this,void 0),ir.set(this,void 0),kn.set(this,void 0),sr.set(this,void 0),Us.set(this,void 0),ke.set(this,void 0),Ds.set(this,void 0),Fs.set(this,void 0),Uo.set(this,void 0)}[(wi=new WeakMap,Ze=new WeakMap,zs=new WeakMap,Me=new WeakMap,ir=new WeakMap,kn=new WeakMap,sr=new WeakMap,Us=new WeakMap,ke=new WeakMap,Ds=new WeakMap,Fs=new WeakMap,Uo=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,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new ar;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=Ge.fromReadableStream(e,this.controller);for await(let s of o)w(this,le,"m",Do).call(this,s);if(o.controller.signal?.aborted)throw new X;return this._addRun(w(this,le,"m",Fo).call(this))}toReadableStream(){return new Ge(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new ar;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 a={...n,stream:!0},i=await e.submitToolOutputs(r,a,{...o,signal:this.controller.signal});this._connected();for await(let u of i)w(this,le,"m",Do).call(this,u);if(i.controller.signal?.aborted)throw new X;return this._addRun(w(this,le,"m",Fo).call(this))}static createThreadAssistantStream(e,r,n){let o=new ar;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 ar;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return w(this,Ds,"f")}currentRun(){return w(this,Fs,"f")}currentMessageSnapshot(){return w(this,Me,"f")}currentRunStepSnapshot(){return w(this,Uo,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,Ze,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,zs,"f"))}async finalRun(){if(await this.done(),!w(this,ir,"f"))throw Error("Final run was not received.");return w(this,ir,"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},a=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)w(this,le,"m",Do).call(this,i);if(a.controller.signal?.aborted)throw new X;return this._addRun(w(this,le,"m",Fo).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 a={...n,stream:!0},i=await e.create(r,a,{...o,signal:this.controller.signal});this._connected();for await(let u of i)w(this,le,"m",Do).call(this,u);if(i.controller.signal?.aborted)throw new X;return this._addRun(w(this,le,"m",Fo).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(a=>typeof a=="string"||typeof a=="number")){s.push(...o);continue}for(let a of o){if(!Io(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);let u=s[i];u==null?s.push(a):s[i]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};ar=it,Do=function(e){if(!this.ended)switch(O(this,Ds,e,"f"),w(this,le,"m",ic).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":w(this,le,"m",dc).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":w(this,le,"m",ac).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":w(this,le,"m",sc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Fo=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");if(!w(this,ir,"f"))throw Error("Final run has not been received");return w(this,ir,"f")},sc=function(e){let[r,n]=w(this,le,"m",uc).call(this,e,w(this,Me,"f"));O(this,Me,r,"f"),w(this,zs,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,a=r.content[o.index];if(a&&a.type=="text")this._emit("textDelta",s,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=w(this,kn,"f")){if(w(this,sr,"f"))switch(w(this,sr,"f").type){case"text":this._emit("textDone",w(this,sr,"f").text,w(this,Me,"f"));break;case"image_file":this._emit("imageFileDone",w(this,sr,"f").image_file,w(this,Me,"f"));break}O(this,kn,o.index,"f")}O(this,sr,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,kn,"f")!==void 0){let o=e.data.content[w(this,kn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,w(this,Me,"f"));break;case"text":this._emit("textDone",o.text,w(this,Me,"f"));break}}w(this,Me,"f")&&this._emit("messageDone",e.data),O(this,Me,void 0,"f")}},ac=function(e){let r=w(this,le,"m",lc).call(this,e);switch(O(this,Uo,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==w(this,Us,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(w(this,ke,"f")&&this._emit("toolCallDone",w(this,ke,"f")),O(this,Us,s.index,"f"),O(this,ke,r.step_details.tool_calls[s.index],"f"),w(this,ke,"f")&&this._emit("toolCallCreated",w(this,ke,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":O(this,Uo,void 0,"f"),e.data.step_details.type=="tool_calls"&&w(this,ke,"f")&&(this._emit("toolCallDone",w(this,ke,"f")),O(this,ke,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},ic=function(e){w(this,wi,"f").push(e),this._emit("event",e)},lc=function(e){switch(e.event){case"thread.run.step.created":return w(this,Ze,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=w(this,Ze,"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=ar.accumulateDelta(r,n.delta);w(this,Ze,"f")[e.data.id]=o}return w(this,Ze,"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":w(this,Ze,"f")[e.data.id]=e.data;break}if(w(this,Ze,"f")[e.data.id])return w(this,Ze,"f")[e.data.id];throw new Error("No snapshot available")},uc=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=w(this,le,"m",cc).call(this,s,a)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},cc=function(e,r){return ar.accumulateDelta(r,e)},dc=function(e){switch(O(this,Fs,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":O(this,ir,e.data,"f"),w(this,ke,"f")&&(this._emit("toolCallDone",w(this,ke,"f")),O(this,ke,void 0,"f"));break;case"thread.run.cancelling":break}};var lr=class extends y{constructor(){super(...arguments),this.steps=new Sn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(f`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(f`/threads/${o}/runs/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(f`/threads/${o}/runs/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/threads/${e}/runs`,j,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(f`/threads/${o}/runs/${e}/cancel`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return it.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await We(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return it.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(f`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return it.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};lr.Steps=Sn;var jt=class extends y{constructor(){super(...arguments),this.runs=new lr(this._client),this.messages=new Tn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/threads/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return it.createThreadAssistantStream(e,this._client.beta.threads,r)}};jt.Runs=lr;jt.Messages=Tn;var Pe=class extends y{constructor(){super(...arguments),this.realtime=new $t(this._client),this.chatkit=new Nt(this._client),this.assistants=new bn(this._client),this.threads=new jt(this._client)}};Pe.Realtime=$t;Pe.ChatKit=Nt;Pe.Assistants=bn;Pe.Threads=jt;var ur=class extends y{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Cn=class extends y{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(f`/containers/${o}/files/${e}/content`,{...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var cr=class extends y{constructor(){super(...arguments),this.content=new Cn(this._client)}create(e,r,n){return this._client.post(f`/containers/${e}/files`,Ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(f`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/containers/${e}/files`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(f`/containers/${o}/files/${e}`,{...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};cr.Content=Cn;var Lt=class extends y{constructor(){super(...arguments),this.files=new cr(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/containers/${e}`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Lt.Files=cr;var En=class extends y{create(e,r,n){let{include:o,...s}=r;return this._client.post(f`/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(f`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/conversations/${e}/items`,H,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(f`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var zt=class extends y{constructor(){super(...arguments),this.items=new En(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};zt.Items=En;var dr=class extends y{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&ee(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:(ee(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let u=i.embedding;i.embedding=oc(u)}),a)))}};var On=class extends y{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(f`/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(f`/evals/${o}/runs/${e}/output_items`,j,{query:s,...n,__security:{bearerAuth:!0}})}};var pr=class extends y{constructor(){super(...arguments),this.outputItems=new On(this._client)}create(e,r,n){return this._client.post(f`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(f`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/evals/${e}/runs`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(f`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(f`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};pr.OutputItems=On;var Dt=class extends y{constructor(){super(...arguments),this.runs=new pr(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Dt.Runs=pr;var mr=class extends y{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(f`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(f`/files/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!o.has(a.status);)if(await We(r),a=await this.retrieve(e),Date.now()-s>n)throw new Be({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var Mn=class extends y{};var Pn=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 fr=class extends y{constructor(){super(...arguments),this.graders=new Pn(this._client)}};fr.Graders=Pn;var Rn=class extends y{create(e,r,n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(f`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(f`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var hr=class extends y{constructor(){super(...arguments),this.permissions=new Rn(this._client)}};hr.Permissions=Rn;var $n=class extends y{list(e,r={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/checkpoints`,j,{query:r,...n,__security:{bearerAuth:!0}})}};var gr=class extends y{constructor(){super(...arguments),this.checkpoints=new $n(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(f`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",j,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/events`,j,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(f`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(f`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};gr.Checkpoints=$n;var Re=class extends y{constructor(){super(...arguments),this.methods=new Mn(this._client),this.jobs=new gr(this._client),this.checkpoints=new hr(this._client),this.alpha=new fr(this._client)}};Re.Methods=Mn;Re.Jobs=gr;Re.Checkpoints=hr;Re.Alpha=fr;var Nn=class extends y{};var Ft=class extends y{constructor(){super(...arguments),this.graderModels=new Nn(this._client)}};Ft.GraderModels=Nn;var yr=class extends y{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var _r=class extends y{retrieve(e,r){return this._client.get(f`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var wr=class extends y{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var jn=class extends y{accept(e,r,n){return this._client.post(f`/realtime/calls/${e}/accept`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(f`/realtime/calls/${e}/hangup`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(f`/realtime/calls/${e}/refer`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(f`/realtime/calls/${e}/reject`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Ln=class extends y{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var lt=class extends y{constructor(){super(...arguments),this.clientSecrets=new Ln(this._client),this.calls=new jn(this._client)}};lt.ClientSecrets=Ln;lt.Calls=jn;function pc(t,e){return!e||!Jf(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)}:bi(t,e)}function bi(t,e){let r=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:Yf(e,o)};if(o.type==="message"){let s=o.content.map(a=>a.type==="output_text"?{...a,parsed:Hf(e,a.text)}:a);return{...o,content:s}}return o}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||qs(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 Hf(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Jf(t){return!!Mo(t.text?.format)}function Zf(t){return t?.$brand==="auto-parseable-tool"}function Qf(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Yf(t,e){let r=Qf(t.tools??[],e.name);return{...e,...e,parsed_arguments:Zf(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function qs(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 zn,Bs,Ut,Ks,mc,fc,hc,gc,Ws=class t extends Et{constructor(e){super(),zn.add(this),Bs.set(this,void 0),Ut.set(this,void 0),Ks.set(this,void 0),O(this,Bs,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),w(this,zn,"m",mc).call(this);let s,a=null;"response_id"in r?(s=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=r.starting_after??null):s=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let i of s)w(this,zn,"m",fc).call(this,i,a);if(s.controller.signal?.aborted)throw new X;return w(this,zn,"m",hc).call(this)}[(Bs=new WeakMap,Ut=new WeakMap,Ks=new WeakMap,zn=new WeakSet,mc=function(){this.ended||O(this,Ut,void 0,"f")},fc=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=w(this,zn,"m",gc).call(this,r);switch(o("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new S(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new S(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new S(`expected content to be 'output_text', got ${i.type}`);o("response.output_text.delta",{...r,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=s.output[r.output_index];if(!a)throw new S(`missing output at index ${r.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:o(r.type,r);break}},hc=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");let r=w(this,Ut,"f");if(!r)throw new S("request ended without sending any events");O(this,Ut,void 0,"f");let n=Xf(r,w(this,Bs,"f"));return O(this,Ks,n,"f"),n},gc=function(r){let n=w(this,Ut,"f");if(!n){if(r.type!=="response.created")throw new S(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=O(this,Ut,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 S(`missing output at index ${r.output_index}`);let s=o.type,a=r.part;s==="message"&&a.type!=="reasoning_text"?o.content.push(a):s==="reasoning"&&a.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(a));break}case"response.output_text.delta":{let o=n.output[r.output_index];if(!o)throw new S(`missing output at index ${r.output_index}`);if(o.type==="message"){let s=o.content[r.content_index];if(!s)throw new S(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new S(`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 S(`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 S(`missing output at index ${r.output_index}`);if(o.type==="reasoning"){let s=o.content?.[r.content_index];if(!s)throw new S(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new S(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{O(this,Ut,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,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=w(this,Ks,"f");if(!e)throw new S("stream ended without producing a ChatCompletion");return e}};function Xf(t,e){return pc(t,e)}var Dn=class extends y{list(e,r={},n){return this._client.getAPIList(f`/responses/${e}/input_items`,j,{query:r,...n,__security:{bearerAuth:!0}})}};var Fn=class extends y{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var ut=class extends y{constructor(){super(...arguments),this.inputItems=new Dn(this._client),this.inputTokens=new Fn(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"&&qs(n),n))}retrieve(e,r={},n){return this._client.get(f`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&qs(o),o))}delete(e,r){return this._client.delete(f`/responses/${e}`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>bi(n,e))}stream(e,r){return Ws.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(f`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};ut.InputItems=Dn;ut.InputTokens=Fn;var Un=class extends y{retrieve(e,r){return this._client.get(f`/skills/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var qn=class extends y{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(f`/skills/${o}/versions/${e}/content`,{...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var br=class extends y{constructor(){super(...arguments),this.content=new qn(this._client)}create(e,r={},n){return this._client.post(f`/skills/${e}/versions`,Ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(f`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/skills/${e}/versions`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(f`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};br.Content=qn;var ct=class extends y{constructor(){super(...arguments),this.content=new Un(this._client),this.versions=new br(this._client)}create(e={},r){return this._client.post("/skills",Ct({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(f`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};ct.Content=Un;ct.Versions=br;var Bn=class extends y{create(e,r,n){return this._client.post(f`/uploads/${e}/parts`,me({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var qt=class extends y{constructor(){super(...arguments),this.parts=new Bn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(f`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};qt.Parts=Bn;var yc=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 Kn=class extends y{create(e,r,n){return this._client.post(f`/vector_stores/${e}/file_batches`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(f`/vector_stores/${o}/file_batches/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(f`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(f`/vector_stores/${o}/file_batches/${e}/files`,j,{query:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await We(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...n];async function c(m){for(let h of m){let _=await i.files.create({file:h,purpose:"assistants"},o);l.push(_.id)}}let p=Array(a).fill(u).map(c);return await yc(p),await this.createAndPoll(e,{file_ids:l})}};var Wn=class extends y{create(e,r,n){return this._client.post(f`/vector_stores/${e}/files`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(f`/vector_stores/${o}/files/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(f`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/vector_stores/${e}/files`,j,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(f`/vector_stores/${o}/files/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await We(i);break;case"failed":case"completed":return a}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(f`/vector_stores/${o}/files/${e}/content`,pe,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var dt=class extends y{constructor(){super(...arguments),this.files=new Wn(this._client),this.fileBatches=new Kn(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/vector_stores/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/vector_stores/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",j,{query:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/vector_stores/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(f`/vector_stores/${e}/search`,pe,{body:r,method:"post",...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};dt.Files=Wn;dt.FileBatches=Kn;var Ar=class extends y{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(f`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",H,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(f`/videos/${e}/content`,{query:r,...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(f`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(f`/videos/${e}/remix`,Ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Vn,_c,Vs,xr=class extends y{constructor(){super(...arguments),Vn.add(this)}async unwrap(e,r,n=this._client.webhookSecret,o=300){return await this.verifySignature(e,r,n,o),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");w(this,Vn,"m",_c).call(this,n);let s=v([r]).values,a=w(this,Vn,"m",Vs).call(this,s,"webhook-signature"),i=w(this,Vn,"m",Vs).call(this,s,"webhook-timestamp"),u=w(this,Vn,"m",Vs).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Ke("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-l>o)throw new Ke("Webhook timestamp is too old");if(l>c+o)throw new Ke("Webhook timestamp is too new");let p=a.split(" ").map(I=>I.startsWith("v1,")?I.substring(3):I),m=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=u?`${u}.${i}.${e}`:`${i}.${e}`,_=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let I of p)try{let C=Buffer.from(I,"base64");if(await crypto.subtle.verify("HMAC",_,C,new TextEncoder().encode(h)))return}catch{continue}throw new Ke("The given webhook signature does not match the expected signature")}};Vn=new WeakSet,_c=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")},Vs=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 Ai,xi,Gs,wc,uh="workload-identity-auth",M=class{constructor({baseURL:e=Je("OPENAI_BASE_URL"),apiKey:r=Je("OPENAI_API_KEY")??null,adminAPIKey:n=Je("OPENAI_ADMIN_KEY")??null,organization:o=Je("OPENAI_ORG_ID")??null,project:s=Je("OPENAI_PROJECT_ID")??null,webhookSecret:a=Je("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:i,...u}={}){Ai.add(this),Gs.set(this,void 0),this.completions=new ur(this),this.chat=new Mt(this),this.embeddings=new dr(this),this.files=new mr(this),this.images=new yr(this),this.audio=new He(this),this.moderations=new wr(this),this.models=new _r(this),this.fineTuning=new Re(this),this.graders=new Ft(this),this.vectorStores=new dt(this),this.webhooks=new xr(this),this.beta=new Pe(this),this.batches=new or(this),this.uploads=new qt(this),this.admin=new Rt(this),this.responses=new ut(this),this.realtime=new lt(this),this.conversations=new zt(this),this.evals=new Dt(this),this.containers=new Lt(this),this.skills=new ct(this),this.videos=new Ar(this);let l={apiKey:r,adminAPIKey:n,organization:o,project:s,webhookSecret:a,workloadIdentity:i,...u,baseURL:e||"https://api.openai.com/v1"};if(r&&i)throw new S("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!i)throw new S("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&Iu())throw new S(`It looks like you're running in a browser-like environment.
72
+ ${p}`)}return a},f=Qm(sc);var Xt=class extends w{list(e,r={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,j,{query:r,...n,__security:{bearerAuth:!0}})}};function Po(t){return t!==void 0&&"function"in t&&t.function!==void 0}function ac(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Ro(t){return t?.$brand==="auto-parseable-response-format"}function er(t){return t?.$brand==="auto-parseable-tool"}function ic(t,e){return!e||!ci(e)?{...t,choices:t.choices.map(r=>(uc(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:$o(t,e)}function $o(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Jr;if(n.finish_reason==="content_filter")throw new Zr;return uc(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>tf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ef(e,n.message.content):null}}});return{...t,choices:r}}function ef(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 tf(t,e){let r=t.tools?.find(n=>Po(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:er(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function lc(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>Po(n)&&n.function?.name===e.function.name);return Po(r)&&(er(r)||r?.function.strict||!1)}function ci(t){return Ro(t.response_format)?!0:t.tools?.some(e=>er(e)||e.type==="function"&&e.function.strict===!0)??!1}function uc(t){for(let e of t||[])if(e.type!=="function")throw new S(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function cc(t){for(let e of t??[]){if(e.type!=="function")throw new S(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new S(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var en=t=>t?.role==="assistant",di=t=>t?.role==="tool";var pi,Os,Ps,No,jo,Rs,zo,ot,Lo,$s,Ns,tn,dc,Mt=class{constructor(){pi.add(this),this.controller=new AbortController,Os.set(this,void 0),Ps.set(this,()=>{}),No.set(this,()=>{}),jo.set(this,void 0),Rs.set(this,()=>{}),zo.set(this,()=>{}),ot.set(this,{}),Lo.set(this,!1),$s.set(this,!1),Ns.set(this,!1),tn.set(this,!1),M(this,Os,new Promise((e,r)=>{M(this,Ps,e,"f"),M(this,No,r,"f")}),"f"),M(this,jo,new Promise((e,r)=>{M(this,Rs,e,"f"),M(this,zo,r,"f")}),"f"),_(this,Os,"f").catch(()=>{}),_(this,jo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,pi,"m",dc).bind(this))},0)}_connected(){this.ended||(_(this,Ps,"f").call(this),this._emit("connect"))}get ended(){return _(this,Lo,"f")}get errored(){return _(this,$s,"f")}get aborted(){return _(this,Ns,"f")}abort(){this.controller.abort()}on(e,r){return(_(this,ot,"f")[e]||(_(this,ot,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,ot,"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,ot,"f")[e]||(_(this,ot,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{M(this,tn,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){M(this,tn,!0,"f"),await _(this,jo,"f")}_emit(e,...r){if(_(this,Lo,"f"))return;e==="end"&&(M(this,Lo,!0,"f"),_(this,Rs,"f").call(this));let n=_(this,ot,"f")[e];if(n&&(_(this,ot,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,tn,"f")&&!n?.length&&Promise.reject(o),_(this,No,"f").call(this,o),_(this,zo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,tn,"f")&&!n?.length&&Promise.reject(o),_(this,No,"f").call(this,o),_(this,zo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};Os=new WeakMap,Ps=new WeakMap,No=new WeakMap,jo=new WeakMap,Rs=new WeakMap,zo=new WeakMap,ot=new WeakMap,Lo=new WeakMap,$s=new WeakMap,Ns=new WeakMap,tn=new WeakMap,pi=new WeakSet,dc=function(e){if(M(this,$s,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return M(this,Ns,!0,"f"),this._emit("abort",e);if(e instanceof S)return this._emit("error",e);if(e instanceof Error){let r=new S(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new S(String(e)))};function pc(t){return typeof t.parse=="function"}var xe,mi,js,fi,hi,gi,mc,fc,rf=10,rn=class extends Mt{constructor(){super(...arguments),xe.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),di(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(en(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 S("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,xe,"m",mi).call(this)}async finalMessage(){return await this.done(),_(this,xe,"m",js).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,xe,"m",fi).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,xe,"m",hi).call(this)}async totalUsage(){return await this.done(),_(this,xe,"m",gi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,xe,"m",js).call(this);r&&this._emit("finalMessage",r);let n=_(this,xe,"m",mi).call(this);n&&this._emit("finalContent",n);let o=_(this,xe,"m",fi).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,xe,"m",hi).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,xe,"m",gi).call(this))}async _createChatCompletion(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,xe,"m",mc).call(this,r);let s=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion($o(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:a,...i}=r,u=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:l=rf}=n||{},c=r.tools.map(h=>{if(er(h)){if(!h.$callback)throw new S("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}),p={};for(let h of c)h.type==="function"&&(p[h.function.name||h.function.function.name]=h.function);let m="tools"in r?c.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 A=(await this._createChatCompletion(e,{...i,tool_choice:s,tools:m,messages:[...this.messages]},n)).choices[0]?.message;if(!A)throw new S("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let C of A.tool_calls){if(C.type!=="function")continue;let g=C.id,{name:b,arguments:k}=C.function,z=p[b];if(z){if(u&&u!==b){let L=`Invalid tool_call: ${JSON.stringify(b)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:o,tool_call_id:g,content:L});continue}}else{let L=`Invalid tool_call: ${JSON.stringify(b)}. Available options are: ${Object.keys(p).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:g,content:L});continue}let Q;try{Q=pc(z)?await z.parse(k):k}catch(L){let T=L instanceof Error?L.message:String(L);this._addMessage({role:o,tool_call_id:g,content:T});continue}let V=await z.function(Q,this),K=_(this,xe,"m",fc).call(this,V);if(this._addMessage({role:o,tool_call_id:g,content:K}),u)return}}}};xe=new WeakSet,mi=function(){return _(this,xe,"m",js).call(this).content??null},js=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(en(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new S("stream ended without producing a ChatCompletionMessage with role=assistant")},fi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(en(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},hi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(di(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}},gi=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},mc=function(e){if(e.n!=null&&e.n>1)throw new S("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},fc=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Do=class t extends rn{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),en(e)&&e.content&&this._emit("content",e.content)}};var ie={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},yi=class extends Error{},wi=class extends Error{};function nf(t,e=ie.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return of(t.trim(),e)}var of=(t,e)=>{let r=t.length,n=0,o=m=>{throw new yi(`${m} at position ${n}`)},s=m=>{throw new wi(`${m} at position ${n}`)},a=()=>(p(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||ie.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ie.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ie.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ie.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ie.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ie.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):c()),i=()=>{let m=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(m,++n-Number(h)))}catch(y){s(String(y))}else if(ie.STR&e)try{return JSON.parse(t.substring(m,n-Number(h))+'"')}catch{return JSON.parse(t.substring(m,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,p();let m={};try{for(;t[n]!=="}";){if(p(),n>=r&&ie.OBJ&e)return m;let h=i();p(),n++;try{let y=a();Object.defineProperty(m,h,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(ie.OBJ&e)return m;throw y}p(),t[n]===","&&n++}}catch{if(ie.OBJ&e)return m;o("Expected '}' at end of object")}return n++,m},l=()=>{n++;let m=[];try{for(;t[n]!=="]";)m.push(a()),p(),t[n]===","&&n++}catch{if(ie.ARR&e)return m;o("Expected ']' at end of array")}return n++,m},c=()=>{if(n===0){t==="-"&&ie.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(ie.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 m=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ie.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(m,n))}catch{t.substring(m,n)==="-"&&ie.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(m,t.lastIndexOf("e")))}catch(y){s(String(y))}}},p=()=>{for(;n<r&&`
73
+ \r `.includes(t[n]);)n++};return a()},_i=t=>nf(t,ie.ALL^ie.NUM);var se,st,nn,Ot,bi,zs,xi,Ai,Ii,Ls,vi,hc,tr=class t extends rn{constructor(e){super(),se.add(this),st.set(this,void 0),nn.set(this,void 0),Ot.set(this,void 0),M(this,st,e,"f"),M(this,nn,[],"f")}get currentChatCompletionSnapshot(){return _(this,Ot,"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,se,"m",bi).call(this);let s=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of s)_(this,se,"m",xi).call(this,a);if(s.controller.signal?.aborted)throw new X;return this._addChatCompletion(_(this,se,"m",Ls).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),_(this,se,"m",bi).call(this),this._connected();let o=Ve.fromReadableStream(e,this.controller),s;for await(let a of o)s&&s!==a.id&&this._addChatCompletion(_(this,se,"m",Ls).call(this)),_(this,se,"m",xi).call(this,a),s=a.id;if(o.controller.signal?.aborted)throw new X;return this._addChatCompletion(_(this,se,"m",Ls).call(this))}[(st=new WeakMap,nn=new WeakMap,Ot=new WeakMap,se=new WeakSet,bi=function(){this.ended||M(this,Ot,void 0,"f")},zs=function(r){let n=_(this,nn,"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,nn,"f")[r.index]=n,n)},xi=function(r){if(this.ended)return;let n=_(this,se,"m",hc).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index];o.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.delta.content,s.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),o.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=_(this,se,"m",zs).call(this,s);s.finish_reason&&(_(this,se,"m",Ii).call(this,s),a.current_tool_call_index!=null&&_(this,se,"m",Ai).call(this,s,a.current_tool_call_index));for(let i of o.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(_(this,se,"m",Ii).call(this,s),a.current_tool_call_index!=null&&_(this,se,"m",Ai).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of o.delta.tool_calls??[]){let u=s.message.tool_calls?.[i.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:i.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:i.function?.arguments??""}):(u?.type,void 0))}}},Ai=function(r,n){if(_(this,se,"m",zs).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let a=_(this,st,"f")?.tools?.find(i=>Po(i)&&i.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:er(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},Ii=function(r){let n=_(this,se,"m",zs).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,se,"m",vi).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}))},Ls=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");let r=_(this,Ot,"f");if(!r)throw new S("request ended without sending any chunks");return M(this,Ot,void 0,"f"),M(this,nn,[],"f"),sf(r,_(this,st,"f"))},vi=function(){let r=_(this,st,"f")?.response_format;return Ro(r)?r:null},hc=function(r){var n,o,s,a;let i=_(this,Ot,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=M(this,Ot,{...l,choices:[]},"f");for(let{delta:c,finish_reason:p,index:m,logprobs:h=null,...y}of r.choices){let A=i.choices[m];if(A||(A=i.choices[m]={finish_reason:p,index:m,message:{},logprobs:h,...y}),h)if(!A.logprobs)A.logprobs=Object.assign({},h);else{let{content:V,refusal:K,...L}=h;Object.assign(A.logprobs,L),V&&((n=A.logprobs).content??(n.content=[]),A.logprobs.content.push(...V)),K&&((o=A.logprobs).refusal??(o.refusal=[]),A.logprobs.refusal.push(...K))}if(p&&(A.finish_reason=p,_(this,st,"f")&&ci(_(this,st,"f")))){if(p==="length")throw new Jr;if(p==="content_filter")throw new Zr}if(Object.assign(A,y),!c)continue;let{content:C,refusal:g,function_call:b,role:k,tool_calls:z,...Q}=c;if(Object.assign(A.message,Q),g&&(A.message.refusal=(A.message.refusal||"")+g),k&&(A.message.role=k),b&&(A.message.function_call?(b.name&&(A.message.function_call.name=b.name),b.arguments&&((s=A.message.function_call).arguments??(s.arguments=""),A.message.function_call.arguments+=b.arguments)):A.message.function_call=b),C&&(A.message.content=(A.message.content||"")+C,!A.message.refusal&&_(this,se,"m",vi).call(this)&&(A.message.parsed=_i(A.message.content))),z){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:V,id:K,type:L,function:T,...E}of z){let F=(a=A.message.tool_calls)[V]??(a[V]={});Object.assign(F,E),K&&(F.id=K),L&&(F.type=L),T&&(F.function??(F.function={name:T.name??"",arguments:""})),T?.name&&(F.function.name=T.name),T?.arguments&&(F.function.arguments+=T.arguments,lc(_(this,st,"f"),F)&&(F.function.parsed_arguments=_i(F.function.arguments)))}}}return i},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ve(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function sf(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:a,...i}=t,u={...i,id:r,choices:n.map(({message:l,finish_reason:c,index:p,logprobs:m,...h})=>{if(!c)throw new S(`missing finish_reason for choice ${p}`);let{content:y=null,function_call:A,tool_calls:C,...g}=l,b=l.role;if(!b)throw new S(`missing role for choice ${p}`);if(A){let{arguments:k,name:z}=A;if(k==null)throw new S(`missing function_call.arguments for choice ${p}`);if(!z)throw new S(`missing function_call.name for choice ${p}`);return{...h,message:{content:y,function_call:{arguments:k,name:z},role:b,refusal:l.refusal??null},finish_reason:c,index:p,logprobs:m}}return C?{...h,index:p,finish_reason:c,logprobs:m,message:{...g,role:b,content:y,refusal:l.refusal??null,tool_calls:C.map((k,z)=>{let{function:Q,type:V,id:K,...L}=k,{arguments:T,name:E,...F}=Q||{};if(K==null)throw new S(`missing choices[${p}].tool_calls[${z}].id
74
+ ${Ds(t)}`);if(V==null)throw new S(`missing choices[${p}].tool_calls[${z}].type
75
+ ${Ds(t)}`);if(E==null)throw new S(`missing choices[${p}].tool_calls[${z}].function.name
76
+ ${Ds(t)}`);if(T==null)throw new S(`missing choices[${p}].tool_calls[${z}].function.arguments
77
+ ${Ds(t)}`);return{...L,id:K,type:V,function:{...F,name:E,arguments:T}}})}}:{...h,message:{...g,content:y,role:b,refusal:l.refusal??null},finish_reason:c,index:p,logprobs:m}}),created:o,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ic(u,e)}function Ds(t){return JSON.stringify(t)}var Fo=class t extends tr{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 at=class extends w{constructor(){super(...arguments),this.messages=new Xt(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(f`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return cc(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>$o(n,e))}runTools(e,r){return e.stream?Fo.runTools(this._client,e,r):Do.runTools(this._client,e,r)}stream(e,r){return tr.createChatCompletion(this._client,e,r)}};at.Messages=Xt;var Pt=class extends w{constructor(){super(...arguments),this.completions=new at(this._client)}};Pt.Completions=at;var on=class extends w{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(f`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var sn=class extends w{list(e={},r){return this._client.getAPIList("/organization/audit_logs",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var an=class extends w{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(f`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",fe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",fe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var ln=class extends w{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(f`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var un=class extends w{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",ne,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var cn=class extends w{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}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}})}};var dn=class extends w{create(e,r,n){return this._client.post(f`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/groups/${e}/roles`,ne,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(f`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var pn=class extends w{create(e,r,n){return this._client.post(f`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/groups/${e}/users`,ne,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(f`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Rt=class extends w{constructor(){super(...arguments),this.users=new pn(this._client),this.roles=new dn(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",ne,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Rt.Users=pn;Rt.Roles=dn;var mn=class extends w{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(f`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/api_keys`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var fn=class extends w{list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/certificates`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(f`/organization/projects/${e}/certificates/activate`,fe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(f`/organization/projects/${e}/certificates/deactivate`,fe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var hn=class extends w{listRateLimits(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/rate_limits`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var gn=class extends w{create(e,r,n){return this._client.post(f`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/projects/${e}/roles`,ne,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var yn=class extends w{create(e,r,n){return this._client.post(f`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(f`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/service_accounts`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var wn=class extends w{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(f`/projects/${o}/groups/${e}/roles`,ne,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(f`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends w{constructor(){super(...arguments),this.roles=new wn(this._client)}create(e,r,n){return this._client.post(f`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/groups`,ne,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};rr.Roles=wn;var _n=class extends w{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(f`/projects/${o}/users/${e}/roles`,ne,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(f`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends w{constructor(){super(...arguments),this.roles=new _n(this._client)}create(e,r,n){return this._client.post(f`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(f`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(f`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/projects/${e}/users`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(f`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};nr.Roles=_n;var ke=class extends w{constructor(){super(...arguments),this.users=new nr(this._client),this.serviceAccounts=new yn(this._client),this.apiKeys=new mn(this._client),this.rateLimits=new hn(this._client),this.groups=new rr(this._client),this.roles=new gn(this._client),this.certificates=new fn(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(f`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(f`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ke.Users=nr;ke.ServiceAccounts=yn;ke.APIKeys=mn;ke.RateLimits=hn;ke.Groups=rr;ke.Roles=gn;ke.Certificates=fn;var bn=class extends w{create(e,r,n){return this._client.post(f`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/organization/users/${e}/roles`,ne,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(f`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var or=class extends w{constructor(){super(...arguments),this.roles=new bn(this._client)}retrieve(e,r){return this._client.get(f`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(f`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",H,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(f`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};or.Roles=bn;var Ae=class extends w{constructor(){super(...arguments),this.auditLogs=new sn(this._client),this.adminAPIKeys=new on(this._client),this.usage=new cn(this._client),this.invites=new ln(this._client),this.users=new or(this._client),this.groups=new Rt(this._client),this.roles=new un(this._client),this.certificates=new an(this._client),this.projects=new ke(this._client)}};Ae.AuditLogs=sn;Ae.AdminAPIKeys=on;Ae.Usage=cn;Ae.Invites=ln;Ae.Users=or;Ae.Groups=Rt;Ae.Roles=un;Ae.Certificates=an;Ae.Projects=ke;var $t=class extends w{constructor(){super(...arguments),this.organization=new Ae(this._client)}};$t.Organization=Ae;var gc=Symbol("brand.privateNullableHeaders");function*Mf(t){if(!t)return;if(gc 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():Ga(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=Ga(n[1])?n[1]:[n[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,i])}}var v=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,a]of Mf(n)){let i=s.toLowerCase();o.has(i)||(e.delete(s),o.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[gc]:!0,values:e,nulls:r}};var xn=class extends w{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:v([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var An=class extends w{create(e,r){return this._client.post("/audio/transcriptions",he({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var In=class extends w{create(e,r){return this._client.post("/audio/translations",he({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var He=class extends w{constructor(){super(...arguments),this.transcriptions=new An(this._client),this.translations=new In(this._client),this.speech=new xn(this._client)}};He.Transcriptions=An;He.Translations=In;He.Speech=xn;var sr=class extends w{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",j,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var vn=class extends w{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/assistants/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/assistants/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",j,{query:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/assistants/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Tn=class extends w{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Sn=class extends w{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Nt=class extends w{constructor(){super(...arguments),this.sessions=new Tn(this._client),this.transcriptionSessions=new Sn(this._client)}};Nt.Sessions=Tn;Nt.TranscriptionSessions=Sn;var kn=class extends w{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/chatkit/sessions/${e}/cancel`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Cn=class extends w{retrieve(e,r){return this._client.get(f`/chatkit/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",H,{query:e,...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/chatkit/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(f`/chatkit/threads/${e}/items`,H,{query:r,...n,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var jt=class extends w{constructor(){super(...arguments),this.sessions=new kn(this._client),this.threads=new Cn(this._client)}};jt.Sessions=kn;jt.Threads=Cn;var En=class extends w{create(e,r,n){return this._client.post(f`/threads/${e}/messages`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(f`/threads/${o}/messages/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(f`/threads/${o}/messages/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/threads/${e}/messages`,j,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(f`/threads/${o}/messages/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Mn=class extends w{retrieve(e,r,n){let{thread_id:o,run_id:s,...a}=r;return this._client.get(f`/threads/${o}/runs/${s}/steps/${e}`,{query:a,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(f`/threads/${o}/runs/${e}/steps`,j,{query:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var yc=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 Je=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,ir,Ti,Ze,Fs,Pe,lr,On,ar,Bs,Ce,qs,Us,Bo,qo,Uo,wc,_c,bc,xc,Ac,Ic,vc,it=class extends Mt{constructor(){super(...arguments),le.add(this),Ti.set(this,[]),Ze.set(this,{}),Fs.set(this,{}),Pe.set(this,void 0),lr.set(this,void 0),On.set(this,void 0),ar.set(this,void 0),Bs.set(this,void 0),Ce.set(this,void 0),qs.set(this,void 0),Us.set(this,void 0),Bo.set(this,void 0)}[(Ti=new WeakMap,Ze=new WeakMap,Fs=new WeakMap,Pe=new WeakMap,lr=new WeakMap,On=new WeakMap,ar=new WeakMap,Bs=new WeakMap,Ce=new WeakMap,qs=new WeakMap,Us=new WeakMap,Bo=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,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new ir;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=Ve.fromReadableStream(e,this.controller);for await(let s of o)_(this,le,"m",qo).call(this,s);if(o.controller.signal?.aborted)throw new X;return this._addRun(_(this,le,"m",Uo).call(this))}toReadableStream(){return new Ve(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new ir;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 a={...n,stream:!0},i=await e.submitToolOutputs(r,a,{...o,signal:this.controller.signal});this._connected();for await(let u of i)_(this,le,"m",qo).call(this,u);if(i.controller.signal?.aborted)throw new X;return this._addRun(_(this,le,"m",Uo).call(this))}static createThreadAssistantStream(e,r,n){let o=new ir;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 ir;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,qs,"f")}currentRun(){return _(this,Us,"f")}currentMessageSnapshot(){return _(this,Pe,"f")}currentRunStepSnapshot(){return _(this,Bo,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Ze,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,Fs,"f"))}async finalRun(){if(await this.done(),!_(this,lr,"f"))throw Error("Final run was not received.");return _(this,lr,"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},a=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,le,"m",qo).call(this,i);if(a.controller.signal?.aborted)throw new X;return this._addRun(_(this,le,"m",Uo).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 a={...n,stream:!0},i=await e.create(r,a,{...o,signal:this.controller.signal});this._connected();for await(let u of i)_(this,le,"m",qo).call(this,u);if(i.controller.signal?.aborted)throw new X;return this._addRun(_(this,le,"m",Uo).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(To(s)&&To(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...o);continue}for(let a of o){if(!To(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);let u=s[i];u==null?s.push(a):s[i]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};ir=it,qo=function(e){if(!this.ended)switch(M(this,qs,e,"f"),_(this,le,"m",bc).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",vc).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",_c).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",wc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Uo=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");if(!_(this,lr,"f"))throw Error("Final run has not been received");return _(this,lr,"f")},wc=function(e){let[r,n]=_(this,le,"m",Ac).call(this,e,_(this,Pe,"f"));M(this,Pe,r,"f"),_(this,Fs,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,a=r.content[o.index];if(a&&a.type=="text")this._emit("textDelta",s,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=_(this,On,"f")){if(_(this,ar,"f"))switch(_(this,ar,"f").type){case"text":this._emit("textDone",_(this,ar,"f").text,_(this,Pe,"f"));break;case"image_file":this._emit("imageFileDone",_(this,ar,"f").image_file,_(this,Pe,"f"));break}M(this,On,o.index,"f")}M(this,ar,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,On,"f")!==void 0){let o=e.data.content[_(this,On,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,Pe,"f"));break;case"text":this._emit("textDone",o.text,_(this,Pe,"f"));break}}_(this,Pe,"f")&&this._emit("messageDone",e.data),M(this,Pe,void 0,"f")}},_c=function(e){let r=_(this,le,"m",xc).call(this,e);switch(M(this,Bo,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,Bs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,Ce,"f")&&this._emit("toolCallDone",_(this,Ce,"f")),M(this,Bs,s.index,"f"),M(this,Ce,r.step_details.tool_calls[s.index],"f"),_(this,Ce,"f")&&this._emit("toolCallCreated",_(this,Ce,"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":M(this,Bo,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,Ce,"f")&&(this._emit("toolCallDone",_(this,Ce,"f")),M(this,Ce,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},bc=function(e){_(this,Ti,"f").push(e),this._emit("event",e)},xc=function(e){switch(e.event){case"thread.run.step.created":return _(this,Ze,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Ze,"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=ir.accumulateDelta(r,n.delta);_(this,Ze,"f")[e.data.id]=o}return _(this,Ze,"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,Ze,"f")[e.data.id]=e.data;break}if(_(this,Ze,"f")[e.data.id])return _(this,Ze,"f")[e.data.id];throw new Error("No snapshot available")},Ac=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=_(this,le,"m",Ic).call(this,s,a)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ic=function(e,r){return ir.accumulateDelta(r,e)},vc=function(e){switch(M(this,Us,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":M(this,lr,e.data,"f"),_(this,Ce,"f")&&(this._emit("toolCallDone",_(this,Ce,"f")),M(this,Ce,void 0,"f"));break;case"thread.run.cancelling":break}};var ur=class extends w{constructor(){super(...arguments),this.steps=new Mn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(f`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(f`/threads/${o}/runs/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(f`/threads/${o}/runs/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/threads/${e}/runs`,j,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(f`/threads/${o}/runs/${e}/cancel`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return it.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await Ge(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return it.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(f`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return it.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};ur.Steps=Mn;var zt=class extends w{constructor(){super(...arguments),this.runs=new ur(this._client),this.messages=new En(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/threads/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return it.createThreadAssistantStream(e,this._client.beta.threads,r)}};zt.Runs=ur;zt.Messages=En;var Re=class extends w{constructor(){super(...arguments),this.realtime=new Nt(this._client),this.chatkit=new jt(this._client),this.assistants=new vn(this._client),this.threads=new zt(this._client)}};Re.Realtime=Nt;Re.ChatKit=jt;Re.Assistants=vn;Re.Threads=zt;var cr=class extends w{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Pn=class extends w{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(f`/containers/${o}/files/${e}/content`,{...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var dr=class extends w{constructor(){super(...arguments),this.content=new Pn(this._client)}create(e,r,n){return this._client.post(f`/containers/${e}/files`,Et({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(f`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/containers/${e}/files`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(f`/containers/${o}/files/${e}`,{...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};dr.Content=Pn;var Lt=class extends w{constructor(){super(...arguments),this.files=new dr(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/containers/${e}`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Lt.Files=dr;var Rn=class extends w{create(e,r,n){let{include:o,...s}=r;return this._client.post(f`/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(f`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/conversations/${e}/items`,H,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(f`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var Dt=class extends w{constructor(){super(...arguments),this.items=new Rn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};Dt.Items=Rn;var pr=class extends w{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&te(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:(te(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let u=i.embedding;i.embedding=yc(u)}),a)))}};var $n=class extends w{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(f`/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(f`/evals/${o}/runs/${e}/output_items`,j,{query:s,...n,__security:{bearerAuth:!0}})}};var mr=class extends w{constructor(){super(...arguments),this.outputItems=new $n(this._client)}create(e,r,n){return this._client.post(f`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(f`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/evals/${e}/runs`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(f`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(f`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};mr.OutputItems=$n;var Ft=class extends w{constructor(){super(...arguments),this.runs=new mr(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Ft.Runs=mr;var fr=class extends w{create(e,r){return this._client.post("/files",he({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(f`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(f`/files/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!o.has(a.status);)if(await Ge(r),a=await this.retrieve(e),Date.now()-s>n)throw new Be({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var Nn=class extends w{};var jn=class extends w{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var hr=class extends w{constructor(){super(...arguments),this.graders=new jn(this._client)}};hr.Graders=jn;var zn=class extends w{create(e,r,n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,fe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(f`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,H,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(f`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var gr=class extends w{constructor(){super(...arguments),this.permissions=new zn(this._client)}};gr.Permissions=zn;var Ln=class extends w{list(e,r={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/checkpoints`,j,{query:r,...n,__security:{bearerAuth:!0}})}};var yr=class extends w{constructor(){super(...arguments),this.checkpoints=new Ln(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",j,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/events`,j,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(f`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(f`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};yr.Checkpoints=Ln;var $e=class extends w{constructor(){super(...arguments),this.methods=new Nn(this._client),this.jobs=new yr(this._client),this.checkpoints=new gr(this._client),this.alpha=new hr(this._client)}};$e.Methods=Nn;$e.Jobs=yr;$e.Checkpoints=gr;$e.Alpha=hr;var Dn=class extends w{};var qt=class extends w{constructor(){super(...arguments),this.graderModels=new Dn(this._client)}};qt.GraderModels=Dn;var wr=class extends w{createVariation(e,r){return this._client.post("/images/variations",he({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",he({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 _r=class extends w{retrieve(e,r){return this._client.get(f`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",fe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var br=class extends w{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Fn=class extends w{accept(e,r,n){return this._client.post(f`/realtime/calls/${e}/accept`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(f`/realtime/calls/${e}/hangup`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(f`/realtime/calls/${e}/refer`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(f`/realtime/calls/${e}/reject`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var qn=class extends w{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var lt=class extends w{constructor(){super(...arguments),this.clientSecrets=new qn(this._client),this.calls=new Fn(this._client)}};lt.ClientSecrets=qn;lt.Calls=Fn;function Tc(t,e){return!e||!ih(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)}:Si(t,e)}function Si(t,e){let r=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:ch(e,o)};if(o.type==="message"){let s=o.content.map(a=>a.type==="output_text"?{...a,parsed:ah(e,a.text)}:a);return{...o,content:s}}return o}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||Ks(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 ah(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function ih(t){return!!Ro(t.text?.format)}function lh(t){return t?.$brand==="auto-parseable-tool"}function uh(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function ch(t,e){let r=uh(t.tools??[],e.name);return{...e,...e,parsed_arguments:lh(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Ks(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 Un,Gs,Ut,Ws,Sc,kc,Cc,Ec,Vs=class t extends Mt{constructor(e){super(),Un.add(this),Gs.set(this,void 0),Ut.set(this,void 0),Ws.set(this,void 0),M(this,Gs,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,Un,"m",Sc).call(this);let s,a=null;"response_id"in r?(s=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=r.starting_after??null):s=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let i of s)_(this,Un,"m",kc).call(this,i,a);if(s.controller.signal?.aborted)throw new X;return _(this,Un,"m",Cc).call(this)}[(Gs=new WeakMap,Ut=new WeakMap,Ws=new WeakMap,Un=new WeakSet,Sc=function(){this.ended||M(this,Ut,void 0,"f")},kc=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=_(this,Un,"m",Ec).call(this,r);switch(o("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new S(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new S(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new S(`expected content to be 'output_text', got ${i.type}`);o("response.output_text.delta",{...r,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=s.output[r.output_index];if(!a)throw new S(`missing output at index ${r.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:o(r.type,r);break}},Cc=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");let r=_(this,Ut,"f");if(!r)throw new S("request ended without sending any events");M(this,Ut,void 0,"f");let n=dh(r,_(this,Gs,"f"));return M(this,Ws,n,"f"),n},Ec=function(r){let n=_(this,Ut,"f");if(!n){if(r.type!=="response.created")throw new S(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=M(this,Ut,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 S(`missing output at index ${r.output_index}`);let s=o.type,a=r.part;s==="message"&&a.type!=="reasoning_text"?o.content.push(a):s==="reasoning"&&a.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(a));break}case"response.output_text.delta":{let o=n.output[r.output_index];if(!o)throw new S(`missing output at index ${r.output_index}`);if(o.type==="message"){let s=o.content[r.content_index];if(!s)throw new S(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new S(`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 S(`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 S(`missing output at index ${r.output_index}`);if(o.type==="reasoning"){let s=o.content?.[r.content_index];if(!s)throw new S(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new S(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{M(this,Ut,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,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=_(this,Ws,"f");if(!e)throw new S("stream ended without producing a ChatCompletion");return e}};function dh(t,e){return Tc(t,e)}var Bn=class extends w{list(e,r={},n){return this._client.getAPIList(f`/responses/${e}/input_items`,j,{query:r,...n,__security:{bearerAuth:!0}})}};var Kn=class extends w{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var ut=class extends w{constructor(){super(...arguments),this.inputItems=new Bn(this._client),this.inputTokens=new Kn(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"&&Ks(n),n))}retrieve(e,r={},n){return this._client.get(f`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&Ks(o),o))}delete(e,r){return this._client.delete(f`/responses/${e}`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Si(n,e))}stream(e,r){return Vs.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(f`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};ut.InputItems=Bn;ut.InputTokens=Kn;var Gn=class extends w{retrieve(e,r){return this._client.get(f`/skills/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Wn=class extends w{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(f`/skills/${o}/versions/${e}/content`,{...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var xr=class extends w{constructor(){super(...arguments),this.content=new Wn(this._client)}create(e,r={},n){return this._client.post(f`/skills/${e}/versions`,Et({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(f`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/skills/${e}/versions`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(f`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};xr.Content=Wn;var ct=class extends w{constructor(){super(...arguments),this.content=new Gn(this._client),this.versions=new xr(this._client)}create(e={},r){return this._client.post("/skills",Et({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(f`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};ct.Content=Gn;ct.Versions=xr;var Vn=class extends w{create(e,r,n){return this._client.post(f`/uploads/${e}/parts`,he({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Bt=class extends w{constructor(){super(...arguments),this.parts=new Vn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(f`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(f`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};Bt.Parts=Vn;var Mc=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 Hn=class extends w{create(e,r,n){return this._client.post(f`/vector_stores/${e}/file_batches`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(f`/vector_stores/${o}/file_batches/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(f`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(f`/vector_stores/${o}/file_batches/${e}/files`,j,{query:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await Ge(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...n];async function c(m){for(let h of m){let y=await i.files.create({file:h,purpose:"assistants"},o);l.push(y.id)}}let p=Array(a).fill(u).map(c);return await Mc(p),await this.createAndPoll(e,{file_ids:l})}};var Jn=class extends w{create(e,r,n){return this._client.post(f`/vector_stores/${e}/files`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(f`/vector_stores/${o}/files/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(f`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(f`/vector_stores/${e}/files`,j,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(f`/vector_stores/${o}/files/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await Ge(i);break;case"failed":case"completed":return a}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(f`/vector_stores/${o}/files/${e}/content`,fe,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var dt=class extends w{constructor(){super(...arguments),this.files=new Jn(this._client),this.fileBatches=new Hn(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(f`/vector_stores/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(f`/vector_stores/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",j,{query:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/vector_stores/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(f`/vector_stores/${e}/search`,fe,{body:r,method:"post",...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};dt.Files=Jn;dt.FileBatches=Hn;var Ar=class extends w{create(e,r){return this._client.post("/videos",he({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(f`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",H,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(f`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",he({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(f`/videos/${e}/content`,{query:r,...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",he({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",he({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(f`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(f`/videos/${e}/remix`,Et({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Zn,Oc,Hs,Ir=class extends w{constructor(){super(...arguments),Zn.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,Zn,"m",Oc).call(this,n);let s=v([r]).values,a=_(this,Zn,"m",Hs).call(this,s,"webhook-signature"),i=_(this,Zn,"m",Hs).call(this,s,"webhook-timestamp"),u=_(this,Zn,"m",Hs).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Ke("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-l>o)throw new Ke("Webhook timestamp is too old");if(l>c+o)throw new Ke("Webhook timestamp is too new");let p=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),m=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=u?`${u}.${i}.${e}`:`${i}.${e}`,y=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let C=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",y,C,new TextEncoder().encode(h)))return}catch{continue}throw new Ke("The given webhook signature does not match the expected signature")}};Zn=new WeakSet,Oc=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Hs=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var ki,Ci,Js,Pc,xh="workload-identity-auth",P=class{constructor({baseURL:e=Je("OPENAI_BASE_URL"),apiKey:r=Je("OPENAI_API_KEY")??null,adminAPIKey:n=Je("OPENAI_ADMIN_KEY")??null,organization:o=Je("OPENAI_ORG_ID")??null,project:s=Je("OPENAI_PROJECT_ID")??null,webhookSecret:a=Je("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:i,...u}={}){ki.add(this),Js.set(this,void 0),this.completions=new cr(this),this.chat=new Pt(this),this.embeddings=new pr(this),this.files=new fr(this),this.images=new wr(this),this.audio=new He(this),this.moderations=new br(this),this.models=new _r(this),this.fineTuning=new $e(this),this.graders=new qt(this),this.vectorStores=new dt(this),this.webhooks=new Ir(this),this.beta=new Re(this),this.batches=new sr(this),this.uploads=new Bt(this),this.admin=new $t(this),this.responses=new ut(this),this.realtime=new lt(this),this.conversations=new Dt(this),this.evals=new Ft(this),this.containers=new Lt(this),this.skills=new ct(this),this.videos=new Ar(this);let l={apiKey:r,adminAPIKey:n,organization:o,project:s,webhookSecret:a,workloadIdentity:i,...u,baseURL:e||"https://api.openai.com/v1"};if(r&&i)throw new S("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!i)throw new S("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&ju())throw new S(`It looks like you're running in a browser-like environment.
78
78
 
79
79
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
80
80
  If you understand the risks and have appropriate mitigations in place,
@@ -83,27 +83,27 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
83
83
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
84
84
 
85
85
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
86
- `);this.baseURL=l.baseURL,this.timeout=l.timeout??xi.DEFAULT_TIMEOUT,this.logger=l.logger??console;let c="warn";this.logLevel=c,this.logLevel=Qa(l.logLevel,"ClientOptions.logLevel",this)??Qa(Je("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??bs(),O(this,Gs,Su,"f");let p=Je("OPENAI_CUSTOM_HEADERS");if(p){let m={};for(let h of p.split(`
87
- `)){let _=h.indexOf(":");_>=0&&(m[h.substring(0,_).trim()]=h.substring(_+1).trim())}l.defaultHeaders=v([m,l.defaultHeaders])}this._options=l,i&&(this._workloadIdentityAuth=new ks(i,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=o,this.project=s,this.webhookSecret=a}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 v([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return v([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return v([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return v([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Nu(e)}getUserAgent(){return`${this.constructor.name}/JS ${kt}`}defaultIdempotencyKey(){return`stainless-node-retry-${za()}`}makeStatusError(e,r,n,o){return Y.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 S?n:new S(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new S(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!w(this,Ai,"m",wc).call(this)&&n||this.baseURL,s=gu(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Fa(a)||!Fa(i))&&(r={...i,...a,...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 Qt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:a,url:i,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(ee(this).debug(`[${l}] sending request`,nt({retryOfRequestLogID:n,method:o.method,url:i,options:o,headers:a.headers})),o.signal?.aborted)throw new X;let m=o.__security??{bearerAuth:!0},h=new AbortController,_=await this.fetchWithAuth(i,a,u,h,m).catch(Ao),I=Date.now();if(_ instanceof globalThis.Error){let A=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new X;let k=bo(_)||/timed? ?out/i.test(String(_)+("cause"in _?String(_.cause):""));if(r)return ee(this).info(`[${l}] connection ${k?"timed out":"failed"} - ${A}`),ee(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${A})`,nt({retryOfRequestLogID:n,url:i,durationMs:I-p,message:_.message})),this.retryRequest(o,r,n??l);throw ee(this).info(`[${l}] connection ${k?"timed out":"failed"} - error; no more retries left`),ee(this).debug(`[${l}] connection ${k?"timed out":"failed"} (error; no more retries left)`,nt({retryOfRequestLogID:n,url:i,durationMs:I-p,message:_.message})),_ instanceof Jt||_ instanceof xo?_:k?new Be:new St({cause:_})}let C=[..._.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,k])=>", "+A+": "+JSON.stringify(k)).join(""),g=`[${l}${c}${C}] ${a.method} ${i} ${_.ok?"succeeded":"failed"} with status ${_.status} in ${I-p}ms`;if(!_.ok){if(_.status===401&&this._workloadIdentityAuth&&m.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Ba(_.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let A=await this.shouldRetry(_);if(r&&A){let z=`retrying, ${r} attempts remaining`;return await Ba(_.body),ee(this).info(`${g} - ${z}`),ee(this).debug(`[${l}] response error (${z})`,nt({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:I-p})),this.retryRequest(o,r,n??l,_.headers)}let k=A?"error; no more retries left":"error; not retryable";ee(this).info(`${g} - ${k}`);let L=await _.text().catch(z=>Ao(z).message),Q=wu(L),G=Q?void 0:L;throw ee(this).debug(`[${l}] response error (${k})`,nt({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:G,durationMs:Date.now()-p})),this.makeStatusError(_.status,Q,G,_.headers)}return ee(this).info(g),ee(this).debug(`[${l}] response start`,nt({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:I-p})),{response:_,options:o,controller:h,requestLogID:l,retryOfRequestLogID:n,startTime:p}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new ko(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${uh}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(o);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,p={signal:o.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,a=o?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=o?.get("retry-after");if(i&&!s){let u=parseFloat(i);Number.isNaN(u)?s=Date.parse(i)-Date.now():s=u*1e3}if(s===void 0){let u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,u)}return await We(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,a=Math.min(.5*Math.pow(2,s),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:i}=n,u=this.buildURL(s,a,i);"timeout"in n&&_u("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:c,isStreamingBody:p}=this.buildBody({options:n});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let m=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=v([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))}:{},...vu(),"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(a,e.__security??{bearerAuth:!0}),a.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=v([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:As(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}:{...w(this,Gs,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};xi=M,Gs=new WeakMap,Ai=new WeakSet,wc=function(){return this.baseURL!=="https://api.openai.com/v1"};M.OpenAI=xi;M.DEFAULT_TIMEOUT=6e5;M.OpenAIError=S;M.APIError=Y;M.APIConnectionError=St;M.APIConnectionTimeoutError=Be;M.APIUserAbortError=X;M.NotFoundError=Fr;M.ConflictError=Ur;M.RateLimitError=Br;M.BadRequestError=Lr;M.AuthenticationError=zr;M.InternalServerError=Kr;M.PermissionDeniedError=Dr;M.UnprocessableEntityError=qr;M.InvalidWebhookSignatureError=Ke;M.toFile=Eo;M.Completions=ur;M.Chat=Mt;M.Embeddings=dr;M.Files=mr;M.Images=yr;M.Audio=He;M.Moderations=wr;M.Models=_r;M.FineTuning=Re;M.Graders=Ft;M.VectorStores=dt;M.Webhooks=xr;M.Beta=Pe;M.Batches=or;M.Uploads=qt;M.Admin=Rt;M.Responses=ut;M.Realtime=lt;M.Conversations=zt;M.Evals=Dt;M.Containers=Lt;M.Skills=ct;M.Videos=Ar;function ch(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 Qe(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Be.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===X.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):ch(t)?e=dl.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=wo(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=wo(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=wo(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=wo(t,"MODEL_NOT_FOUND"):e=t,e}var $e=t=>t();function pt(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function dh(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 vi(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var ph="LC_AUTOGENERATED";function Gn(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'."),ph)}function mt(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(!ts.isInstance(t))throw new Error("Invalid generic chat message");return dh(t);default:throw new Error(`Unknown message type: ${e}`)}}function bc(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("codex"))}function Bt(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(n||a){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function Ti(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Ac(t){let e=$e(()=>{if(Ti(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ti(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 xc(){let t=cl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Kt(t,e=!1,r="1.0.0"){let n=Ac(t),o=xc(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function Ic(t,e){let r;return mo(t)?r=ka(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function mh(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function vc(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(Tc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
88
- `)}function Tc(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}: ${Hs(o,e)},`):r.push(`${n}?: ${Hs(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
89
- `)}function Hs(t,e){if(mh(t))return t.anyOf.map(r=>Hs(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["{",Tc(t,e+2),"}"].join(`
90
- `);case"array":return t.items?`${Hs(t.items,e)}[]`:"any[]";default:return""}}function Js(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function Hn(t){return"type"in t&&t.type!=="function"}function Sc(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 kc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Ir(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Zs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Cc(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 Ec(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 Oc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Mc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Pc(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 Rc(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 Nc=Symbol("Let zodToJsonSchema decide on which parser to use"),$c={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"},jc=t=>typeof t=="string"?{...$c,basePath:["#"],definitions:{},name:t}:{...$c,basePath:["#"],definitions:{},...t};var qo=t=>"_def"in t?t._def:t;function Lc(t){if(!t)return!0;for(let e in t)return!1;return!0}var zc=t=>{let e=jc(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[qo(o),{def:qo(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Si(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function V(t,e,r,n,o){t[e]=r,Si(t,e,n,o)}function Dc(){return{}}function Fc(t,e){let r={type:"array"};return t.type?._def?.typeName!==U.ZodAny&&(r.items=P(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&V(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&V(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(V(r,"minItems",t.exactLength.value,t.exactLength.message,e),V(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Uc(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?V(r,"minimum",n.value,n.message,e):V(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),V(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(r,"maximum",n.value,n.message,e):V(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),V(r,"maximum",n.value,n.message,e));break;case"multipleOf":V(r,"multipleOf",n.value,n.message,e);break}return r}function qc(){return{type:"boolean"}}function Bc(t,e){return P(t.type._def,e)}var Kc=(t,e)=>P(t.innerType._def,e);function ki(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ki(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 fh(t,e)}}var fh=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":V(r,"minimum",n.value,n.message,e);break;case"max":V(r,"maximum",n.value,n.message,e);break}return r};function Wc(t,e){return{...P(t.innerType._def,e),default:t.defaultValue()}}function Vc(t,e,r){return e.effectStrategy==="input"?P(t.schema._def,e,r):{}}function Gc(t){return{type:"string",enum:[...t.values]}}var hh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Hc(t,e){let r=[P(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),P(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 a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function Jc(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 Ci,vr={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:()=>(Ci===void 0&&(Ci=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ci),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Qs(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?gh(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":V(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":V(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ne(r,"email",o.message,e);break;case"format:idn-email":Ne(r,"idn-email",o.message,e);break;case"pattern:zod":je(r,vr.email,o.message,e);break}break;case"url":Ne(r,"uri",o.message,e);break;case"uuid":Ne(r,"uuid",o.message,e);break;case"regex":je(r,o.regex,o.message,e);break;case"cuid":je(r,vr.cuid,o.message,e);break;case"cuid2":je(r,vr.cuid2,o.message,e);break;case"startsWith":je(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":je(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Ne(r,"date-time",o.message,e);break;case"date":Ne(r,"date",o.message,e);break;case"time":Ne(r,"time",o.message,e);break;case"duration":Ne(r,"duration",o.message,e);break;case"length":V(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),V(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{je(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ne(r,"ipv4",o.message,e),o.version!=="v4"&&Ne(r,"ipv6",o.message,e);break}case"emoji":je(r,vr.emoji,o.message,e);break;case"ulid":{je(r,vr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ne(r,"binary",o.message,e);break}case"contentEncoding:base64":{V(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{je(r,vr.base64,o.message,e);break}}break}case"nanoid":je(r,vr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var gh=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ne=(t,e,r,n)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):V(t,"format",e,r,n)},je=(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:Zc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):V(t,"pattern",Zc(e,n),r,n)},Zc=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<o.length;l++){if(a){s+=o[l],a=!1;continue}if(n.i){if(i){if(o[l].match(/[a-z]/)){u?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],u=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
86
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??Ci.DEFAULT_TIMEOUT,this.logger=l.logger??console;let c="warn";this.logLevel=c,this.logLevel=ni(l.logLevel,"ClientOptions.logLevel",this)??ni(Je("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??As(),M(this,Js,Du,"f");let p=Je("OPENAI_CUSTOM_HEADERS");if(p){let m={};for(let h of p.split(`
87
+ `)){let y=h.indexOf(":");y>=0&&(m[h.substring(0,y).trim()]=h.substring(y+1).trim())}l.defaultHeaders=v([m,l.defaultHeaders])}this._options=l,i&&(this._workloadIdentityAuth=new Es(i,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=o,this.project=s,this.webhookSecret=a}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 v([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return v([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return v([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return v([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Hu(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ct}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ka()}`}makeStatusError(e,r,n,o){return Y.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 S?n:new S(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new S(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,ki,"m",Pc).call(this)&&n||this.baseURL,s=Eu(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Wa(a)||!Wa(i))&&(r={...i,...a,...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 Yt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:a,url:i,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(te(this).debug(`[${l}] sending request`,nt({retryOfRequestLogID:n,method:o.method,url:i,options:o,headers:a.headers})),o.signal?.aborted)throw new X;let m=o.__security??{bearerAuth:!0},h=new AbortController,y=await this.fetchWithAuth(i,a,u,h,m).catch(Io),A=Date.now();if(y instanceof globalThis.Error){let b=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new X;let k=Ao(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(r)return te(this).info(`[${l}] connection ${k?"timed out":"failed"} - ${b}`),te(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${b})`,nt({retryOfRequestLogID:n,url:i,durationMs:A-p,message:y.message})),this.retryRequest(o,r,n??l);throw te(this).info(`[${l}] connection ${k?"timed out":"failed"} - error; no more retries left`),te(this).debug(`[${l}] connection ${k?"timed out":"failed"} (error; no more retries left)`,nt({retryOfRequestLogID:n,url:i,durationMs:A-p,message:y.message})),y instanceof Zt||y instanceof vo?y:k?new Be:new kt({cause:y})}let C=[...y.headers.entries()].filter(([b])=>b==="x-request-id").map(([b,k])=>", "+b+": "+JSON.stringify(k)).join(""),g=`[${l}${c}${C}] ${a.method} ${i} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${A-p}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&m.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Ja(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let b=await this.shouldRetry(y);if(r&&b){let L=`retrying, ${r} attempts remaining`;return await Ja(y.body),te(this).info(`${g} - ${L}`),te(this).debug(`[${l}] response error (${L})`,nt({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:A-p})),this.retryRequest(o,r,n??l,y.headers)}let k=b?"error; no more retries left":"error; not retryable";te(this).info(`${g} - ${k}`);let z=await y.text().catch(L=>Io(L).message),Q=Pu(z),V=Q?void 0:z;throw te(this).debug(`[${l}] response error (${k})`,nt({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:V,durationMs:Date.now()-p})),this.makeStatusError(y.status,Q,V,y.headers)}return te(this).info(g),te(this).debug(`[${l}] response start`,nt({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:A-p})),{response:y,options:o,controller:h,requestLogID:l,retryOfRequestLogID:n,startTime:p}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Eo(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${xh}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(o);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,p={signal:o.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,a=o?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=o?.get("retry-after");if(i&&!s){let u=parseFloat(i);Number.isNaN(u)?s=Date.parse(i)-Date.now():s=u*1e3}if(s===void 0){let u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,u)}return await Ge(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,a=Math.min(.5*Math.pow(2,s),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:i}=n,u=this.buildURL(s,a,i);"timeout"in n&&Ou("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:c,isStreamingBody:p}=this.buildBody({options:n});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let m=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=v([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))}:{},...zu(),"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(a,e.__security??{bearerAuth:!0}),a.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=v([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,Js,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};Ci=P,Js=new WeakMap,ki=new WeakSet,Pc=function(){return this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=Ci;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=S;P.APIError=Y;P.APIConnectionError=kt;P.APIConnectionTimeoutError=Be;P.APIUserAbortError=X;P.NotFoundError=Kr;P.ConflictError=Gr;P.RateLimitError=Vr;P.BadRequestError=qr;P.AuthenticationError=Ur;P.InternalServerError=Hr;P.PermissionDeniedError=Br;P.UnprocessableEntityError=Wr;P.InvalidWebhookSignatureError=Ke;P.toFile=Oo;P.Completions=cr;P.Chat=Pt;P.Embeddings=pr;P.Files=fr;P.Images=wr;P.Audio=He;P.Moderations=br;P.Models=_r;P.FineTuning=$e;P.Graders=qt;P.VectorStores=dt;P.Webhooks=Ir;P.Beta=Re;P.Batches=sr;P.Uploads=Bt;P.Admin=$t;P.Responses=ut;P.Realtime=lt;P.Conversations=Dt;P.Evals=Ft;P.Containers=Lt;P.Skills=ct;P.Videos=Ar;function Ah(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 Qe(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Be.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===X.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Ah(t)?e=_l.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=xo(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=xo(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=xo(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=xo(t,"MODEL_NOT_FOUND"):e=t,e}var Ne=t=>t();function pt(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Ih(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 Mi(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var vh="LC_AUTOGENERATED";function Qn(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'."),vh)}function mt(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(!ns.isInstance(t))throw new Error("Invalid generic chat message");return Ih(t);default:throw new Error(`Unknown message type: ${e}`)}}function Rc(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("codex"))}function Kt(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(n||a){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function Oi(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function $c(t){let e=Ne(()=>{if(Oi(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Oi(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 Nc(){let t=wl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Gt(t,e=!1,r="1.0.0"){let n=$c(t),o=Nc(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function jc(t,e){let r;return go(t)?r=Ra(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Th(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function zc(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(Lc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
88
+ `)}function Lc(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}: ${Zs(o,e)},`):r.push(`${n}?: ${Zs(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
89
+ `)}function Zs(t,e){if(Th(t))return t.anyOf.map(r=>Zs(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["{",Lc(t,e+2),"}"].join(`
90
+ `);case"array":return t.items?`${Zs(t.items,e)}[]`:"any[]";default:return""}}function Qs(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 Yn(t){return"type"in t&&t.type!=="function"}function Dc(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 Fc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function vr(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 Ys(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function qc(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 Uc(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 Bc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Kc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Gc(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 Wc(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 Hc=Symbol("Let zodToJsonSchema decide on which parser to use"),Vc={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"},Jc=t=>typeof t=="string"?{...Vc,basePath:["#"],definitions:{},name:t}:{...Vc,basePath:["#"],definitions:{},...t};var Ko=t=>"_def"in t?t._def:t;function Zc(t){if(!t)return!0;for(let e in t)return!1;return!0}var Qc=t=>{let e=Jc(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])=>[Ko(o),{def:Ko(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Pi(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function W(t,e,r,n,o){t[e]=r,Pi(t,e,n,o)}function Yc(){return{}}function Xc(t,e){let r={type:"array"};return t.type?._def?.typeName!==U.ZodAny&&(r.items=R(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&W(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&W(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(W(r,"minItems",t.exactLength.value,t.exactLength.message,e),W(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ed(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?W(r,"minimum",n.value,n.message,e):W(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),W(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?W(r,"maximum",n.value,n.message,e):W(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),W(r,"maximum",n.value,n.message,e));break;case"multipleOf":W(r,"multipleOf",n.value,n.message,e);break}return r}function td(){return{type:"boolean"}}function rd(t,e){return R(t.type._def,e)}var nd=(t,e)=>R(t.innerType._def,e);function Ri(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Ri(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 Sh(t,e)}}var Sh=(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":W(r,"minimum",n.value,n.message,e);break;case"max":W(r,"maximum",n.value,n.message,e);break}return r};function od(t,e){return{...R(t.innerType._def,e),default:t.defaultValue()}}function sd(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function ad(t){return{type:"string",enum:[...t.values]}}var kh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function id(t,e){let r=[R(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),R(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(kh(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function ld(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 $i,Tr={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:()=>($i===void 0&&($i=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$i),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 Xs(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Ch(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":W(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":W(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":je(r,"email",o.message,e);break;case"format:idn-email":je(r,"idn-email",o.message,e);break;case"pattern:zod":ze(r,Tr.email,o.message,e);break}break;case"url":je(r,"uri",o.message,e);break;case"uuid":je(r,"uuid",o.message,e);break;case"regex":ze(r,o.regex,o.message,e);break;case"cuid":ze(r,Tr.cuid,o.message,e);break;case"cuid2":ze(r,Tr.cuid2,o.message,e);break;case"startsWith":ze(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":ze(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":je(r,"date-time",o.message,e);break;case"date":je(r,"date",o.message,e);break;case"time":je(r,"time",o.message,e);break;case"duration":je(r,"duration",o.message,e);break;case"length":W(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),W(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ze(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&je(r,"ipv4",o.message,e),o.version!=="v4"&&je(r,"ipv6",o.message,e);break}case"emoji":ze(r,Tr.emoji,o.message,e);break;case"ulid":{ze(r,Tr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{je(r,"binary",o.message,e);break}case"contentEncoding:base64":{W(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ze(r,Tr.base64,o.message,e);break}}break}case"nanoid":ze(r,Tr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Ch=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),je=(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}}})):W(t,"format",e,r,n)},ze=(t,e,r,n)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:ud(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):W(t,"pattern",ud(e,n),r,n)},ud=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<o.length;l++){if(a){s+=o[l],a=!1;continue}if(n.i){if(i){if(o[l].match(/[a-z]/)){u?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],u=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
91
91
  ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
92
92
  ]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
93
93
  `:`[${o[l]}\r
94
- ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Ys(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===U.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Qs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===U.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function Qc(t,e){if(e.mapStrategy==="record")return Ys(t,e);let r=P(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=P(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 Yc(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 Xc(){return{not:{}}}function ed(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Bo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rd(t,e){if(e.target==="openApi3")return td(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Bo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Bo[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return td(t,e)}var td=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>P(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 nd(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:Bo[t.innerType._def.typeName],nullable:!0}:{type:[Bo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=P(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=P(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function od(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",Si(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?V(r,"minimum",n.value,n.message,e):V(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),V(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(r,"maximum",n.value,n.message,e):V(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),V(r,"maximum",n.value,n.message,e));break;case"multipleOf":V(r,"multipleOf",n.value,n.message,e);break}return r}function yh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":P(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":P(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function sd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=P(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:yh(t,e)};return r.required.length||delete r.required,r}var ad=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return P(t.innerType._def,{...e,currentPath:e.currentPath});let r=P(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var id=(t,e)=>{if(e.pipeStrategy==="input")return P(t.in._def,e);if(e.pipeStrategy==="output")return P(t.out._def,e);let r=P(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=P(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function ld(t,e){return P(t.type._def,e)}function ud(t,e){let n={type:"array",uniqueItems:!0,items:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&V(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&V(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function cd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>P(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:P(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>P(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function dd(){return{not:{}}}function pd(){return{}}var md=(t,e)=>P(t.innerType._def,e);function P(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Nc)return a}if(n&&!r){let a=_h(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=bh(t,t.typeName,e,r);return s&&Ah(t,e,s),o.jsonSchema=s,s}var _h=(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:wh(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}},wh=(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("/")},bh=(t,e,r,n)=>{switch(e){case U.ZodString:return Qs(t,r);case U.ZodNumber:return od(t,r);case U.ZodObject:return sd(t,r);case U.ZodBigInt:return Uc(t,r);case U.ZodBoolean:return qc();case U.ZodDate:return ki(t,r);case U.ZodUndefined:return dd();case U.ZodNull:return ed(r);case U.ZodArray:return Fc(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return rd(t,r);case U.ZodIntersection:return Hc(t,r);case U.ZodTuple:return cd(t,r);case U.ZodRecord:return Ys(t,r);case U.ZodLiteral:return Jc(t,r);case U.ZodEnum:return Gc(t);case U.ZodNativeEnum:return Yc(t);case U.ZodNullable:return nd(t,r);case U.ZodOptional:return ad(t,r);case U.ZodMap:return Qc(t,r);case U.ZodSet:return ud(t,r);case U.ZodLazy:return P(t.getter()._def,r);case U.ZodPromise:return ld(t,r);case U.ZodNaN:case U.ZodNever:return Xc();case U.ZodEffects:return Vc(t,r,n);case U.ZodAny:return Dc();case U.ZodUnknown:return pd();case U.ZodDefault:return Wc(t,r);case U.ZodBranded:return Bc(t,r);case U.ZodReadonly:return md(t,r);case U.ZodCatch:return Kc(t,r);case U.ZodPipeline:return id(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(o=>{})(e)}},Ah=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ei=(t,e)=>{let r=zc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=P(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Lc(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let p=Object.entries(r.definitions).filter(([m])=>!l.has(m));if(p.length===0)break;for(let[m,h]of p)u[m]=P(qo(h),{...r,currentPath:[...r.basePath,r.definitionPath,m]},!0)??{},l.add(m)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function fd(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 ft(e,[],e)}function Oi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Oi(e))return!0;for(let e of t.anyOf??[])if(Oi(e))return!0;return!1}function ft(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Tr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(Tr(n))for(let[m,h]of Object.entries(n))ft(h,[...e,"$defs",m],r);let o=t.definitions;if(Tr(o))for(let[m,h]of Object.entries(o))ft(h,[...e,"definitions",m],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(Tr(i)){for(let[m,h]of Object.entries(i))if(!Oi(h)&&!a.includes(m))throw new Error(`Zod field at \`${[...e,"properties",m].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(i),t.properties=Object.fromEntries(Object.entries(i).map(([m,h])=>[m,ft(h,[...e,"properties",m],r)]))}let u=t.items;Tr(u)&&(t.items=ft(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((m,h)=>ft(m,[...e,"anyOf",String(h)],r)));let c=t.allOf;if(Array.isArray(c))if(c.length===1){let m=ft(c[0],[...e,"allOf","0"],r);Object.assign(t,m),delete t.allOf}else t.allOf=c.map((m,h)=>ft(m,[...e,"allOf",String(h)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Ih(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let m=xh(r,p);if(typeof m=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!Tr(m))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(m)}`);return Object.assign(t,{...m,...t}),delete t.$ref,ft(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(!Tr(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 Tr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ih(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function vh(t,e){return Ei(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Th(t){return fd(Al(t,{target:"draft-7"}))}function Sh(t){return"_zod"in t}function hd(t,e,r){return Gu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Sh(t)?Th(t):vh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var gd=["jsonSchema","functionCalling","jsonMode"];function yd(t,e){if(typeof e<"u"&&!gd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${gd.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 kh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function _d(t,e,r){if(xl(t))return hd(t,e,r);if(Pr(t))return kh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Fe(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 wd(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 bd={"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},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Jn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Sr=class extends co{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.4.3")}_getReasoningParams(t){if(!pt(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&&tt(t.json_schema.schema)?_d(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=Bt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Kt(r.defaultHeaders),this.client=new M(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Ir(t)?Rc(t.metadata.customTool):is(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ic(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(Hn(n)||Ir(n))return n;if(Sc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return mo(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(mt(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,c=s;if(c._getType()==="function"&&(l-=2),c.additional_kwargs?.function_call&&(l+=3),c?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(c.additional_kwargs.function_call)),l+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=vc(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 Qe(o)}})}get profile(){return bd[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=yd(this.model,e?.method);if(i==="jsonMode"){n=Sa(o);let u=Fe(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=Fe(o),l={name:s??"extract",description:os(u),schema:tt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),tt(o)||yt(o)){let c=Sa(o);n=Ue.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:c.invoke(p.content))}else n=new kl}else{let u=s??"extract",l=Fe(o),c;tt(o)||yt(o)?c={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(c=o,u=o.name):(u=o.title??u,c={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:c}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=El(o,u)}return Ol(r,n,a)}};var Xs={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=ba({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=wa(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=wa(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=ba({dataUrl:t.url}),r=Gn(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=Gn(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`)}},Mi=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(ls(l,{returnId:!0}))}catch(c){a.push($r(l,c.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new R({content:wd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new ts(t.content||"",t.role??"unknown")}},Pi=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ia({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new et({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new rs({content:s,response_metadata:i}):o==="developer"?new rs({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new fl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new xa({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new ml({content:s,role:o,response_metadata:i})},Ad=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=hl(()=>{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=Gn(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}}}},xd=({message:t,model:e})=>{let r=mt(t);if(r==="system"&&pt(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")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="tool"&&q.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")};function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=Ad(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Ko=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return xd({message:r});let n=mt(r);n==="system"&&pt(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>Xo(a)?es(a,Xs):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),R.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Cl):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),q.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 ea=class extends Sr{constructor(t,e){super(Jn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Js(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),pt(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=Ko({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let h of a){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let _=h.generationInfo?.completion??0;i[_]===void 0?i[_]=h:i[_]=i[_].concat(h)}let u=Object.entries(i).sort(([h],[_])=>parseInt(h,10)-parseInt(_,10)).map(([h,_])=>_),{functions:l,function_call:c}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,c),m=await this._getNumTokensFromGenerations(u);return n.input_tokens=p,n.output_tokens=m,n.total_tokens=p+m,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:c,completion_tokens_details:p}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(n.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let m=[];for(let h of a?.choices??[]){let _={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},a)};_.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},gt(_.message)&&(_.message.usage_metadata=n),_.message=new R(Object.fromEntries(Object.entries(_.message).filter(([I])=>!I.startsWith("lc_")))),m.push(_)}return{generations:m,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let n=Ko({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:c}=l;if(!c)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(c,u,s);s=c.role??s;let m={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let h={...m};l.finish_reason!=null&&(h.finish_reason=l.finish_reason,h.system_fingerprint=u.system_fingerprint,h.model_name=u.model,h.service_tier=u.service_tier),this.logprobs&&(h.logprobs=l.logprobs);let _=new uo({message:p,text:p.content,generationInfo:h});yield _,await r?.handleLLMNewToken(_.text??"",m,void 0,void 0,void 0,{chunk:_})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},c=new uo({message:new et({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield c,await r?.handleLLMNewToken(c.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:c})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Qe(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Pi({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Mi({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var ta="__openai_function_call_ids__";function Ed(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 Eh(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 Ri=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}},ra=t=>{if(t.error){let u=new Error(t.error.message);throw u.name=t.error.code,u}let e,r=[],n=[],o=[],s=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){let l={...u};return delete l.parsed_arguments,l}return u}),a={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:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let u of t.output)if(u.type==="message")e=u.id,r.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(i.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(Ed),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(i.refusal=l.refusal,[]):l));else if(u.type==="function_call"){let l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{n.push(ls(l,{returnId:!0}))}catch(c){let p;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(p=c.message),o.push($r(l,p))}i[ta]??={},u.id&&(i[ta][u.call_id]=u.id)}else if(u.type==="reasoning"){i.reasoning=u;let l=u.summary?.map(c=>c.text).filter(Boolean).join("");l&&r.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){let l=Cc(u);l?n.push(l):o.push($r(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){let l=Ec(u);l?n.push(l):o.push($r(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&r.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),i.tool_outputs??=[],i.tool_outputs.push(u)):(i.tool_outputs??=[],i.tool_outputs.push(u));return new R({id:e,content:r,tool_calls:n,invalid_tool_calls:o,usage_metadata:Ri(t.usage),additional_kwargs:i,response_metadata:a})},Od=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}},$i=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[Ed(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){i=t.item.id;let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[ta]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"){let u=ra(t.response);n=Ri(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text&&(a.parsed??=JSON.parse(u.text));for(let[l,c]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=c)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((c,p)=>({...c,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta});else return t.type==="response.image_generation_call.partial_image",null;return new uo({text:e.map(u=>u.text).join(""),message:new et({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},Md=t=>{let e=R.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=$e(()=>{try{let g=mt(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=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 c=(g,A)=>{o||(o={type:"message",role:n,content:[],...A?{phase:A}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...g]:[...g]:o.content.push(...g)},p=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},m=g=>{let A=$e(()=>{let k=g.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(g.fileId)return{type:"input_image",detail:A,file_id:g.fileId};if(g.url)return{type:"input_image",detail:A,image_url:g.url};if(g.data){let k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${g.mimeType??"image/png"};base64,${k}`}}},h=g=>{if(g.fileId){let A=vi(g);return{type:"input_file",file_id:g.fileId,...A?{filename:A}:{}}}if(g.url){let A=vi(g);return{...A?{filename:A}:{},type:"input_file",file_url:g.url}}if(g.data){let A=Gn(g),k=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,${k}`,filename:A}}},_=g=>{let A=$e(()=>{if(Array.isArray(g.summary)){let Q=g.summary?.map(G=>G?.text).filter(G=>typeof G=="string")??[];if(Q.length>0)return Q}return g.reasoning?[g.reasoning]:[]}),k=A.length>0?A.map(Q=>({type:"summary_text",text:Q})):[{type:"summary_text",text:""}],L={type:"reasoning",id:g.id??"",summary:k};return g.reasoning&&(L.content=[{type:"reasoning_text",text:g.reasoning}]),L},I=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:p(g.args)}),C=g=>{let A=p(g.output),k=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:A,...k?{status:k}:{}}};for(let g of t.contentBlocks)if(g.type==="text"){let A=$e(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});c([{type:"input_text",text:g.text}],A)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield _(g);else if(g.type==="tool_call"){yield*l();let A=g.id??"";A&&(s.add(A),i.delete(A)),yield I(g)}else if(g.type==="tool_call_chunk"){if(g.id){let A=i.get(g.id)??{name:g.name,args:[]};g.name&&(A.name=g.name),g.args&&A.args.push(g.args),i.set(g.id,A)}}else if(g.type==="server_tool_call"){yield*l();let A=g.id??"";A&&(a.add(A),u.delete(A)),yield I(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let A=u.get(g.id)??{name:g.name,args:[]};g.name&&(A.name=g.name),g.args&&A.args.push(g.args),u.set(g.id,A)}}else if(g.type==="server_tool_call_result")yield*l(),yield C(g);else if(g.type!=="audio")if(g.type==="file"){let A=h(g);A&&c([A])}else if(g.type==="image"){let A=m(g);A&&c([A])}else if(g.type==="video"){let A=h(g);A&&c([A])}else g.type==="text-plain"?g.text&&c([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(let[g,A]of i){if(!g||s.has(g))continue;let k=A.args.join("");!A.name&&!k||(yield{type:"function_call",call_id:g,name:A.name??"",arguments:k})}for(let[g,A]of u){if(!g||a.has(g))continue;let k=A.args.join("");!A.name&&!k||(yield{type:"function_call",call_id:g,name:A.name??"",arguments:k})}}return Array.from(r())},na=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Md(n);let s=n.additional_kwargs,a=mt(n);if(a==="system"&&pt(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(m=>m.type==="input_image");if(l)return l;let c=i.content.find(m=>m.type==="computer_screenshot");if(c)return c;let p=i.content.find(m=>m.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(_=>"type"in _))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let _=Od(u);i.push(_)}let{content:c}=n;if(s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),typeof c=="string"||c.length>0){let _={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:$e(()=>typeof c=="string"?c:c.flatMap(I=>{if(I.type==="text"){let C=I;return{type:"output_text",text:C.text,annotations:(C.annotations??[]).map(Eh)}}return I.type==="output_text"||I.type==="refusal"?I:[]})),phase:$e(()=>{if(Array.isArray(c))return c.find(I=>"phase"in I&&typeof I.phase=="string")?.phase})};i.push(_)}let p=s?.[ta];R.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(_=>Mc(_)?{type:"custom_tool_call",id:_.call_id,call_id:_.id??"",input:_.args.input,name:_.name}:Oc(_)?{type:"computer_call",id:_.call_id,call_id:_.id??"",action:_.args.action}:{type:"function_call",name:_.name,arguments:JSON.stringify(_.args),call_id:_.id,...e?{}:{id:p?.[_.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(_=>({type:"function_call",name:_.function.name,call_id:_.id,arguments:_.function.arguments,...e?{}:{id:p?.[_.id]}})));let m=o?.output?.length?o?.output:s.tool_outputs,h=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(m!=null){let _=m?.filter(I=>h.includes(I.type));_.length>0&&i.push(..._)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Xo(l)?es(l,Xs):l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:$e(()=>{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:$e(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]));return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});var oa=class extends Sr{constructor(t,e){super(Jn(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:kc(t?.tool_choice)?t?.tool_choice:(()=>{let o=Js(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:na({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:ra(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*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:na({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let o of n){if(e.signal?.aborted)return;let s=$i(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}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 Qe(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Hn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(Ir(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(is(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Zs(n)&&r.push(Pc(n));return r}};var sa=class Pd extends Sr{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Jn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new oa(n),this.completions=n?.completions??new ea(n)}_useResponsesApi(e){let r=e?.tools?.some(Hn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Zs)||e?.tools?.some(Ir);return this.useResponsesApi||r||n||o||bc(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*_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 Pd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var $h=x.object({type:x.literal("screenshot")}),Nh=x.object({type:x.literal("click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),jh=x.object({type:x.literal("double_click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),Lh=x.object({type:x.literal("drag"),path:x.array(x.object({x:x.number(),y:x.number()}))}),zh=x.object({type:x.literal("keypress"),keys:x.array(x.string())}),Dh=x.object({type:x.literal("move"),x:x.number(),y:x.number()}),Fh=x.object({type:x.literal("scroll"),x:x.number(),y:x.number(),scroll_x:x.number(),scroll_y:x.number()}),Uh=x.object({type:x.literal("type"),text:x.string()}),qh=x.object({type:x.literal("wait"),duration:x.number().optional()}),Bh=x.union([$h,Nh,jh,Lh,zh,Dh,Fh,Uh,qh]),C1=x.object({action:Bh});var Kh=x.object({type:x.literal("exec"),command:x.array(x.string()),env:x.record(x.string(),x.string()).optional(),working_directory:x.string().optional(),timeout_ms:x.number().optional(),user:x.string().optional()}),P1=x.union([Kh]);var j1=x.object({commands:x.array(x.string()).describe("Array of shell commands to execute"),timeout_ms:x.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:x.number().optional().describe("Optional maximum number of characters to return from each command")});var Wh=x.object({type:x.literal("create_file"),path:x.string(),diff:x.string()}),Vh=x.object({type:x.literal("update_file"),path:x.string(),diff:x.string()}),Gh=x.object({type:x.literal("delete_file"),path:x.string()}),F1=x.union([Wh,Vh,Gh]);var Nd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Zh={default:"text-embedding-ada-002"},Ni=new Map,aa=null,Qh=()=>{let t=$d.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},Yh=async t=>{let e=Qh();Ni.size===0&&(aa||(aa=(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=>Ni.set(o.name,o))}catch(n){throw aa=null,n}})()),await aa);let r=Ni.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Xh=async(t="default")=>await Yh(Nd[t]);var Qn=(t,e)=>e,jd=(t,e)=>({...t,...e}),Ld=(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(`
94
+ ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function ea(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===U.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Xs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===U.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function cd(t,e){if(e.mapStrategy==="record")return ea(t,e);let r=R(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function dd(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 pd(){return{not:{}}}function md(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Go={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hd(t,e){if(e.target==="openApi3")return fd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Go&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Go[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return fd(t,e)}var fd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>R(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function gd(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:Go[t.innerType._def.typeName],nullable:!0}:{type:[Go[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function yd(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",Pi(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?W(r,"minimum",n.value,n.message,e):W(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),W(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?W(r,"maximum",n.value,n.message,e):W(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),W(r,"maximum",n.value,n.message,e));break;case"multipleOf":W(r,"multipleOf",n.value,n.message,e);break}return r}function Eh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function wd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=R(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:Eh(t,e)};return r.required.length||delete r.required,r}var _d=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return R(t.innerType._def,{...e,currentPath:e.currentPath});let r=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var bd=(t,e)=>{if(e.pipeStrategy==="input")return R(t.in._def,e);if(e.pipeStrategy==="output")return R(t.out._def,e);let r=R(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=R(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function xd(t,e){return R(t.type._def,e)}function Ad(t,e){let n={type:"array",uniqueItems:!0,items:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&W(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&W(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Id(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:R(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function vd(){return{not:{}}}function Td(){return{}}var Sd=(t,e)=>R(t.innerType._def,e);function R(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Hc)return a}if(n&&!r){let a=Mh(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Ph(t,t.typeName,e,r);return s&&Rh(t,e,s),o.jsonSchema=s,s}var Mh=(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:Oh(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}},Oh=(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("/")},Ph=(t,e,r,n)=>{switch(e){case U.ZodString:return Xs(t,r);case U.ZodNumber:return yd(t,r);case U.ZodObject:return wd(t,r);case U.ZodBigInt:return ed(t,r);case U.ZodBoolean:return td();case U.ZodDate:return Ri(t,r);case U.ZodUndefined:return vd();case U.ZodNull:return md(r);case U.ZodArray:return Xc(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return hd(t,r);case U.ZodIntersection:return id(t,r);case U.ZodTuple:return Id(t,r);case U.ZodRecord:return ea(t,r);case U.ZodLiteral:return ld(t,r);case U.ZodEnum:return ad(t);case U.ZodNativeEnum:return dd(t);case U.ZodNullable:return gd(t,r);case U.ZodOptional:return _d(t,r);case U.ZodMap:return cd(t,r);case U.ZodSet:return Ad(t,r);case U.ZodLazy:return R(t.getter()._def,r);case U.ZodPromise:return xd(t,r);case U.ZodNaN:case U.ZodNever:return pd();case U.ZodEffects:return sd(t,r,n);case U.ZodAny:return Yc();case U.ZodUnknown:return Td();case U.ZodDefault:return od(t,r);case U.ZodBranded:return rd(t,r);case U.ZodReadonly:return Sd(t,r);case U.ZodCatch:return nd(t,r);case U.ZodPipeline:return bd(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(o=>{})(e)}},Rh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ni=(t,e)=>{let r=Qc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=R(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Zc(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let p=Object.entries(r.definitions).filter(([m])=>!l.has(m));if(p.length===0)break;for(let[m,h]of p)u[m]=R(Ko(h),{...r,currentPath:[...r.basePath,r.definitionPath,m]},!0)??{},l.add(m)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function kd(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 ft(e,[],e)}function ji(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(ji(e))return!0;for(let e of t.anyOf??[])if(ji(e))return!0;return!1}function ft(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Sr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(Sr(n))for(let[m,h]of Object.entries(n))ft(h,[...e,"$defs",m],r);let o=t.definitions;if(Sr(o))for(let[m,h]of Object.entries(o))ft(h,[...e,"definitions",m],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(Sr(i)){for(let[m,h]of Object.entries(i))if(!ji(h)&&!a.includes(m))throw new Error(`Zod field at \`${[...e,"properties",m].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(i),t.properties=Object.fromEntries(Object.entries(i).map(([m,h])=>[m,ft(h,[...e,"properties",m],r)]))}let u=t.items;Sr(u)&&(t.items=ft(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((m,h)=>ft(m,[...e,"anyOf",String(h)],r)));let c=t.allOf;if(Array.isArray(c))if(c.length===1){let m=ft(c[0],[...e,"allOf","0"],r);Object.assign(t,m),delete t.allOf}else t.allOf=c.map((m,h)=>ft(m,[...e,"allOf",String(h)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Nh(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let m=$h(r,p);if(typeof m=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!Sr(m))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(m)}`);return Object.assign(t,{...m,...t}),delete t.$ref,ft(t,e,r)}return t}function $h(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(!Sr(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 Sr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function jh(t,e){return Ni(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function zh(t){return kd(El(t,{target:"draft-7"}))}function Lh(t){return"_zod"in t}function Cd(t,e,r){return ac({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Lh(t)?zh(t):jh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var Ed=["jsonSchema","functionCalling","jsonMode"];function Md(t,e){if(typeof e<"u"&&!Ed.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Ed.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 Dh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Od(t,e,r){if(Ml(t))return Cd(t,e,r);if($r(t))return Dh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Fe(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>kl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function Pd(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 Rd={"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},"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 Xn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var kr=class extends ho{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.4.3")}_getReasoningParams(t){if(!pt(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&&tt(t.json_schema.schema)?Od(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=Kt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Gt(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return vr(t)?Wc(t.metadata.customTool):us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:jc(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(Yn(n)||vr(n))return n;if(Dc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return go(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(mt(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,c=s;if(c._getType()==="function"&&(l-=2),c.additional_kwargs?.function_call&&(l+=3),c?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(c.additional_kwargs.function_call)),l+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=zc(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 Qe(o)}})}get profile(){return Rd[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Md(this.model,e?.method);if(i==="jsonMode"){n=Pa(o);let u=Fe(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=Fe(o),l={name:s??"extract",description:as(u),schema:tt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),tt(o)||wt(o)){let c=Pa(o);n=qe.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:c.invoke(p.content))}else n=new Nl}else{let u=s??"extract",l=Fe(o),c;tt(o)||wt(o)?c={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(c=o,u=o.name):(u=o.title??u,c={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:c}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=zl(o,u)}return Ll(r,n,a)}};var ta={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=Sa({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=Ta(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=Ta(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=Sa({dataUrl:t.url}),r=Qn(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=Qn(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`)}},zi=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(cs(l,{returnId:!0}))}catch(c){a.push(jr(l,c.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new $({content:Pd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new ns(t.content||"",t.role??"unknown")}},Li=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ea({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new et({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new os({content:s,response_metadata:i}):o==="developer"?new os({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Al({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new Ca({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new xl({content:s,role:o,response_metadata:i})},$d=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=Il(()=>{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=Qn(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}}}},Nd=({message:t,model:e})=>{let r=mt(t);if(r==="system"&&pt(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")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};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 a=$d(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Wo=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Nd({message:r});let n=mt(r);n==="system"&&pt(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>ts(a)?rs(a,ta):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),$.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(jl):(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 ra=class extends kr{constructor(t,e){super(Xn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Qs(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),pt(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=Wo({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let h of a){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let y=h.generationInfo?.completion??0;i[y]===void 0?i[y]=h:i[y]=i[y].concat(h)}let u=Object.entries(i).sort(([h],[y])=>parseInt(h,10)-parseInt(y,10)).map(([h,y])=>y),{functions:l,function_call:c}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,c),m=await this._getNumTokensFromGenerations(u);return n.input_tokens=p,n.output_tokens=m,n.total_tokens=p+m,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:c,completion_tokens_details:p}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(n.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let m=[];for(let h of a?.choices??[]){let y={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},a)};y.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},yt(y.message)&&(y.message.usage_metadata=n),y.message=new $(Object.fromEntries(Object.entries(y.message).filter(([A])=>!A.startsWith("lc_")))),m.push(y)}return{generations:m,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let n=Wo({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:c}=l;if(!c)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(c,u,s);s=c.role??s;let m={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let h={...m};l.finish_reason!=null&&(h.finish_reason=l.finish_reason,h.system_fingerprint=u.system_fingerprint,h.model_name=u.model,h.service_tier=u.service_tier),this.logprobs&&(h.logprobs=l.logprobs);let y=new fo({message:p,text:p.content,generationInfo:h});yield y,await r?.handleLLMNewToken(y.text??"",m,void 0,void 0,void 0,{chunk:y})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},c=new fo({message:new et({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield c,await r?.handleLLMNewToken(c.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:c})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Qe(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Li({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return zi({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var na="__openai_function_call_ids__";function Ud(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 qh(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 Di=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}},oa=t=>{if(t.error){let u=new Error(t.error.message);throw u.name=t.error.code,u}let e,r=[],n=[],o=[],s=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){let l={...u};return delete l.parsed_arguments,l}return u}),a={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:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let u of t.output)if(u.type==="message")e=u.id,r.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(i.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(Ud),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(i.refusal=l.refusal,[]):l));else if(u.type==="function_call"){let l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{n.push(cs(l,{returnId:!0}))}catch(c){let p;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(p=c.message),o.push(jr(l,p))}i[na]??={},u.id&&(i[na][u.call_id]=u.id)}else if(u.type==="reasoning"){i.reasoning=u;let l=u.summary?.map(c=>c.text).filter(Boolean).join("");l&&r.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){let l=qc(u);l?n.push(l):o.push(jr(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){let l=Uc(u);l?n.push(l):o.push(jr(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&r.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),i.tool_outputs??=[],i.tool_outputs.push(u)):(i.tool_outputs??=[],i.tool_outputs.push(u));return new $({id:e,content:r,tool_calls:n,invalid_tool_calls:o,usage_metadata:Di(t.usage),additional_kwargs:i,response_metadata:a})},Bd=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}},Fi=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[Ud(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){i=t.item.id;let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[na]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"){let u=oa(t.response);n=Di(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text&&(a.parsed??=JSON.parse(u.text));for(let[l,c]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=c)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((c,p)=>({...c,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta});else return t.type==="response.image_generation_call.partial_image",null;return new fo({text:e.map(u=>u.text).join(""),message:new et({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},Kd=t=>{let e=$.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ne(()=>{try{let g=mt(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=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 c=(g,b)=>{o||(o={type:"message",role:n,content:[],...b?{phase:b}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...g]:[...g]:o.content.push(...g)},p=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},m=g=>{let b=Ne(()=>{let k=g.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(g.fileId)return{type:"input_image",detail:b,file_id:g.fileId};if(g.url)return{type:"input_image",detail:b,image_url:g.url};if(g.data){let k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:b,image_url:`data:${g.mimeType??"image/png"};base64,${k}`}}},h=g=>{if(g.fileId){let b=Mi(g);return{type:"input_file",file_id:g.fileId,...b?{filename:b}:{}}}if(g.url){let b=Mi(g);return{...b?{filename:b}:{},type:"input_file",file_url:g.url}}if(g.data){let b=Qn(g),k=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,${k}`,filename:b}}},y=g=>{let b=Ne(()=>{if(Array.isArray(g.summary)){let Q=g.summary?.map(V=>V?.text).filter(V=>typeof V=="string")??[];if(Q.length>0)return Q}return g.reasoning?[g.reasoning]:[]}),k=b.length>0?b.map(Q=>({type:"summary_text",text:Q})):[{type:"summary_text",text:""}],z={type:"reasoning",id:g.id??"",summary:k};return g.reasoning&&(z.content=[{type:"reasoning_text",text:g.reasoning}]),z},A=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:p(g.args)}),C=g=>{let b=p(g.output),k=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:b,...k?{status:k}:{}}};for(let g of t.contentBlocks)if(g.type==="text"){let b=Ne(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});c([{type:"input_text",text:g.text}],b)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield y(g);else if(g.type==="tool_call"){yield*l();let b=g.id??"";b&&(s.add(b),i.delete(b)),yield A(g)}else if(g.type==="tool_call_chunk"){if(g.id){let b=i.get(g.id)??{name:g.name,args:[]};g.name&&(b.name=g.name),g.args&&b.args.push(g.args),i.set(g.id,b)}}else if(g.type==="server_tool_call"){yield*l();let b=g.id??"";b&&(a.add(b),u.delete(b)),yield A(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let b=u.get(g.id)??{name:g.name,args:[]};g.name&&(b.name=g.name),g.args&&b.args.push(g.args),u.set(g.id,b)}}else if(g.type==="server_tool_call_result")yield*l(),yield C(g);else if(g.type!=="audio")if(g.type==="file"){let b=h(g);b&&c([b])}else if(g.type==="image"){let b=m(g);b&&c([b])}else if(g.type==="video"){let b=h(g);b&&c([b])}else g.type==="text-plain"?g.text&&c([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(let[g,b]of i){if(!g||s.has(g))continue;let k=b.args.join("");!b.name&&!k||(yield{type:"function_call",call_id:g,name:b.name??"",arguments:k})}for(let[g,b]of u){if(!g||a.has(g))continue;let k=b.args.join("");!b.name&&!k||(yield{type:"function_call",call_id:g,name:b.name??"",arguments:k})}}return Array.from(r())},sa=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Kd(n);let s=n.additional_kwargs,a=mt(n);if(a==="system"&&pt(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(m=>m.type==="input_image");if(l)return l;let c=i.content.find(m=>m.type==="computer_screenshot");if(c)return c;let p=i.content.find(m=>m.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(y=>"type"in y))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let y=Bd(u);i.push(y)}let{content:c}=n;if(s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),typeof c=="string"||c.length>0){let y={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ne(()=>typeof c=="string"?c:c.flatMap(A=>{if(A.type==="text"){let C=A;return{type:"output_text",text:C.text,annotations:(C.annotations??[]).map(qh)}}return A.type==="output_text"||A.type==="refusal"?A:[]})),phase:Ne(()=>{if(Array.isArray(c))return c.find(A=>"phase"in A&&typeof A.phase=="string")?.phase})};i.push(y)}let p=s?.[na];$.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(y=>Kc(y)?{type:"custom_tool_call",id:y.call_id,call_id:y.id??"",input:y.args.input,name:y.name}:Bc(y)?{type:"computer_call",id:y.call_id,call_id:y.id??"",action:y.args.action}:{type:"function_call",name:y.name,arguments:JSON.stringify(y.args),call_id:y.id,...e?{}:{id:p?.[y.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(y=>({type:"function_call",name:y.function.name,call_id:y.id,arguments:y.function.arguments,...e?{}:{id:p?.[y.id]}})));let m=o?.output?.length?o?.output:s.tool_outputs,h=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(m!=null){let y=m?.filter(A=>h.includes(A.type));y.length>0&&i.push(...y)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),ts(l)?rs(l,ta):l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ne(()=>{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:Ne(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]));return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});var aa=class extends kr{constructor(t,e){super(Xn(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:Fc(t?.tool_choice)?t?.tool_choice:(()=>{let o=Qs(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:sa({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:oa(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*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:sa({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let o of n){if(e.signal?.aborted)return;let s=Fi(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}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 Qe(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Yn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(vr(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(us(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Ys(n)&&r.push(Gc(n));return r}};var ia=class Gd extends kr{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=Xn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new aa(n),this.completions=n?.completions??new ra(n)}_useResponsesApi(e){let r=e?.tools?.some(Yn),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(Ys)||e?.tools?.some(vr);return this.useResponsesApi||r||n||o||Rc(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*_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 Gd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Wh=I.object({type:I.literal("screenshot")}),Vh=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),Hh=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),Jh=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),Zh=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),Qh=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),Yh=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),Xh=I.object({type:I.literal("type"),text:I.string()}),eg=I.object({type:I.literal("wait"),duration:I.number().optional()}),tg=I.union([Wh,Vh,Hh,Jh,Zh,Qh,Yh,Xh,eg]),fU=I.object({action:tg});var rg=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()}),wU=I.union([rg]);var AU=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 ng=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),og=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),sg=I.object({type:I.literal("delete_file"),path:I.string()}),SU=I.union([ng,og,sg]);var Hd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},ug={default:"text-embedding-ada-002"},qi=new Map,la=null,cg=()=>{let t=Vd.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},dg=async t=>{let e=cg();qi.size===0&&(la||(la=(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=>qi.set(o.name,o))}catch(n){throw la=null,n}})()),await la);let r=qi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},pg=async(t="default")=>await dg(Hd[t]);var to=(t,e)=>e,Jd=(t,e)=>({...t,...e}),Zd=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
95
95
 
96
96
  `);return o[o.length-1]?.trim()===r?t:`${t}
97
97
 
98
- ${r}`},zd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),kr=()=>({agentExecutionContext:$({reducer:jd,default:zd}),outputMessage:$({reducer:Ld,default:()=>""}),summary:$({reducer:Qn,default:()=>""}),status:$({reducer:Qn})}),ia=()=>({...kr(),sharedStatePatch:$({reducer:Qn})}),eg=$.Root({agentExecutionContext:$({default:zd,reducer:jd}),currentIntent:$({default:()=>"none",reducer:Qn}),lastExecutedAgent:$({default:()=>"",reducer:Qn}),requiresFollowUp:$({default:()=>!0,reducer:Qn}),stepCount:$({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:$({default:()=>"",reducer:Ld})}),re=async(t,e)=>{await Ea("trace_message",t,e)},Ae=async(t,e)=>{await Ea("graph_ux_suggestion",t,e)};var tg=(t,e)=>async(r,n)=>{let o=new Headers(n?.headers);o.delete("Authorization"),o.delete("api-key"),t&&t.length>0&&(o.set("X-Esri-Authorization",`Bearer ${t}`),o.set("X-Esri-Request-Source","MapsSDK"));let s=e&&n?.signal?AbortSignal.any([e,n.signal]):n?.signal??e;return await fetch(r,{...n,headers:o,signal:s})},ji=async(t={})=>{let{modelTier:e="default",temperature:r=0,abortSignal:n}=t,o=$d.getDefault(),s=await Jh.getCredential(`${o.url}/sharing`),a=Nd[e],i=await Xh(e);return new sa({modelName:a,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:i,fetch:tg(s.token,n)}})};var rg=x.object({id:x.string().min(1),name:x.string().min(1),description:x.string().min(1)});x.array(rg);var Dd="0.1",Zn=1536,Fd="openai",Ud=Zh.default,qd=`Name: {name}
98
+ ${r}`},Qd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Cr=()=>({agentExecutionContext:O({reducer:Jd,default:Qd}),outputMessage:O({reducer:Zd,default:()=>""}),summary:O({reducer:to,default:()=>""}),status:O({reducer:to})}),ua=()=>({...Cr(),sharedStatePatch:O({reducer:to})}),mg=O.Root({agentExecutionContext:O({default:Qd,reducer:Jd}),currentIntent:O({default:()=>"none",reducer:to}),lastExecutedAgent:O({default:()=>"",reducer:to}),requiresFollowUp:O({default:()=>!0,reducer:to}),stepCount:O({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:O({default:()=>"",reducer:Zd})});var fg=t=>typeof t=="string"&&t.length>0?t:void 0,hg=t=>t&&typeof t=="object"&&"aborted"in t?t:void 0,gg=t=>{let e=t?.configurable;return{conversationId:fg(e?.thread_id),abortSignal:hg(e?.abortSignal),requestId:lg.applicationName}},yg=async({config:t})=>{let e=Vd.getDefault(),r=(await ig.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i}=gg(t),u=new Headers(o?.headers);u.delete("Authorization"),u.delete("api-key"),r&&r.length>0&&(u.set("X-Esri-Authorization",`Bearer ${r}`),u.set("X-Esri-Request-Source","MapsSDK")),s&&s.length>0&&u.set("X-Esri-Conversation-Id",s),i&&i.length>0&&u.set("X-Esri-Request-Id",i);let l=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:u,signal:l})}},Ui=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=Hd[e],s=await pg(e);return new ia({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await yg({config:n})}})};var wg=I.object({id:I.string().min(1),name:I.string().min(1),description:I.string().min(1)});I.array(wg);var Yd="0.1",eo=1536,Xd="openai",ep=ug.default,tp=`Name: {name}
99
99
  Title: {title}
100
- Description: {description}`,Bd=`Name: {name}
100
+ Description: {description}`,rp=`Name: {name}
101
101
  Alias: {alias}
102
- Description: {description}`,Kd=x.object({schemaVersion:x.literal(Dd),modified:x.number().int().nonnegative(),embeddings:x.object({modelProvider:x.literal(Fd),model:x.literal(Ud),dimensions:x.literal(Zn),templates:x.object({layer:x.string().default(qd),field:x.string().default(Bd)})}),layers:x.array(x.object({id:x.string().min(1),name:x.string().min(1),title:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Zn,{message:`Layer vector must be exactly ${Zn} dimensions`}),fields:x.array(x.object({name:x.string().min(1),alias:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Zn,{message:`Field vector must be exactly ${Zn} dimensions`})}))})).default([])});var ng=(t,e)=>{let r=Ml.fromTemplate(t);return po.fromMessages([r,...e])};var Wo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,abortSignal:i}=t,u=ng(e,o??[]),l=(await ji({modelTier:r,temperature:n,abortSignal:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{})};var og=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),sq=d.object({fields:d.array(og)});var aq=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var Vd=t=>Array.isArray(t)&&t.every(io),ag=t=>typeof t=="object"&&t!=null&&"messages"in t&&Vd(t.messages),ig=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ht=class extends Pl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e){let r=this.tools.find(n=>n.name===t.name);try{if(r===void 0)throw new Error(`Tool "${t.name}" not found.`);let n=await r.invoke({...t,type:"tool_call"},e);return io(n)&&n.getType()==="tool"||ue(n)?n:new q({status:"success",name:r.name,content:typeof n=="string"?n:JSON.stringify(n),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||ao(n))throw n;return new q({status:"error",content:`Error: ${n.message}
103
- Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(ig(t))r=[await this.runTool(t.lg_tool_call,e)];else{let s;if(Vd(t))s=t;else if(ag(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(gt(l)){i=l;break}}if(i==null||!gt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===ne.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ll(a))?o?o.goto.push(...s.goto):o=new ne({graph:ne.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var aB=$.Root({llmInputMessages:$({reducer:(t,e)=>fo([],e),default:()=>[]})});var Vo=(t,e)=>e??t,qg=$.Root({...ia(),intent:$({reducer:Vo}),vectorSearchLayerResults:$({reducer:Vo,default:()=>[]}),vectorSearchFieldResults:$({reducer:Vo}),navigationInternalState:$({reducer:Vo,default:()=>({toolCallMessage:void 0})})});async function Bg(t,e){let r=Er.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Li.assetsPath?.endsWith("/")?Li.assetsPath:`${Li.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await cg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new dg({url:s,width:24,height:24}),u=new ug({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Kg=["mapView"];function Ye(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Kg.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Wg({address:t},e){let{mapView:r}=Ye(e);return await Bg(t,r)}var Vg=d.object({address:d.string().describe("The full address or place name to locate.")}),Gg=D(Wg,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Vg});async function Hg(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 Jg({bookmarkName:t},e){let{mapView:r}=Ye(e);return await Promise.resolve(Hg(t,r))}var Zg=x.object({bookmarkName:x.string().describe("The name of the bookmark to navigate to.")}),Qg=D(Jg,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Zg});async function Yg(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function Xg({layerId:t,where:e},r){let{mapView:n}=Ye(r);return await Yg(t,e,n)}var ey=x.object({layerId:x.string().describe("The layerId of the layer to zoom to."),where:x.string().describe("The sql-92 where clause used to query features to zoom to")}),ty=D(Xg,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:ey});async function ry(t){let e=new pg({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function ny(t,e){let{mapView:r}=Ye(e);return await ry(r)}var oy=x.object({}),sy=D(ny,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:oy});async function ay(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 iy(t,e){let{mapView:r}=Ye(e);return await ay(r)}var ly=d.object({}),uy=D(iy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:ly});async function cy(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 dy({layerId:t},e){let{mapView:r}=Ye(e);return await cy(t,r)}var py=x.object({layerId:x.string().describe("The id of the layer to navigate to")}),my=D(dy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:py});async function fy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function hy({scale:t},e){let{mapView:r}=Ye(e);return await fy(t,r)}var gy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),yy=D(hy,{name:"goToScale",description:"Go to the specified view scale.",schema:gy});async function _y(t,e,r){let n={target:new tp({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 wy({center:t,zoom:e,scale:r},n){let{mapView:o}=Ye(n);return await _y(t,o,{zoom:e,scale:r})}var by=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.")}),Ay=D(wy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:by});async function xy(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Iy({zoom:t},e){let{mapView:r}=Ye(e);return await xy(t,r)}var vy=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Ty=D(Iy,{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:vy}),Yd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./YL7PGYWC.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./ANPXRYLV.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./3PAHY5KA.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./GAHILDQF.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./SYJSVUUR.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./DKBTJJMW.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W6PSG4GX.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./3MQIRMUM.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./EVDOPN3G.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./GQFWFZXP.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./7WZHZP6U.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./F6V7MLPY.js").then(t=>t.default)});async function Wt(t){let e=Object.entries(Yd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
102
+ Description: {description}`,np=I.object({schemaVersion:I.literal(Yd),modified:I.number().int().nonnegative(),embeddings:I.object({modelProvider:I.literal(Xd),model:I.literal(ep),dimensions:I.literal(eo),templates:I.object({layer:I.string().default(tp),field:I.string().default(rp)})}),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(eo,{message:`Layer vector must be exactly ${eo} 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(eo,{message:`Field vector must be exactly ${eo} dimensions`})}))})).default([])});var _g=(t,e)=>{let r=Dl.fromTemplate(t);return zr.fromMessages([r,...e])};var Vo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=_g(e,o??[]),l=(await Ui({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{})};var bg=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),W1=d.object({fields:d.array(bg)});var V1=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var sp=t=>Array.isArray(t)&&t.every(po),Ag=t=>typeof t=="object"&&t!=null&&"messages"in t&&sp(t.messages),Ig=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ht=class extends Fl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e){let r=this.tools.find(n=>n.name===t.name);try{if(r===void 0)throw new Error(`Tool "${t.name}" not found.`);let n=await r.invoke({...t,type:"tool_call"},e);return po(n)&&n.getType()==="tool"||ce(n)?n:new B({status:"success",name:r.name,content:typeof n=="string"?n:JSON.stringify(n),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||co(n))throw n;return new B({status:"error",content:`Error: ${n.message}
103
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Ig(t))r=[await this.runTool(t.lg_tool_call,e)];else{let s;if(sp(t))s=t;else if(Ag(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(yt(l)){i=l;break}}if(i==null||!yt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e))??[])}if(!r.some(ce))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ce(s)?s.graph===re.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>gl(a))?o?o.goto.push(...s.goto):o=new re({graph:re.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var HB=O.Root({llmInputMessages:O({reducer:(t,e)=>yo([],e),default:()=>[]})});var Ho=(t,e)=>e??t,oy=O.Root({...ua(),intent:O({reducer:Ho}),vectorSearchLayerResults:O({reducer:Ho,default:()=>[]}),vectorSearchFieldResults:O({reducer:Ho}),navigationInternalState:O({reducer:Ho,default:()=>({toolCallMessage:void 0})})});async function sy(t,e){let r=Er.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Bi.assetsPath?.endsWith("/")?Bi.assetsPath:`${Bi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await Sg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new kg({url:s,width:24,height:24}),u=new Tg({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var ay=["mapView"];function Ye(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=ay.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}=Ye(e);return await sy(t,r)}var ly=d.object({address:d.string().describe("The full address or place name to locate.")}),uy=D(iy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:ly});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 dy({bookmarkName:t},e){let{mapView:r}=Ye(e);return await Promise.resolve(cy(t,r))}var py=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),my=D(dy,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:py});async function fy(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function hy({layerId:t,where:e},r){let{mapView:n}=Ye(r);return await fy(t,e,n)}var gy=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")}),yy=D(hy,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:gy});async function wy(t){let e=new Cg({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 _y(t,e){let{mapView:r}=Ye(e);return await wy(r)}var by=I.object({}),xy=D(_y,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:by});async function Ay(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 Iy(t,e){let{mapView:r}=Ye(e);return await Ay(r)}var vy=d.object({}),Ty=D(Iy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:vy});async function Sy(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}=Ye(e);return await Sy(t,r)}var Cy=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),Ey=D(ky,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Cy});async function My(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Oy({scale:t},e){let{mapView:r}=Ye(e);return await My(t,r)}var Py=d.object({scale:d.number().describe("The map scale of the view to go to.")}),Ry=D(Oy,{name:"goToScale",description:"Go to the specified view scale.",schema:Py});async function $y(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 Ny({center:t,zoom:e,scale:r},n){let{mapView:o}=Ye(n);return await $y(t,o,{zoom:e,scale:r})}var jy=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.")}),zy=D(Ny,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:jy});async function Ly(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Dy({zoom:t},e){let{mapView:r}=Ye(e);return await Ly(t,r)}var Fy=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),qy=D(Dy,{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:Fy}),dp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./YL7PGYWC.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./ANPXRYLV.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./3PAHY5KA.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./GAHILDQF.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./SYJSVUUR.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./DKBTJJMW.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W6PSG4GX.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./3MQIRMUM.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./EVDOPN3G.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./GQFWFZXP.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./7WZHZP6U.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./F6V7MLPY.js").then(t=>t.default)});async function Wt(t){let e=Object.entries(dp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
104
104
  Available prompts:
105
- ${Object.keys(Yd).join(`
106
- `)}`);return await e[1]()}var Xn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Sy(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=fg({basemapTheme:await Jd(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=hg({basemapTheme:await Jd(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function ky(t){return await mg(t)}async function Cy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await Sy(u),c=await ky(l);return i.renderer=c.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Ey=["mapView"];function Le(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Ey.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Oy({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await Cy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var My=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)")}),Py=D(Oy,{name:"chart",description:`Label: Charts
105
+ ${Object.keys(dp).join(`
106
+ `)}`);return await e[1]()}var oo=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Uy(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=Mg({basemapTheme:await lp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=Og({basemapTheme:await lp(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function By(t){return await Eg(t)}async function Ky({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await Uy(u),c=await By(l);return i.renderer=c.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Gy=["mapView"];function Le(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Gy.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Wy({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Ky({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Vy=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)")}),Hy=D(Wy,{name:"chart",description:`Label: Charts
107
107
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
108
108
  Keywords: pie, chart, all categories, breakdown, proportion
109
109
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -113,19 +113,19 @@ ${Object.keys(Yd).join(`
113
113
  Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
114
114
  Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
115
115
  Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
116
- Fields: This style requires 2-8 number fields.`,schema:My});function Ry(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Ki({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function $y(t){return await gg(t)}async function Ny({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Ry(u),c=await $y(l);return i.renderer=c.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function jy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await Ny({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Ly=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")}),zy=D(jy,{name:"color-age",description:`Label: Age (color)
116
+ Fields: This style requires 2-8 number fields.`,schema:Vy});function Jy(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Xi({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function Zy(t){return await Pg(t)}async function Qy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Jy(u),c=await Zy(l);return i.renderer=c.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Yy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Qy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Xy=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")}),ew=D(Yy,{name:"color-age",description:`Label: Age (color)
117
117
  Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
118
118
  Keywords: since, age, how old, how long
119
119
  Example: Show the age of each feature based on its reported date.
120
- Fields: This style requires at least one field with a date type.`,schema:Ly});function Dy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=Ki({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function Fy(t){return await yg(t)}async function Uy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Dy(u),c=await Fy(l);return i.renderer=c.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function qy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await Uy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var By=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")}),Ky=D(qy,{name:"color",description:`Label: Counts and Amounts (color)
120
+ Fields: This style requires at least one field with a date type.`,schema:Xy});function tw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=Xi({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function rw(t){return await Rg(t)}async function nw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=tw(u),c=await rw(l);return i.renderer=c.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function ow({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await nw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var sw=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")}),aw=D(ow,{name:"color",description:`Label: Counts and Amounts (color)
121
121
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
122
122
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
123
123
  Example: Color each feature based on the population density.
124
- Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:By});function Wy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=Ki({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function Vy(t){return await _g(t)}async function Gy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Wy(u),c=await Vy(l);return i.renderer=c.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function Hy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await Gy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Jy=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")}),Zy=D(Hy,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
124
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:sw});function iw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=Xi({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function lw(t){return await $g(t)}async function uw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=iw(u),c=await lw(l);return i.renderer=c.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function cw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await uw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var dw=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")}),pw=D(cw,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
125
125
  Description: Vary symbol size and color based on the values of two numeric attributes.
126
126
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
127
127
  Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
128
- Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:Jy});function Qy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=bg({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function Yy(t){return await wg(t)}async function Xy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=Qy(i),l=await Yy(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function e_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await Ae({type:"show-legend",data:{layerIds:[t]}},n),await Xy({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var t_=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")}),r_=D(e_,{name:"dot-density",description:`Dot Density
128
+ Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:dw});function mw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=jg({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function fw(t){return await Ng(t)}async function hw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=mw(i),l=await fw(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function gw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await hw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var yw=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")}),ww=D(gw,{name:"dot-density",description:`Dot Density
129
129
  Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
130
130
  **Use cases:**
131
131
  - Population distribution visualization
@@ -136,11 +136,11 @@ ${Object.keys(Yd).join(`
136
136
  - Visualize distribution of different crops across regions
137
137
  - Display demographic patterns within census tracts
138
138
  **Fields:** Requires 2-8 number fields.
139
- **Keywords:** density, how much, how many, total, number, amount`,schema:t_});function n_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=xg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function o_(t){return await Ag(t)}async function s_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=n_(i),l=await o_(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function a_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await Ae({type:"show-legend",data:{layerIds:[t]}},n),await s_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var i_=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")}),l_=D(a_,{name:"heatmap",description:`Label: Heat Map
139
+ **Keywords:** density, how much, how many, total, number, amount`,schema:yw});function _w(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=Lg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function bw(t){return await zg(t)}async function xw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=_w(i),l=await bw(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function Aw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await xw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Iw=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")}),vw=D(Aw,{name:"heatmap",description:`Label: Heat Map
140
140
  Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
141
141
  Keywords: density, heatmap, hot spots, pattern, cluster
142
142
  Example: Create a heatmap
143
- Fields: This typically requires zero or one field of type number.`,schema:i_});function u_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=vg({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function c_(t){return await Ig(t)}async function d_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=u_(u),c=await c_(l);return i.renderer=c.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function p_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await d_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var m_=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)")}),f_=D(p_,{name:"predominance",description:`Label: Predominant category
143
+ Fields: This typically requires zero or one field of type number.`,schema:Iw});function Tw(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Fg({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function Sw(t){return await Dg(t)}async function kw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=Tw(u),c=await Sw(l);return i.renderer=c.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function Cw({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await kw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Ew=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)")}),Mw=D(Cw,{name:"predominance",description:`Label: Predominant category
144
144
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
145
145
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
146
146
  Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
@@ -150,15 +150,15 @@ Fields: This typically requires zero or one field of type number.`,schema:i_});f
150
150
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
151
151
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
152
152
  Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
153
- Fields: This style relies on 2-10 number fields.`,schema:m_});function h_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=Sg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function g_(t){return await Tg(t)}async function y_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=h_(i),l=await g_(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function __({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await Ae({type:"show-legend",data:{layerIds:[t]}},n),await y_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var w_=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")}),b_=D(__,{name:"relationship",description:`Label: Relationship
153
+ Fields: This style relies on 2-10 number fields.`,schema:Ew});function Ow(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=Ug({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function Pw(t){return await qg(t)}async function Rw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=Ow(i),l=await Pw(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function $w({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await Rw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Nw=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")}),jw=D($w,{name:"relationship",description:`Label: Relationship
154
154
  Description: Overlays two color ramps to represent the relationship between two numeric attributes.
155
155
  Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
156
156
  Example: Show the relationship between tree height and carbon storage
157
- Fields: This style requires two number fields.`,schema:w_});function A_(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 x_(t){return await kg(t)}async function I_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=A_(u),c=await x_(l);return i.renderer=c.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function v_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await I_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var T_=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")}),S_=D(v_,{name:"size-age",description:`Label: Age (size)
157
+ Fields: This style requires two number fields.`,schema:Nw});function zw(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Lw(t){return await Bg(t)}async function Dw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=zw(u),c=await Lw(l);return i.renderer=c.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Fw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Dw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var qw=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")}),Uw=D(Fw,{name:"size-age",description:`Label: Age (size)
158
158
  Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
159
159
  Keywords: since, age, how old, how long
160
160
  Example: Change the size of features so older features are larger than new features.
161
- Fields: This style requires at least one field with a date type.`,schema:T_});function k_(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function C_(t){return await Cg(t)}async function E_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=k_(u),c=await C_(l);return i.renderer=c.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function O_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await E_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var M_=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")}),P_=D(O_,{name:"size",description:`Label: Counts and Amounts (size)
161
+ Fields: This style requires at least one field with a date type.`,schema:qw});function Bw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Kw(t){return await Kg(t)}async function Gw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Bw(u),c=await Kw(l);return i.renderer=c.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function Ww({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Gw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Vw=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")}),Hw=D(Ww,{name:"size",description:`Label: Counts and Amounts (size)
162
162
  Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
163
163
  Keywords: graduated size, proportional size, how much, total, number, amount, size
164
164
  Example: Vary the size of each point based on the total population.
@@ -168,11 +168,11 @@ Fields: This typically requires zero or one field of type number.`,schema:i_});f
168
168
  Description: Vary symbol sizes along a continuous ramp to represent dates.
169
169
  Keywords: graduated size, proportional size, classed size, how much, total, number, when
170
170
  Example: Vary the size of each feature based on the date a ticket was completed.
171
- Fields: This style requires a single field with a date type.`,schema:M_});function R_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Og({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function $_(t){return await Eg(t)}async function N_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=R_(u),c=await $_(l);return i.renderer=c.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function j_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await N_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var L_=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")}),z_=D(j_,{name:"type",description:`Label: Types (unique symbols)
171
+ Fields: This style requires a single field with a date type.`,schema:Vw});function Jw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Wg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function Zw(t){return await Gg(t)}async function Qw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Jw(u),c=await Zw(l);return i.renderer=c.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function Yw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Qw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Xw=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")}),e_=D(Yw,{name:"type",description:`Label: Types (unique symbols)
172
172
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
173
173
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
174
174
  Example: Color each feature based on the region it belongs to
175
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:L_}),D_=$.Root({...kr(),vectorSearchLayerIds:$(),vectorSearchFieldResults:$(),layerFieldInfo:$(),selectedLayerId:$()}),F_=$.Root({...kr(),vectorSearchLayerIds:$(),vectorSearchFieldResults:$(),layerFieldInfo:$(),queryResponse:$(),dataExplorationMessages:$({reducer:fo,default:()=>[]})}),U_=["mapView"];function Vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=U_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var q_=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."},B_=async(t,e)=>{let{mapView:r}=Vt(e);return q_(r)},fK=D(B_,{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({})}),K_=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."},W_=async(t,e)=>{let{mapView:r}=Vt(e);return await K_(r)},hK=D(W_,{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({})}),Xd=5;function da(t){return"point"in t&&t.point!==void 0}function Go(t){return"layerId"in t&&t.layerId!==void 0}var fa=async(t,e)=>{if(da(t)){let{point:r}=t;return{geometry:new tp({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Go(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Xd+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Xd)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:np.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},V_=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},G_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await fa(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Mg({filter:new rp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await V_(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},H_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Gt=d.enum(H_),J_=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Vt(s);return await G_(t,a,n,o,e,r)},Z_=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:Gt.optional().describe("The units for the distance buffer.")}),Q_=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:Gt.optional().describe("The units for the distance buffer.")}),Y_=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([Z_,Q_]).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.")}),gK=D(J_,{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:Y_}),Di=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},X_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,ew=t=>{if(typeof t=="string"&&t)return t;let e=Di(t);return e?e.toISOString().slice(0,10):null};var tw=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=ew(t);return s?Pg(s,la("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Rg(t,la("long-time"));let s=Di(t);return s?Zd(s,{...la("long-time"),timeZone:"UTC"}):t}let o=Di(t);return o?Zd(o,{...la("short-date-short-time"),timeZone:X_(r)}):t},sp=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},rw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,nw=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},ow=(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}},sw=(t,e,r)=>{let n=nw(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=rw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},ap=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,ip=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?ow(r,s):s?.type==="date-time"?sw(r,s,o):tw(r,n,o)},aw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=sp(e,r,t)??r;return ip(t,e,s,o?.type,n)},iw=(t,e)=>ap(t,e),lp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=sp(l.name,c,t)??c,m=ap(t,l.name);u[m]=ip(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},lw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},uw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=lw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=aw(o,e,i,n.timeZone),l=iw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function cw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Vt(n),s=await uw(t,e,r,o);return JSON.stringify(s,null,2)}var dw=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.")})}),pw=D(cw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:dw}),Wi=(t,e,r)=>r?t.hasAllFeaturesInView&&t.availableFields===e:t.hasAllFeatures&&t.availableFields===e;function pa(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var mw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(g=>g.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,m;if(a){let g=await fa(a,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Go(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Go(a)){let A=o.map?.allLayers.find(k=>k.id===a.layerId);p={geometryLayerName:A?.title??A?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else da(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});m=new rp({geometry:g.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let h=Wi(u,[r],!1),_=null,I=null,C=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:pa(i.definitionExpression,e.where),...m&&{filter:m},outStatisticTypes:{include:[n]}};_=await $g(g);let A=["string","small-integer","integer"],k=l.domain?.type==="coded-value"?l.domain:null;(A.includes(l.type)||k)&&(I=(await Ng({layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:pa(i.definitionExpression,e.where),...m&&{filter:m}})).uniqueValueInfos.sort((L,Q)=>Q.count-L.count).slice(0,C)),I&&l.domain?.type==="coded-value"&&(I=I.map(L=>({...L,value:k?k.getName(L.value)??L.value:L.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof _?.[n]=="number"?_[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:_?.[n]??null,summaryStatistics:_,uniqueValues:I,where:e.where,spatialFilterInfo:p}}};async function fw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Xn(o,"layersAndFieldsRegistry"),{mapView:a}=Vt(o),i=await mw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var hw=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:Gt.optional().describe("The units for the distance buffer.")}),gw=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:Gt.optional().describe("The units for the distance buffer.")}),yw=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([hw,gw]).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.")}),_w=D(fw,{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.
175
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:Xw}),t_=O.Root({...Cr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),selectedLayerId:O()}),r_=O.Root({...Cr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),queryResponse:O(),dataExplorationMessages:O({reducer:yo,default:()=>[]})}),n_=["mapView"];function Vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=n_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var o_=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."},s_=async(t,e)=>{let{mapView:r}=Vt(e);return o_(r)},nG=D(s_,{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({})}),a_=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."},i_=async(t,e)=>{let{mapView:r}=Vt(e);return await a_(r)},oG=D(i_,{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 fa(t){return"point"in t&&t.point!==void 0}function Jo(t){return"layerId"in t&&t.layerId!==void 0}var ya=async(t,e)=>{if(fa(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(Jo(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 a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:gp.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},l_=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},u_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await ya(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Vg({filter:new hp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await l_(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},c_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Ht=d.enum(c_),d_=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Vt(s);return await u_(t,a,n,o,e,r)},p_=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:Ht.optional().describe("The units for the distance buffer.")}),m_=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:Ht.optional().describe("The units for the distance buffer.")}),f_=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([p_,m_]).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.")}),sG=D(d_,{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:f_}),Gi=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},h_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,g_=t=>{if(typeof t=="string"&&t)return t;let e=Gi(t);return e?e.toISOString().slice(0,10):null};var y_=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=g_(t);return s?Hg(s,ca("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Jg(t,ca("long-time"));let s=Gi(t);return s?up(s,{...ca("long-time"),timeZone:"UTC"}):t}let o=Gi(t);return o?up(o,{...ca("short-date-short-time"),timeZone:h_(r)}):t},wp=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},w_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,__=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},b_=(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}},x_=(t,e,r)=>{let n=__(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=w_(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},_p=(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"?b_(r,s):s?.type==="date-time"?x_(r,s,o):y_(r,n,o)},A_=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=wp(e,r,t)??r;return bp(t,e,s,o?.type,n)},I_=(t,e)=>_p(t,e),xp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=wp(l.name,c,t)??c,m=_p(t,l.name);u[m]=bp(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},v_=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},T_=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=v_(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=A_(o,e,i,n.timeZone),l=I_(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function S_({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Vt(n),s=await T_(t,e,r,o);return JSON.stringify(s,null,2)}var k_=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.")})}),C_=D(S_,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:k_}),el=(t,e,r)=>r?t.hasAllFeaturesInView&&t.availableFields===e:t.hasAllFeatures&&t.availableFields===e;function ha(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var E_=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(g=>g.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,m;if(a){let g=await ya(a,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Jo(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Jo(a)){let b=o.map?.allLayers.find(k=>k.id===a.layerId);p={geometryLayerName:b?.title??b?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else fa(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});m=new hp({geometry:g.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let h=el(u,[r],!1),y=null,A=null,C=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:ha(i.definitionExpression,e.where),...m&&{filter:m},outStatisticTypes:{include:[n]}};y=await Zg(g);let b=["string","small-integer","integer"],k=l.domain?.type==="coded-value"?l.domain:null;(b.includes(l.type)||k)&&(A=(await Qg({layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:ha(i.definitionExpression,e.where),...m&&{filter:m}})).uniqueValueInfos.sort((z,Q)=>Q.count-z.count).slice(0,C)),A&&l.domain?.type==="coded-value"&&(A=A.map(z=>({...z,value:k?k.getName(z.value)??z.value:z.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof y?.[n]=="number"?y[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:y?.[n]??null,summaryStatistics:y,uniqueValues:A,where:e.where,spatialFilterInfo:p}}};async function M_({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=oo(o,"layersAndFieldsRegistry"),{mapView:a}=Vt(o),i=await E_({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var O_=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:Ht.optional().describe("The units for the distance buffer.")}),P_=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:Ht.optional().describe("The units for the distance buffer.")}),R_=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([O_,P_]).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.")}),$_=D(M_,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
176
176
 
177
177
  USE THIS TOOL FOR:
178
178
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -184,7 +184,7 @@ DO NOT USE FOR:
184
184
  - "Show / list / find features" \u2014 use queryFeatures instead
185
185
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
186
186
 
187
- Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:yw}),ww=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(m=>m.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let m=await fa(n,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=m.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let m;if(l){let I=new jg({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Lg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});m=await s.queryTopFeatures(I)}else{let I=s.createQuery();I.where=pa(s.definitionExpression,t.where||"1=1"),I.outFields=p.length?p:["*"],I.orderByFields=e.orderByFields,I.num=e.topCount,u&&(I.geometry=u,I.spatialRelationship="intersects"),n?.distance&&(I.distance=n.distance),n?.units&&(I.units=n.units),I.outSpatialReference=r.spatialReference;let C=Wi(a,t.outFields,o??!1);try{m=C?await a.queryFeatures(I):await s.queryFeatures(I)}catch(g){console.warn("Client-side query failed, falling back to server:",g),m=await s.queryFeatures(I)}}let h=m.features.map(I=>I.attributes[c]),{attributes:_}=lp(s,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:_,objectIds:h,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},bw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Vt(o),a=await ww(t,e,s,r,n);return JSON.stringify(a,null,2)},Aw=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:Gt.optional().describe("The units for the distance buffer.")}),xw=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:Gt.optional().describe("The units for the distance buffer.")}),Iw=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([Aw,xw]).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).")}),vw=D(bw,{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:Iw}),zi=25,Tw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(I=>I.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let I=await fa(r,e);if("error"in I){let C={error:I.error};if(Go(r)){let g=e.map?.allLayers.find(A=>A.id===r.layerId);C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else da(r)&&(C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:C}}if(!I.geometry){let C={};if(Go(r)){let g=e.map?.allLayers.find(A=>A.id===r.layerId);C.error=`No features found matching: ${r.where}`,C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else da(r)&&(C.error="Failed to create point geometry",C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:C}}i=I.geometry}else n&&(i=e.extent.clone());let u=Wi(s,t.outFields,n??!1),l=o.objectIdField,c=o.createQuery();c.where=pa(o.definitionExpression,t.where||"1=1"),c.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,l])],c.orderByFields=t.orderByFields,i&&(c.geometry=i,c.spatialRelationship="intersects"),r?.distance&&(c.distance=r.distance),r?.units&&(c.units=r.units),c.outSpatialReference=e.spatialReference;let p,m;try{p=u?await s.queryFeatureCount(c):await o.queryFeatureCount(c),p>0&&p<=zi&&(m=u?await s.queryFeatures(c):await o.queryFeatures(c))}catch(I){console.warn("Client-side query failed, falling back to server:",I),p=await o.queryFeatureCount(c),p>0&&p<=zi&&(m=await o.queryFeatures(c))}let{objectIds:h,attributes:_}=m?lp(o,m,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${p} features found`,details:{totalCount:p,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...h&&{objectIds:h,objectIdField:l},..._&&{attributes:_},...p>zi&&{note:`${p} features found.`}}}};async function Sw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Vt(n),s=await Tw(t,o,e,r);return JSON.stringify(s,null,2)}var 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:Gt.optional().describe("The units for the distance buffer.")}),Cw=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:Gt.optional().describe("The units for the distance buffer.")}),Ew=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([kw,Cw]).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).")}),Ow=D(Sw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
187
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:R_}),N_=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(m=>m.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let m=await ya(n,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=m.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let m;if(l){let A=new Yg({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Xg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});m=await s.queryTopFeatures(A)}else{let A=s.createQuery();A.where=ha(s.definitionExpression,t.where||"1=1"),A.outFields=p.length?p:["*"],A.orderByFields=e.orderByFields,A.num=e.topCount,u&&(A.geometry=u,A.spatialRelationship="intersects"),n?.distance&&(A.distance=n.distance),n?.units&&(A.units=n.units),A.outSpatialReference=r.spatialReference;let C=el(a,t.outFields,o??!1);try{m=C?await a.queryFeatures(A):await s.queryFeatures(A)}catch(g){console.warn("Client-side query failed, falling back to server:",g),m=await s.queryFeatures(A)}}let h=m.features.map(A=>A.attributes[c]),{attributes:y}=xp(s,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:y,objectIds:h,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},j_=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Vt(o),a=await N_(t,e,s,r,n);return JSON.stringify(a,null,2)},z_=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:Ht.optional().describe("The units for the distance buffer.")}),L_=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:Ht.optional().describe("The units for the distance buffer.")}),D_=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([z_,L_]).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).")}),F_=D(j_,{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:D_}),Ki=25,q_=async(t,e,r,n)=>{let o=e.map?.allLayers.find(A=>A.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let A=await ya(r,e);if("error"in A){let C={error:A.error};if(Jo(r)){let g=e.map?.allLayers.find(b=>b.id===r.layerId);C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else fa(r)&&(C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:C}}if(!A.geometry){let C={};if(Jo(r)){let g=e.map?.allLayers.find(b=>b.id===r.layerId);C.error=`No features found matching: ${r.where}`,C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else fa(r)&&(C.error="Failed to create point geometry",C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:C}}i=A.geometry}else n&&(i=e.extent.clone());let u=el(s,t.outFields,n??!1),l=o.objectIdField,c=o.createQuery();c.where=ha(o.definitionExpression,t.where||"1=1"),c.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,l])],c.orderByFields=t.orderByFields,i&&(c.geometry=i,c.spatialRelationship="intersects"),r?.distance&&(c.distance=r.distance),r?.units&&(c.units=r.units),c.outSpatialReference=e.spatialReference;let p,m;try{p=u?await s.queryFeatureCount(c):await o.queryFeatureCount(c),p>0&&p<=Ki&&(m=u?await s.queryFeatures(c):await o.queryFeatures(c))}catch(A){console.warn("Client-side query failed, falling back to server:",A),p=await o.queryFeatureCount(c),p>0&&p<=Ki&&(m=await o.queryFeatures(c))}let{objectIds:h,attributes:y}=m?xp(o,m,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${p} features found`,details:{totalCount:p,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...h&&{objectIds:h,objectIdField:l},...y&&{attributes:y},...p>Ki&&{note:`${p} features found.`}}}};async function U_({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Vt(n),s=await q_(t,o,e,r);return JSON.stringify(s,null,2)}var B_=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:Ht.optional().describe("The units for the distance buffer.")}),K_=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:Ht.optional().describe("The units for the distance buffer.")}),G_=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([B_,K_]).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).")}),W_=D(U_,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
188
188
 
189
189
  USE THIS TOOL FOR:
190
190
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -193,64 +193,60 @@ USE THIS TOOL FOR:
193
193
  - Spatial queries \u2014 finding features near/within/intersecting other features
194
194
  - Any question where the user wants to SEE or COUNT matching features
195
195
 
196
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Ew}),up=[pw,_w,vw,Ow];var yK=new ht(up,{handleToolErrors:!1});var Mw=$.Root({...kr(),helpInternalState:$({reducer:Vo,default:()=>({toolCallMessage:void 0})})}),Pw=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
196
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:G_}),Ap=[C_,$_,F_,W_];var aG=new ht(Ap,{handleToolErrors:!1});var V_=O.Root({...Cr(),helpInternalState:O({reducer:Ho,default:()=>({toolCallMessage:void 0})})}),H_=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
197
197
  `);return`**${r.layerItem.title}** has ${n.length} field(s):
198
198
 
199
- ${o}`},Rw=async({layerTitle:t},e)=>{let r=Xn(e,"layersAndFieldsRegistry");return Pw(r,t)},$w=D(Rw,{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.")})}),Nw=$.Root({...kr(),intent:$({reducer:(t,e)=>e}),arcgisKnowledgeMessages:$({reducer:fo,default:()=>[]}),arcgisKnowledgeToolResult:$({reducer:(t,e)=>e,default:()=>null})}),ua={conversationId:""};function cp(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 eo(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function ha(t){!t||eo(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function ga(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)&&cp(r),{view:r}}async function to(t){let e=t?.configurable?.context;if(jw(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 Qd(n)}}else{cp(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 Qd(n)}}}}function jw(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 Fi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ma.fromDataModel(e)}},ma=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(Ho.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Ui.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Lw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
200
- Relationship Types: ${n}.`}},Ho=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=zw(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Dw(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}},Ui=class extends Ho{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Ho.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},Lw=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},zw=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Dw(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 Fw(t,e){return e?`${t}
199
+ ${o}`},J_=async({layerTitle:t},e)=>{let r=oo(e,"layersAndFieldsRegistry");return H_(r,t)},Z_=D(J_,{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.")})}),Q_=O.Root({...Cr(),intent:O({reducer:(t,e)=>e}),arcgisKnowledgeMessages:O({reducer:yo,default:()=>[]}),arcgisKnowledgeToolResult:O({reducer:(t,e)=>e,default:()=>null})}),da={conversationId:""};function Ip(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 Mr(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function wa(t){!t||Mr(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function _a(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)&&Ip(r),{view:r}}async function so(t){let e=t?.configurable?.context;if(Y_(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 cp(n)}}else{Ip(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 cp(n)}}}}function Y_(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 Wi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ga.fromDataModel(e)}},ga=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(Zo.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Vi.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:X_(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
200
+ Relationship Types: ${n}.`}},Zo=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=eb(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:tb(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}},Vi=class extends Zo{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Zo.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},X_=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},eb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function tb(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 ba(t){return t?.configurable?.abortSignal}function rb(t,e){return e?`${t}
201
201
 
202
202
  Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
203
203
 
204
204
  Attempt Number: ${e.attemptCount}
205
205
  Execution Error: ${e.executionError}
206
206
  Failed Query:
207
- ${e.failedGraphQuery}`:t}async function Uw(t,e,r,n){let{graphQuery:o,explanation:s}=await Vi(t,e,r,n);return`Generated Graph Query:
208
- ${o}
209
-
210
- Explanation: ${s}`}async function Vi(t,e,r,n,o){let s={message:Fw(t,o),context:new Fi(e)};ua.conversationId&&(s.conversationId=ua.conversationId),await re({text:"Attempting to generate a cypher query from your prompt..."},n);let a=await Hd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:Gd.findCredential(Er.getDefault().url)?.token??""}});if(a.httpStatus!==200)throw new Error(`Graph query service returned an error: ${a.httpStatus}`,{cause:a.data});ua.conversationId||(ua.conversationId=a.data.conversationId);let i=!1,u=Date.now(),l=a.data.sequenceNumber,c="",p="",m=1;for(;!i;){await new Promise(_=>setTimeout(_,1e3)),await re({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,m)}`},n),m=m%3+1;let h=await Hd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:a.data.conversationId,inquiryId:a.data.inquiryId,ackSequenceNumber:l}),headers:{"Content-Type":"application/json",token:Gd.findCredential(Er.getDefault().url)?.token??""}});if(h.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${h.httpStatus}`,{cause:h.data});if(h.data.context)c=h.data.context.graphQuery,p=h.data.message||"";else if(!h.data.hasMore)i=!0;else if(Date.now()-u>6e4)throw new Error("Graph query service polling timed out after 1 minute.");l=h.data.sequenceNumber}return{graphQuery:c,explanation:p}}var Cr=3;function dp(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 Gi(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 qw=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,c=o?.signal,p=()=>{l.abort(c?.reason)};c&&(c.aborted?l.abort(c.reason):c.addEventListener("abort",p,{once:!0}));try{let m=await Dg(t,e,o);i=m.resultHeader;let h=m.resultRowsStream.getReader(),_=0,I=Date.now(),C=!1;for(;;){let{done:g,value:A}=await h.read();if(g)break;if(!C&&a&&Date.now()-I>a)return l.abort(),{type:"timeout"};for(let k of A){if(_++,s&&_>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,k)}}}catch(m){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Gi(m),error:m}}finally{c?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function pp({prompt:t,kg:e,graphQueryServiceUrl:r,targetStructure:n,targetStructureReducer:o,requestOptions:s,queryRowLimit:a,queryTimeoutMs:i,config:u}){let l;for(let c=1;c<=Cr;c++){let p;try{p=await Vi(t,e.dataModel,r,u,l)}catch(_){return{type:"generation-error",errorMessage:Gi(_),error:_}}await re({text:`Attempting to execute query: ${p.graphQuery.substring(0,500)}${p.graphQuery.length>500?"...":""}`},u);let m=await qw({kg:e,queryParams:new op({openCypherQuery:p.graphQuery}),targetStructure:n,targetStructureReducer:o,requestOptions:s,queryRowLimit:a,queryTimeoutMs:i}),h=m.type==="aborted"?"Query execution was aborted.":m.type==="timeout"?"Query execution timed out.":m.type==="error"?`Query failed with error: ${m.errorMessage}`:"";if(m.type==="success")return{type:"success",graphQuery:p.graphQuery,explanation:p.explanation,rowLimitReached:m.rowLimitReached,resultHeader:m.resultHeader,processedResult:m.processedResult};if(m.type==="aborted")return{type:"aborted",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation};if(c>=Cr)return m.type==="timeout"?{type:"timeout",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation}:{type:"execution-error",errorMessage:h,error:m.error,graphQuery:p.graphQuery,explanation:p.explanation};l={failedGraphQuery:p.graphQuery,executionError:h,attemptCount:c},await re({text:`Attempt ${c} failed with error: ${h}. Retrying...`},u)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Cr} attempts.`)}var Bw=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let c=u-a.length;if(c<=0)break;let p=(await Fg(t,new Ug({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:c}),s)).resultRowsStream.getReader(),m=!1;for(;!m;){let{done:h,value:_}=await p.read();if(h){m=!0;break}for(let I of _)for(let C of I)a.push(C)}}}catch(l){return console.log('Error when running graph search with query: "',e,'" - error: ',l),s?.signal?.aborted?{type:"aborted"}:{type:"error",errorMessage:Gi(l),error:l}}return{type:"success",results:a}};function Kw(t,e){Yn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Yn(t,e){if(!(!t||typeof t!="object")){if(Vw(t))for(let r of t.path)Yn(r,e);else if(Ww(t))e(t);else if(Array.isArray(t))for(let r of t)Yn(r,e);else if(Gw(t))for(let r of Object.values(t.properties??{}))Yn(r,e)}}function Ww(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Vw(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Gw(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Hw(t,e){let r=[];for(let n of[...e.dataModel.entityTypes,...e.dataModel.relationshipTypes]){let o=t.getMemberIdsByType(n.name);for(let s of o)r.push({id:s,typeName:n.name})}return r}function Jw(t){let e=[],r=[],n=t?.allLayers.find(o=>o.type==="knowledge-graph")?.inclusionModeDefinition;if(n?.generateAllSublayers)return{allNamedTypesFullyDynamic:!0,idTypePairs:e,dynamicTypes:r};for(let[o,s]of n?.namedTypeDefinitions??[])if(s.useAllData)r.push(o);else for(let[a]of s.members)e.push({id:a,typeName:o});return{allNamedTypesFullyDynamic:!1,idTypePairs:e,dynamicTypes:r}}async function Zw(t,e,r,n,o){let{view:s}=n,a=await pp({prompt:t,kg:e,graphQueryServiceUrl:r,targetStructure:new Map,targetStructureReducer:(p,m)=>{for(let h of m)Kw(h,p);return p},requestOptions:{signal:o?.signal,timeout:o?.timeout},config:o});if(a.type!=="success"){let p=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${p}`)}let{graphQuery:i,explanation:u,processedResult:l}=a,c=Array.from(l.values());return await re({text:`Query Results parsed into ${c.length} unique relationships and entities. Atempting to add to link chart...`},o),!eo(s)&&s?.map?(await s.map.addRecords(c),await ha(s),`Link Chart updated successfully. Cypher Query used:
211
- ${i}
207
+ ${e.failedGraphQuery}`:t}async function nb(t,e,r,n){let{graphQuery:o,explanation:s}=await tl(t,e,r,n);return{graphQuery:o,explanation:s}}async function tl(t,e,r,n,o){let s={message:rb(t,o),context:new Wi(e)};da.conversationId&&(s.conversationId=da.conversationId);let a=ba(n);await ee({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await ip(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:ap.findCredential(Er.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});da.conversationId||(da.conversationId=i.data.conversationId);let u=!1,l=Date.now(),c=i.data.sequenceNumber,p="",m="",h=1;for(;!u;){await new Promise(A=>setTimeout(A,1e3)),await ee({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,h)}`},n),h=h%3+1;let y=await ip(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:ap.findCredential(Er.getDefault().url)?.token??""},signal:a});if(y.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${y.httpStatus}`,{cause:y.data});if(y.data.context?.kind){if(y.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${y.data.message}`,{cause:y.data});p=y.data.context.graphQuery,m=y.data.message||"",u=!0}else if(!y.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=y.data.sequenceNumber}return{graphQuery:p,explanation:m}}var ro=3;function vp(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function ao(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var ob=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,c=o?.signal,p=()=>{l.abort(c?.reason)};c&&(c.aborted?l.abort(c.reason):c.addEventListener("abort",p,{once:!0}));try{let m=await ty(t,e,o);i=m.resultHeader;let h=m.resultRowsStream.getReader(),y=0,A=Date.now(),C=!1;for(;;){let{done:g,value:b}=await h.read();if(g)break;if(!C&&a&&Date.now()-A>a)return l.abort(),{type:"timeout"};for(let k of b){if(y++,s&&y>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,k)}}}catch(m){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:ao(m),error:m}}finally{c?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function Tp({prompt:t,kg:e,graphQueryServiceUrl:r,targetStructure:n,targetStructureReducer:o,requestOptions:s,queryRowLimit:a,queryTimeoutMs:i,config:u}){let l;for(let c=1;c<=ro;c++){let p;try{p=await tl(t,e.dataModel,r,u,l)}catch(y){return{type:"generation-error",errorMessage:ao(y),error:y}}await ee({text:`Attempting to execute query: ${p.graphQuery.substring(0,500)}${p.graphQuery.length>500?"...":""}`},u);let m=await ob({kg:e,queryParams:new yp({openCypherQuery:p.graphQuery}),targetStructure:n,targetStructureReducer:o,requestOptions:s,queryRowLimit:a,queryTimeoutMs:i}),h=m.type==="aborted"?"Query execution was aborted.":m.type==="timeout"?"Query execution timed out.":m.type==="error"?`Query failed with error: ${m.errorMessage}`:"";if(m.type==="success")return{type:"success",graphQuery:p.graphQuery,explanation:p.explanation,rowLimitReached:m.rowLimitReached,resultHeader:m.resultHeader,processedResult:m.processedResult};if(m.type==="aborted")return{type:"aborted",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation};if(c>=ro)return m.type==="timeout"?{type:"timeout",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation}:{type:"execution-error",errorMessage:h,error:m.error,graphQuery:p.graphQuery,explanation:p.explanation};l={failedGraphQuery:p.graphQuery,executionError:h,attemptCount:c},await ee({text:`Attempt ${c} failed with error: ${h}. Retrying...`},u)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${ro} attempts.`)}var sb=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let c=u-a.length;if(c<=0)break;let p=(await ry(t,new ny({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:c}),s)).resultRowsStream.getReader(),m=!1;for(;!m;){let{done:h,value:y}=await p.read();if(h){m=!0;break}for(let A of y)for(let C of A)a.push(C)}}}catch(l){let c=ao(l);return s?.signal?.aborted?{type:"aborted",errorMessage:c,error:l}:{type:"error",errorMessage:c,error:l}}return{type:"success",results:a}};function ab(t,e){no(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function no(t,e){if(!(!t||typeof t!="object")){if(lb(t))for(let r of t.path)no(r,e);else if(ib(t))e(t);else if(Array.isArray(t))for(let r of t)no(r,e);else if(ub(t))for(let r of Object.values(t.properties??{}))no(r,e)}}function ib(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function lb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function ub(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=[];for(let n of[...e.dataModel.entityTypes,...e.dataModel.relationshipTypes]){let o=t.getMemberIdsByType(n.name);for(let s of o)r.push({id:s,typeName:n.name})}return r}function db(t){let e=[],r=[],n=t?.allLayers.find(o=>o.type==="knowledge-graph")?.inclusionModeDefinition;if(n?.generateAllSublayers)return{allNamedTypesFullyDynamic:!0,idTypePairs:e,dynamicTypes:r};for(let[o,s]of n?.namedTypeDefinitions??[])if(s.useAllData)r.push(o);else for(let[a]of s.members)e.push({id:a,typeName:o});return{allNamedTypesFullyDynamic:!1,idTypePairs:e,dynamicTypes:r}}async function pb(t,e,r,n,o){let{view:s}=n,a=await Tp({prompt:t,kg:e,graphQueryServiceUrl:r,targetStructure:new Map,targetStructureReducer:(p,m)=>{for(let h of m)ab(h,p);return p},requestOptions:{signal:ba(o),timeout:o?.timeout},config:o});if(a.type!=="success"){let p=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${p}`)}let{graphQuery:i,explanation:u,processedResult:l}=a,c=Array.from(l.values());return await ee({text:`Query Results parsed into ${c.length} unique relationships and entities. Atempting to add to link chart...`},o),!Mr(s)&&s?.map?(await s.map.addRecords(c),await wa(s),{generatedQuery:i,explanation:u,addedIdTypePairs:c}):(await s?.map?.allLayers.find(p=>p.type==="knowledge-graph")?.addRecords(c),{generatedQuery:i,explanation:u,addedIdTypePairs:c})}var pa="addRecords",mb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),fb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await so(e),n=_a(e),{view:o}=n,s=Er.getDefault().helperServices,a=t;if(!Mr(o)&&o.map){let i=o.map,u=await Wt("arcgis_knowledge_current_lc_context"),l=cb(i,r);a=`${t}
212
208
 
213
- Explanation: ${u}`):(await s?.map?.allLayers.find(p=>p.type==="knowledge-graph")?.addRecords(c),`Map updated successfully. Cypher Query used:
214
- ${i}
209
+ ${u}${JSON.stringify(l)}`}else if(Mr(o)&&o.map){let i=o.map,{allNamedTypesFullyDynamic:u,idTypePairs:l,dynamicTypes:c}=db(i),p=await Wt("arcgis_knowledge_current_map_context");if(a=`${t}
215
210
 
216
- Explanation: ${u}`)}var mp="addRecords",Qw=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Yw=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=ga(e),{view:o}=n,s=Er.getDefault().helperServices,a=t;if(!eo(o)&&o.map){let u=o.map,l=await Wt("arcgis_knowledge_current_lc_context"),c=Hw(u,r);a=`${t}
211
+ ${p}${JSON.stringify(l)} and all entities or relationships with the the following typeNames in the array: ${JSON.stringify(c)}`,u)return{toolName:pa,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:i,explanation:u,addedIdTypePairs:l}=await pb(a,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:pa,status:"success",summary:`Records added successfully. Cypher Query used: ${i}
217
212
 
218
- ${l}${JSON.stringify(c)}`}else{let u=o.map,{allNamedTypesFullyDynamic:l,idTypePairs:c,dynamicTypes:p}=Jw(u),m=await Wt("arcgis_knowledge_current_map_context");if(a=`${t}
213
+ Number of records added: ${l.length}`,details:{generatedQuery:i,explanation:u,addedIdTypePairs:l}}}catch(i){let u=ao(i);return console.error(`Failed to add records to the link chart. ${u}`,i),{toolName:pa,status:"error",errorMessage:`Failed to add records to the link chart. ${u}`,error:i}}},hb=D(fb,{name:pa,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.",schema:mb});async function gb(t,e){return await e.map?.applyLayout(t),await wa(e),{appliedLayout:t}}var Hi="applyLayout",yb=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")}),wb=async({layout:t},e)=>{let{view:r}=_a(e);if(Mr(r))return{toolName:Hi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await gb(t,r);return{toolName:Hi,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},_b=D(wb,{name:Hi,description:"Apply a diagram layout to the link chart",schema:yb});async function bb(t,e){return e.map?.changeNonspatialDataDisplay(t),await wa(e),{appliedNonspatialDataDisplayMode:t}}var Ji="changeNonspatialVisibility",xb=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Ab=async({setting:t},e)=>{let{view:r}=_a(e);if(Mr(r))return{toolName:Ji,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await bb(t,r);return{toolName:Ji,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},Ib=D(Ab,{name:Ji,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:xb});async function vb(t,e,r,n,o){let s,a="";for(let i=1;i<=ro;i++){let{graphQuery:u,explanation:l}=await tl(t,e.dataModel,r,o,s);try{await ee({text:`Attempting to create link chart from derived query: ${u}`},o);let c=await ey.fromCypherQuery(e,new yp({openCypherQuery:u}));await ee({text:"Link chart created successfully, loading..."},o),await c.load();let p=n.map;return n.map=c,await n.when(),await mp.whenOnce(()=>!n.updating),c.entityCount===0&&c.relationshipCount===0?(n.map===c&&(n.map=p),c.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
214
+ ${u}
219
215
 
220
- ${m}${JSON.stringify(c)} and all entities or relationships with the the following typeNames in the array: ${JSON.stringify(p)}`,l)throw new Error("No records have been added to the map because all data in the knowledge graph is contained in the map.")}let i=await Zw(a,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:mp,status:"success",summary:i}},Xw=D(Yw,{name:mp,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.",schema:Qw});async function eb(t,e){return await e.map?.applyLayout(t),await ha(e),`Successfully applied layout: ${t}.`}var qi="applyLayout",tb=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")}),rb=async({layout:t},e)=>{let{view:r}=ga(e);if(eo(r))return{toolName:qi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let n=await eb(t,r);return{toolName:qi,status:"success",summary:n}}},nb=D(rb,{name:qi,description:"Apply a diagram layout to the link chart",schema:tb});async function ob(t,e){return e.map?.changeNonspatialDataDisplay(t),await ha(e),`Successfully applied nonspatial visibility setting: ${t}.`}var Bi="changeNonspatialVisibility",sb=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),ab=async({setting:t},e)=>{let{view:r}=ga(e);if(eo(r))return{toolName:Bi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let n=await ob(t,r);return{toolName:Bi,status:"success",summary:n}}},ib=D(ab,{name:Bi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:sb});async function lb(t,e,r,n,o){let s;for(let a=1;a<=Cr;a++){let{graphQuery:i,explanation:u}=await Vi(t,e.dataModel,r,o,s);try{await re({text:`Attempting to create link chart from derived query: ${i}`},o);let l=await zg.fromCypherQuery(e,new op({openCypherQuery:i}));await re({text:"Link chart created successfully, loading..."},o),await l.load();let c=n.map;return n.map=l,await n.when(),await ep.whenOnce(()=>!n.updating),l.entityCount===0&&l.relationshipCount===0?(n.map===l&&(n.map=c),l.destroy(),{type:"error",message:`Query returned no results. Cypher Query used to create the link chart:
221
- ${i}
222
-
223
- Explanation: ${u}`}):(await ha(n),{type:"success",message:`Link chart created successfully. Cypher Query used to create the link chart:
224
- ${i}
216
+ Explanation: ${l}`}):(await wa(n),{type:"success",graphQuery:u,explanation:l})}catch(c){let p=ao(c);if(i>=ro){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await ee({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${ro} attempts. Last error: ${a}`}}var ma="createLinkChart",Tb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Sb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await so(e),{view:n}=_a(e);if(Mr(n))return{toolName:ma,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=Er.getDefault().helperServices,s=await vb(t,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:ma,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:ma,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
217
+ ${a}
225
218
 
226
- Explanation: ${u}`})}catch(l){let c=l instanceof Error?l.message:String(l);if(a>=Cr)throw new Error(`Failed to create link chart after ${Cr} attempts. Last error: ${c}`);s={failedGraphQuery:i,executionError:c,attemptCount:a},await re({text:`Attempt ${a} to create link chart failed with error: ${c}. Retrying ...`},o)}}throw new Error(`Failed to create link chart after ${Cr} attempts.`)}var ca="createLinkChart",ub=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),cb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),{view:n}=ga(e);if(eo(n))return{toolName:ca,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=Er.getDefault().helperServices,s=await lb(t,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);return s.type==="error"?{toolName:ca,status:"error",errorMessage:s.message,error:new Error}:{toolName:ca,status:"success",summary:s.message}}},db=D(cb,{name:ca,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.",schema:ub}),fp="queryGraphData",pb=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. IMPORTANT:
219
+ Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},kb=D(Sb,{name:ma,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.",schema:Tb}),Zi="queryGraphData",Cb=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. IMPORTANT:
227
220
 
228
221
  REQUEST LIMIT: If the user does not specifically request for no limits or an explicit limit to be placed on the query, or the number of rows will not be limited by e.g. the number of entity or relationship types in the graph, ensure that the generated query has a reasonable row limit (e.g. 10 rows).
229
222
 
230
- DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),mb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Er.getDefault().helperServices,o=await pp({prompt:t,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(p,m)=>(p.push(m),p),requestOptions:{signal:e?.signal,timeout:e?.timeout},config:e});if(o.type!=="success"){let p=o.type==="generation-error"?o.errorMessage:`${o.errorMessage} Cypher query: ${o.graphQuery}`;throw new Error(`Failed to query the knowledge graph. ${p}`)}let{graphQuery:s,processedResult:a,resultHeader:i}=o,u=i.headerKeys;for(let p of a)for(let m of p)Yn(m,h=>dp(h));let l=50,c=a.slice(0,l).map(p=>JSON.stringify(p));return{toolName:fp,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
223
+ DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),Eb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await so(e),n=Er.getDefault().helperServices,o=await Tp({prompt:t,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(m,h)=>(m.push(h),m),requestOptions:{signal:ba(e),timeout:e?.timeout},config:e});if(o.type!=="success"){let m=o.type==="generation-error"?o.errorMessage:`${o.errorMessage} Cypher query: ${o.graphQuery}`;return{toolName:Zi,status:"error",errorMessage:`Failed to query the knowledge graph. ${m}`,error:"error"in o?o.error:null}}let{graphQuery:s,explanation:a,processedResult:i,resultHeader:u}=o,l=u.headerKeys;for(let m of i)for(let h of m)no(h,y=>vp(y));let c=50,p=i.slice(0,c).map(m=>JSON.stringify(m));return{toolName:Zi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
231
224
 
232
225
  \`\`\`cypher
233
226
  ${s}
234
227
  \`\`\`
235
228
 
236
229
  Query Results:
237
- ${c.length} result(s) found.
230
+ ${p.length} result(s) found.
238
231
 
239
- Column Headers: ${u.join(", ")}
232
+ Column Headers: ${l.join(", ")}
240
233
 
241
- ${c.length>l?`Showing top ${l} results:
234
+ ${p.length>c?`Showing top ${c} results:
242
235
 
243
236
  `:`Results:
244
237
 
245
- `}${c.join(`
238
+ `}${p.join(`
246
239
  `)}
247
- `,details:{generatedQuery:s,resultHeader:i,queryResults:a}}},fb=D(mb,{name:fp,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:pb}),hp="generateCypher",hb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),gb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Er.getDefault().helperServices,o=await Uw(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:hp,status:"success",summary:o}},yb=D(gb,{name:hp,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:hb}),_b=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let c=r.get(u)??new Set;l.propertyNames.forEach(p=>c.add(p)),r.set(u,c)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
240
+ `,details:{generatedQuery:s,explanation:a,resultHeader:u,queryResults:i}}},Mb=D(Eb,{name:Zi,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:Cb}),Qi="generateCypher",Ob=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Pb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await so(e),n=Er.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await nb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Qi,status:"success",summary:`Generated Graph Query:
241
+ ${o}
242
+
243
+ Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=ao(o);return{toolName:Qi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},Rb=D(Pb,{name:Qi,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:Ob}),$b=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let c=r.get(u)??new Set;l.propertyNames.forEach(p=>c.add(p)),r.set(u,c)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
248
244
  ${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
249
245
  `)}`,a=`Relationship Types:
250
246
  ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
251
247
  `)}`;return`${s}
252
248
 
253
- ${a}`};async function wb(t,e){let r=await Wt("arcgis_knowledge_lucene_generation_prompt"),n={inquiry:t,dataModelForSearch:_b(e)},o=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),s=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(u=>u.name).concat(e.dataModel.relationshipTypes.map(u=>u.name)))).min(1),i=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:o,resultLimit:s});return await Wo({promptText:r,inputVariables:n,schema:i})}var gp="searchGraphData",bb=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.")}),Ab=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e);await re({text:"Generating search query for the user inquiry"},e);let n=await wb(t,r);await re({text:"Executing graph search with generated search query"},e);let o=await Bw({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:e?.signal,timeout:e?.timeout}});if(o.type!=="success")throw new Error(`Graph search failed with error: ${o.type==="error"?o.errorMessage:"aborted"}`);for(let i of o.results)Yn(i,u=>dp(u));let s=10,a=o.results.slice(0,s);return{toolName:gp,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
249
+ ${a}`};async function Nb(t,e){let r=await Wt("arcgis_knowledge_lucene_generation_prompt"),n={inquiry:t,dataModelForSearch:$b(e)},o=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),s=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(u=>u.name).concat(e.dataModel.relationshipTypes.map(u=>u.name)))).min(1),i=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:o,resultLimit:s});return await Vo({promptText:r,inputVariables:n,schema:i})}var Yi="searchGraphData",jb=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.")}),zb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await so(e);await ee({text:"Generating search query for the user inquiry"},e);let n=await Nb(t,r);await ee({text:"Executing graph search with generated search query"},e);let o=await sb({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:ba(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Yi,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)no(i,u=>vp(u));let s=10,a=o.results.slice(0,s);return{toolName:Yi,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
254
250
  Query: ${n.query}
255
251
  Type Category Filter: ${n.typeCategoryFilter}
256
252
  Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
@@ -261,7 +257,7 @@ ${a}`};async function wb(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
261
257
  ${o.results.length>s?`Showing top ${s} results:
262
258
 
263
259
  `:""}${a.map(i=>JSON.stringify(i)).join(`
264
- `)}`,details:{generatedQuery:n,searchResults:{...o}}}},xb=D(Ab,{name:gp,description:"Allows users to search the knowledge graph for text matching their inquiry, 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.",schema:bb});var PK=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
260
+ `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},Lb=D(zb,{name:Yi,description:"Allows users to search the knowledge graph for text matching their inquiry, 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.",schema:jb});var IG=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
265
261
  This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
266
262
 
267
263
  Supported actions:
@@ -280,11 +276,11 @@ ${a}`};async function wb(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
280
276
  _Example: “Center the map on San Francisco at scale 50000”_
281
277
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
282
278
  _Example: “Go to the Downtown bookmark”_
283
- _Example: “Where is Mount Rainier?”_`;var oW=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
279
+ _Example: “Where is Mount Rainier?”_`;var XG=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.
284
280
  _Example: “Color points by sales amount”_
285
281
  _Example: “Show population density with a color gradient”_
286
282
  _Example: “Create a relationship map between height and depth”_
287
- _Example: “Vary circle sizes according to population”_`;var SW=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
283
+ _Example: “Vary circle sizes according to population”_`;var I2=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).
288
284
  The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
289
285
  _Example: “Only show stations where Brand is Shell”_
290
286
  _Example: “Make Shell stations stand out on the map”_
@@ -292,7 +288,7 @@ ${a}`};async function wb(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
292
288
  This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
293
289
  _Example: “How many features are there?”_
294
290
  _Example: “What’s the average population?”_
295
- _Example: “Which values are in the status field?”_`;var UW=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
291
+ _Example: “Which values are in the status field?”_`;var F2=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
296
292
 
297
293
  _Example: “Tell me about this map”_
298
294
  _Example: “List all layers in this map”_
@@ -305,7 +301,7 @@ ${a}`};async function wb(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
305
301
 
306
302
  IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond accordingly.
307
303
  _Example: "Create a chart"_
308
- _Example: "Create a table"_`;var n2=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).
304
+ _Example: "Create a table"_`;var oW=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).
309
305
  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.
310
306
  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,
311
307
  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
@@ -343,7 +339,7 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
343
339
  _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
344
340
  _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
345
341
  _example: "Find John Smith and all people he has made phone calls to in the last year"_
346
- _example: "What is the average age of all people who work for Esri?"_`;var Or=Wo;var ze=re;var _a=()=>ia(),Ji=async(t,e)=>await Ae(t,e),Zi=async({modelTier:t="default",temperature:e=0,abortSignal:r}={})=>await ji({modelTier:t,temperature:e,abortSignal:r});var Zo=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Sb=()=>({latestItemId:null,memory:{}}),Xi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Sb()},kb=d.object({intent:d.enum(["summarize","followUp","clarify"]),itemId:d.string().default(""),question:d.string().default("")}),Cb=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Eb=d.object({answer:d.string(),isRelevant:d.boolean()}),Ob=async(t,e)=>{await ze({text:"Answering follow-up...",agentName:"analytics"},e);let r=Xi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Zo(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Or({promptText:Mb,schema:Eb,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Mb=`
342
+ _example: "What is the average age of all people who work for Esri?"_`;var gt=Vo;var ge=ee;var Yo=()=>ua(),Aa=async(t,e)=>await _e(t,e),Ia=async({modelTier:t="default",temperature:e=0,config:r}={})=>await Ui({modelTier:t,temperature:e,config:r});var Or=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Ub=()=>({latestItemId:null,memory:{}}),al=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Ub()},Bb=d.object({intent:d.enum(["summarize","followUp","clarify"]),itemId:d.string().default(""),question:d.string().default("")}),Kb=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Gb=d.object({answer:d.string(),isRelevant:d.boolean()}),Wb=async(t,e)=>{await ge({text:"Answering follow-up...",agentName:"analytics"},e);let r=al(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Or(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await gt({promptText:Vb,schema:Gb,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Vb=`
347
343
  You answer follow-up questions about an ArcGIS item.
348
344
 
349
345
  Ground your answer in the provided item context.
@@ -363,7 +359,7 @@ Item full context
363
359
 
364
360
  Question:
365
361
  {question}
366
- `;function ro(t){let{portal:e,user:r}=t??{};if(!t||!e||!r)throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Tp=D(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;ro(n);let{result:o,error:s}=await Rl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:d.object({itemTitle:d.string().describe("The portal item title to resolve to an item id.")})}),Pb=async(t,e)=>{await ze({text:"Analyzing intent...",agentName:"analytics"},e);let r=Zo(t.agentExecutionContext.messages),n=!!Xi(t).latestItemId,o=await po.fromTemplate(Rb).format({userMessage:r,hasSummaryContext:String(n)}),s=await _o({model:await Zi({modelTier:"fast"}),tools:[Tp],systemPrompt:o,responseFormat:kb,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Rb=`
362
+ `;function Pr(t){let{portal:e,user:r}=t??{};if(!t||!e||!r)throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var $p=D(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;Pr(n);let{result:o,error:s}=await ql(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:d.object({itemTitle:d.string().describe("The portal item title to resolve to an item id.")})}),Hb=async(t,e)=>{await ge({text:"Analyzing intent...",agentName:"analytics"},e);let r=Or(t.agentExecutionContext.messages),n=!!al(t).latestItemId,o=await zr.fromTemplate(Jb).format({userMessage:r,hasSummaryContext:String(n)}),s=await Fr({model:await Ia({modelTier:"fast"}),tools:[$p],systemPrompt:o,responseFormat:Bb,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Jb=`
367
363
  Classify the user analytics request.
368
364
 
369
365
  Rules:
@@ -393,7 +389,7 @@ hasSummaryContext:
393
389
 
394
390
  User message:
395
391
  {userMessage}
396
- `,$b=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await ze({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;ro(n);let{portal:o,user:s}=n,{result:a,error:i}=await $l(s,o,r);if(i||!a)return await ze({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await Or({promptText:Nb,schema:Cb,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:c,summary:p}=l,m=Xi(t),h={latestItemId:r,memory:{...m.memory,[r]:{summary:p,followUpQuestions:c,fullContext:u}}};return c.length&&await Ji({type:"suggested-prompts",data:{prompts:c}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:h}}}},Nb=`
392
+ `,Zb=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await ge({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;Pr(n);let{portal:o,user:s}=n,{result:a,error:i}=await Ul(s,o,r);if(i||!a)return await ge({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await gt({promptText:Qb,schema:Kb,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:c,summary:p}=l,m=al(t),h={latestItemId:r,memory:{...m.memory,[r]:{summary:p,followUpQuestions:c,fullContext:u}}};return c.length&&await Aa({type:"suggested-prompts",data:{prompts:c}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:h}}}},Qb=`
397
393
  You are a item summary tool for ArcGIS. Your job is to summarize an item's info based on the provided context.
398
394
  Summary rules:
399
395
  - The summary should be concise markdown, make sure to format the output nicely so it's easy to read.
@@ -408,15 +404,15 @@ Do not include internal identifiers.
408
404
  If the user asks for a detailed summary, you may expand the response up to 300 words.
409
405
  Item context:
410
406
  {context}
411
- `,Qi=(t,e)=>e??t,Sp=$.Root({..._a(),analyticsIntent:$({reducer:Qi,default:()=>"clarify"}),analyticsItemId:$({reducer:Qi,default:()=>null}),analyticsQuestion:$({reducer:Qi,default:()=>""})}),jb=()=>new ye(Sp).addNode("detectAnalyticsIntent",Pb).addNode("summarizePortalItem",$b).addNode("answerAnalyticsFollowUp",Ob).addEdge(he,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":B).addEdge("summarizePortalItem",B).addEdge("answerAnalyticsFollowUp",B),Lb=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
407
+ `,nl=(t,e)=>e??t,Np=O.Root({...Yo(),analyticsIntent:O({reducer:nl,default:()=>"clarify"}),analyticsItemId:O({reducer:nl,default:()=>null}),analyticsQuestion:O({reducer:nl,default:()=>""})}),Yb=()=>new de(Np).addNode("detectAnalyticsIntent",Hb).addNode("summarizePortalItem",Zb).addNode("answerAnalyticsFollowUp",Wb).addEdge(ue,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":q).addEdge("summarizePortalItem",q).addEdge("answerAnalyticsFollowUp",q),Xb=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
412
408
  - summarizes ArcGIS portal items from item context
413
409
  - suggests follow-up prompts grounded in the item
414
- `,zb={id:"portal-item-analytics",name:"Portal Item Analytics",description:Lb,createGraph:jb,workspace:Sp},Db=t=>t.map(e=>`"${e}"`).join(", "),Fb=d.object({successMessage:d.string().default("")}),wp="portal-group-creation",bp="approveAddMembers",Ub=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
410
+ `,ex={id:"portal-item-analytics",name:"Portal Item Analytics",description:Xb,createGraph:Yb,workspace:Np},tx=t=>t.map(e=>`"${e}"`).join(", "),rx=d.object({successMessage:d.string().default("")}),Cp="portal-group-creation",Ep="approveAddMembers",nx=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
415
411
 
416
412
  ${n.map(p=>`- **@${p}**`).join(`
417
413
  `)}
418
414
 
419
- Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==wp||s.id!==bp){let p={agentId:wp,id:bp,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new Yo(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ze({text:`Adding members ${Db(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;ro(a);let{result:i,error:u}=await Ll(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:c}=i;try{let p=(await Or({promptText:qb,schema:Fb,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(c.map(m=>({username:m.username,reason:m.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},qb=`
415
+ Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Cp||s.id!==Ep){let p={agentId:Cp,id:Ep,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new es(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ge({text:`Adding members ${tx(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;Pr(a);let{result:i,error:u}=await Gl(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:c}=i;try{let p=(await gt({promptText:ox,schema:rx,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(c.map(m=>({username:m.username,reason:m.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},ox=`
420
416
  Write a concise, friendly success message for adding members to a group.
421
417
 
422
418
  Rules:
@@ -431,7 +427,7 @@ Added members:
431
427
 
432
428
  Not added members:
433
429
  {notAddedMembers}
434
- `,Ap="portal-group-creation",xp="approveCreateGroup",Bb=d.object({successMessage:d.string().default("")}),Kb=d.object({failureMessage:d.string().default("")}),Wb=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==Ap||o.id!==xp){let l={agentId:Ap,id:xp,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new Yo(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ze({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;ro(s);let{result:a,error:i}=await jl(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let c=(await Or({promptText:Gb,schema:Kb,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(c)return{status:"success",outputMessage:c}}catch(c){console.error("Error generating create-group failure message:",c)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Or({promptText:Vb,schema:Bb,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},Vb=`
430
+ `,Mp="portal-group-creation",Op="approveCreateGroup",sx=d.object({successMessage:d.string().default("")}),ax=d.object({failureMessage:d.string().default("")}),ix=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==Mp||o.id!==Op){let l={agentId:Mp,id:Op,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new es(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ge({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;Pr(s);let{result:a,error:i}=await Kl(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let c=(await gt({promptText:ux,schema:ax,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(c)return{status:"success",outputMessage:c}}catch(c){console.error("Error generating create-group failure message:",c)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await gt({promptText:lx,schema:sx,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},lx=`
435
431
  Write a concise, friendly success message after creating a portal group.
436
432
 
437
433
  Rules:
@@ -442,7 +438,7 @@ Rules:
442
438
 
443
439
  Group title:
444
440
  {groupTitle}
445
- `,Gb=`
441
+ `,ux=`
446
442
  Write a concise, friendly failure message after an attempt to create a portal group.
447
443
 
448
444
  Rules:
@@ -457,7 +453,7 @@ Group title:
457
453
 
458
454
  Failure reason:
459
455
  {failureReason}
460
- `,Hb=d.object({intent:d.enum(["clarify","create","addMembers"]).default("clarify"),title:d.string().default(""),memberIdentifiers:d.array(d.string()).default([]),clarifyMessage:d.string().default("")}),Jb=async(t,e)=>{await ze({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Zo(t.agentExecutionContext.messages).trim(),n=await Or({promptText:Zb,schema:Hb,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},Zb=`
456
+ `,cx=d.object({intent:d.enum(["clarify","create","addMembers"]).default("clarify"),title:d.string().default(""),memberIdentifiers:d.array(d.string()).default([]),clarifyMessage:d.string().default("")}),dx=async(t,e)=>{await ge({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Or(t.agentExecutionContext.messages).trim(),n=await gt({promptText:px,schema:cx,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},px=`
461
457
  You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
462
458
 
463
459
  Rules:
@@ -483,10 +479,10 @@ Examples:
483
479
 
484
480
  User message:
485
481
  {userMessage}
486
- `,Qb=d.discriminatedUnion("destinationType",[d.object({destinationType:d.literal("portal-content")}),d.object({destinationType:d.literal("portal-groups")}),d.object({destinationType:d.literal("portal-item"),itemId:d.string().trim().min(1)}),d.object({destinationType:d.literal("portal-group"),groupId:d.string().trim().min(1)})]);function Yb(t){let e=Qb.safeParse(t);return e.success?e.data:void 0}var kp="portal-navigation",Cp=async(t,e)=>{await Ji({type:kp,data:{...t}},e)},Xb=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ze({text:"Preparing navigation...",agentName:"group-creation"},e),await Cp({destinationType:"portal-group",groupId:r},e),{}):{}},Ip=(t,e)=>e??t,Ep=$.Root({..._a(),intentParams:$({reducer:Ip,default:()=>({intent:"clarify"})}),createdGroupId:$({reducer:Ip,default:()=>""})}),eA=()=>new ye(Ep).addNode("detectGroupCreationIntent",Jb).addNode("createPortalGroup",Wb).addNode("addMembersToPortalGroup",Ub).addNode("suggestCreatedGroupNavigation",Xb).addEdge(he,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return B}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",B),tA=String.raw`- **portal-group-creation** - Portal group creation assistant:
482
+ `,mx=d.discriminatedUnion("destinationType",[d.object({destinationType:d.literal("portal-content")}),d.object({destinationType:d.literal("portal-groups")}),d.object({destinationType:d.literal("portal-item"),itemId:d.string().trim().min(1)}),d.object({destinationType:d.literal("portal-group"),groupId:d.string().trim().min(1)})]);function fx(t){let e=mx.safeParse(t);return e.success?e.data:void 0}var jp="portal-navigation",il=async(t,e)=>{await Aa({type:jp,data:{...t}},e)},hx=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ge({text:"Preparing navigation...",agentName:"group-creation"},e),await il({destinationType:"portal-group",groupId:r},e),{}):{}},Pp=(t,e)=>e??t,zp=O.Root({...Yo(),intentParams:O({reducer:Pp,default:()=>({intent:"clarify"})}),createdGroupId:O({reducer:Pp,default:()=>""})}),gx=()=>new de(zp).addNode("detectGroupCreationIntent",dx).addNode("createPortalGroup",ix).addNode("addMembersToPortalGroup",nx).addNode("suggestCreatedGroupNavigation",hx).addEdge(ue,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return q}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",q),yx=String.raw`- **portal-group-creation** - Portal group creation assistant:
487
483
  - creates a new ArcGIS Portal group for the signed-in user
488
484
  - adds users to the newly created group using @mention usernames
489
- `,rA={id:"portal-group-creation",name:"Portal Group Creation",description:tA,createGraph:eA,workspace:Ep},Op="portalDocAssistantMemory",nA=()=>({conversationId:""}),oA=t=>{let e=t?.[Op]?.value;if(!e||typeof e!="object")return nA();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},sA=t=>({[Op]:{value:t}});async function aA({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await iA({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:lA(a,s),conversationId:a[0]?.conversationId??""}}async function iA({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Tb.findCredential(t.url)?.token??""},a=await _p(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(m,h)=>{if(!h)return;await il(1e3);let _=await _p(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:m}),headers:s,signal:n.signal});if(_.httpStatus!==200)throw new Error(`Doc assistant poll failed (${_.httpStatus})`,{cause:_.data});let I=_.data;u.push(I),await p(I.sequenceNumber,I.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function lA(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return so(e)}}var uA=async(t,e)=>{await ze({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Zo(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;ro(n);let o=oA(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await aA({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:sA({conversationId:a||o.conversationId})}},cA=D(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;ro(n);try{return(await Nl(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:d.object({groupTitle:d.string().describe("The portal group title to resolve to a group id.")})}),vp=d.object({shouldSuggestNavigation:d.boolean().default(!1),destinationType:d.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:d.string().default(""),groupId:d.string().default("")}),dA=async(t,e)=>{await ze({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Zo(t.agentExecutionContext.messages).trim(),o=await po.fromTemplate(mA).format({question:n,response:r}),s=await _o({model:await Zi({modelTier:"default"}),tools:[Tp,cA],systemPrompt:o,responseFormat:vp,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=vp.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=pA(a);return i?(await Cp(i,e),{}):{}};function pA({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return so(t)}}var mA=`
485
+ `,wx={id:"portal-group-creation",name:"Portal Group Creation",description:yx,createGraph:gx,workspace:zp},Lp="portalDocAssistantMemory",_x=()=>({conversationId:""}),bx=t=>{let e=t?.[Lp]?.value;if(!e||typeof e!="object")return _x();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},xx=t=>({[Lp]:{value:t}});async function Ax({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await Ix({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:vx(a,s),conversationId:a[0]?.conversationId??""}}async function Ix({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:qb.findCredential(t.url)?.token??""},a=await kp(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(m,h)=>{if(!h)return;await hl(1e3);let y=await kp(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:m}),headers:s,signal:n.signal});if(y.httpStatus!==200)throw new Error(`Doc assistant poll failed (${y.httpStatus})`,{cause:y.data});let A=y.data;u.push(A),await p(A.sequenceNumber,A.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function vx(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return uo(e)}}var Tx=async(t,e)=>{await ge({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Or(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;Pr(n);let o=bx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Ax({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:xx({conversationId:a||o.conversationId})}},Dp=D(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;Pr(n);try{return(await Bl(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:d.object({groupTitle:d.string().describe("The portal group title to resolve to a group id.")})}),Rp=d.object({shouldSuggestNavigation:d.boolean().default(!1),destinationType:d.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:d.string().default(""),groupId:d.string().default("")}),Sx=async(t,e)=>{await ge({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Or(t.agentExecutionContext.messages).trim(),o=await zr.fromTemplate(Cx).format({question:n,response:r}),s=await Fr({model:await Ia({modelTier:"default"}),tools:[$p,Dp],systemPrompt:o,responseFormat:Rp,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=Rp.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=kx(a);return i?(await il(i,e),{}):{}};function kx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return uo(t)}}var Cx=`
490
486
  You decide whether the assistant response should include a navigation action to ArcGIS Portal.
491
487
 
492
488
  Given the user question and assistant response:
@@ -510,7 +506,111 @@ User question:
510
506
 
511
507
  Assistant response:
512
508
  {response}
513
- `,Mp=$.Root({..._a()}),fA=()=>new ye(Mp).addNode("answerDocQuestion",uA).addNode("extractNavigationIntent",dA).addEdge(he,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",B),hA=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
509
+ `,Fp=O.Root({...Yo()}),Ex=()=>new de(Fp).addNode("answerDocQuestion",Tx).addNode("extractNavigationIntent",Sx).addEdge(ue,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",q),Mx=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
514
510
  - answers general ArcGIS, Portal, Enterprise, and JavaScript SDK questions
515
511
  - acts as a fallback when specialized agents are not applicable
516
- `,gA={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:hA,createGraph:fA,workspace:Mp},yA=tl`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`,_A=(t,e)=>{let{destinationType:r}=t,n=`${e.url}/home`;switch(r){case"portal-content":return`${n}/content.html`;case"portal-groups":return`${n}/groups.html`;case"portal-item":return`${n}/item.html?id=${t.itemId}`;case"portal-group":return`${n}/group.html?id=${t.groupId}`;default:return so(r)}},Yi=class extends ol{constructor(){super(...arguments),this.t9n=al({blocking:!0}),this.assistantEl=no(),this.formEl=no(),this.voiceInputEl=no(),this.inputEl=no(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=nl()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,defaultClosed:5}}static{this.styles=yA}getNavigationAction(e){if(e?.type!==kp)return;let r=Yb(e.data);if(!r)return;let n=_A(r,this.portal);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),rl(Mr`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?Mr`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-groups":return r.openGroups;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return so(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,showVoiceInput:s,isListening:a,isVoiceInputDisabled:i}=this;return Mr`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:u})=>{this.interrupt=u}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:u})=>{this.inputText=u.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${oo(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${u=>{u.preventDefault();let l=r.trim();l&&(this.assistantEl.value?.submitMessage(l),this.inputText="")}} ${oo(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:u})=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:u})=>{this.inputText=u??""}} ${oo(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${u=>{u.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${u=>{this.inputText=u.detail.text}} ${oo(this.voiceInputEl)}></arcgis-portal-voice-input>${s&&Mr`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${i} .appearance=${a?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let u=this.voiceInputEl.value;a?await u?.stopListening():await u?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${zb} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${rA} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${gA} .context=${{portal:n,user:o}}></arcgis-assistant-agent>${this.interrupt&&Mr`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:u})=>{this.assistantEl.value?.submitInterrupt(u)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};sl("arcgis-portal-ai-assistant",Yi);return Yi},"identity/IdentityManager","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","config","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","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","request",a)
512
+ `,Ox={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:Mx,createGraph:Ex,workspace:Fp},qp=`
513
+ Shared markdown formatting rules:
514
+ - Use clear markdown headings (##) to separate sections.
515
+ - Use concise bullet points for lists of facts, counts, or signals.
516
+ - Emphasize key metrics with bold labels (for example: **Recent items:** 4).
517
+ - Keep wording direct and analytical; avoid filler language but make sure the language is friendly.
518
+ - Do not include raw internal IDs unless explicitly requested.
519
+ `,Px=()=>({latestGroupId:null,memory:{}}),va=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:Px()},Rx=async(t,e)=>{await ge({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=va(t),n=t.groupSummaryGroupId??r.latestGroupId,o=n?r.memory[n]:void 0,s=t.groupSummaryQuestion||Or(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await gt({promptText:Nx,schema:$x,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I do not have group analytics context yet. Ask me to analyze a group first with analyze group <group id>."}},$x=d.object({answer:d.string(),isRelevant:d.boolean()}),Nx=`
520
+ You answer follow-up questions about ArcGIS group analytics.
521
+
522
+ ${qp}
523
+
524
+ Ground your answer in the provided group analytics summary and context.
525
+ If the answer is not available from the provided context, state that clearly and suggest what to check next.
526
+
527
+ Response rules:
528
+ - Reply in concise markdown with this section structure:
529
+ 1) ## Answer
530
+ 2) ## Evidence
531
+ 3) ## Gaps (only when data is missing)
532
+ - Keep the answer focused on the follow-up question.
533
+ - Do not include internal identifiers.
534
+ - Mark isRelevant=false when the question is not about this group or cannot be grounded in this group context.
535
+
536
+ Group analytics summary:
537
+ {summary}
538
+
539
+ Group full context:
540
+ {fullContext}
541
+
542
+ Question:
543
+ {question}
544
+ `,jx=async(t,e)=>{await ge({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=Or(t.agentExecutionContext.messages),n=!!va(t).latestGroupId,o=await zr.fromTemplate(Lx).format({userMessage:r,hasAnalyticsContext:String(n)}),s=await Fr({model:await Ia({modelTier:"fast"}),tools:[Dp],systemPrompt:o,responseFormat:zx,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,groupId:i,question:u}=s.structuredResponse,l=a==="summarize"&&!i,c=a==="followUp"&&!(u??"").trim(),p=a==="clarify"||l||c;return{groupSummaryIntent:p?"clarify":a,groupSummaryGroupId:i||null,groupSummaryQuestion:u||"",status:"success",outputMessage:p?"Please clarify with a group id or title":""}},zx=d.object({intent:d.enum(["summarize","followUp","navigation","clarify"]),groupId:d.string().default(""),question:d.string().default("")}),Lx=`
545
+ Classify the user's request for ArcGIS Portal group analytics.
546
+
547
+ Rules:
548
+ - intent="summarize" only when the user explicitly asks to summarize, analyze, overview, or recap a group.
549
+ - intent="followUp" for follow-up questions about a previously analyzed group.
550
+ - intent="navigation" when the user asks to open, go to, navigate to, or view the group page.
551
+ - intent="clarify" when intent or required group target is missing.
552
+ - groupId must be the final resolved group id.
553
+ - If request has explicit group id, set groupId directly.
554
+ - If request references group title (for example $title, $"title with spaces", or plain quoted group title), call resolvePortalGroupIdByTitle and set groupId to the tool result.
555
+ - Never return group titles in output fields.
556
+ - If intent is "followUp", set question to the user's full question/request text.
557
+ - If intent is "navigation", set question="".
558
+ - If intent is "summarize", set question="".
559
+ - If intent is "navigation" and no group is specified, leave groupId empty so the system can navigate to the groups listing page.
560
+ - If hasAnalyticsContext is true and the user asks about the same group context without an explicit summarize/analyze command, prefer "followUp".
561
+
562
+ Examples:
563
+ - "Analyze group 0123456789abcdef0123456789abcdef" => summarize, groupId="0123456789abcdef0123456789abcdef"
564
+ - "Analyze group $living atlas" => summarize, call resolvePortalGroupIdByTitle("living atlas") and set groupId to tool result
565
+ - "Analyze group $"living atlas basemaps"" => summarize, call resolvePortalGroupIdByTitle("living atlas basemaps") and set groupId to tool result
566
+ - "Is this group active?" with hasAnalyticsContext=true => followUp
567
+
568
+ hasAnalyticsContext:
569
+ {hasAnalyticsContext}
570
+
571
+ User message:
572
+ {userMessage}
573
+ `,Dx=async(t,e)=>{let r=va(t),n=t.groupSummaryGroupId??r.latestGroupId;return await ge({text:"Preparing navigation...",agentName:"group-analytics"},e),await il(n?{destinationType:"portal-group",groupId:n}:{destinationType:"portal-groups"},e),{status:"success"}};function Up({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var Fx=720*60*60*1e3;function qx(t){let e=Wl(t);return{id:t.id??"",title:t.title??"",description:t.description??"",snippet:t.snippet??"",access:t.access??null,owner:t.owner??"",tags:t.tags??[],created:t.created?.getTime(),modified:t.modified?.getTime(),isInvitationOnly:t.isInvitationOnly,sourceSignals:{capabilities:Vl(t),membershipAccess:Hl(t),isOpenData:Jl(t),isDistributedCollaborationGroup:Zl(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function Ux(t){let e={owner:t.owner??"",admins:[],users:[]};try{return await t.fetchMembers()}catch(r){return console.warn("Unable to fetch group members for analytics context",r),e}}function Bx(t){return t.map(e=>({id:e.id??"",title:e.title??"Untitled",type:e.type??"Unknown",owner:e.owner??"",created:e.created?.getTime(),modified:e.modified?.getTime()}))}function Kx(t,e){return t.filter(r=>r.modified?Up({timestamp:r.modified,now:e,windowMs:Fx}):!1)}function Gx(t){let e=new Map;for(let r of t)e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].sort((r,n)=>n[1]-r[1]||r[0].localeCompare(n[0])).slice(0,6).map(([r,n])=>({type:r,count:n}))}async function Wx(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=Bx(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:Kx(r,n),topItemTypes:Gx(r)}}async function Vx(t,e){if(!e)return{error:{code:"missingGroupId",message:"Group id is required."}};try{let r=(await t.queryGroups({query:`id:${e}`,num:1})).results[0];if(!r)return{error:{code:"groupNotFound",message:`No group found for id: ${e}`}};let n=qx(r),o=await Ux(r),s=await Wx(r);return{result:{group:n,members:o,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var Hx=2160*60*60*1e3,Jx=async(t,e)=>{let r=t.groupSummaryGroupId;if(!r)return{status:"success",outputMessage:'Please clarify with analyze group <group id>, analyze group $<title>, or analyze group $"<title with spaces>".'};await ge({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let n=e?.configurable?.context;Pr(n);let{result:o,error:s}=await Vx(n.portal,r);if(s||!o)return await ge({text:"Failed to fetch group context",agentName:"group-analytics"},e),{status:"success",outputMessage:"Unable to retrieve group context for analytics."};let{group:a,items:i}=o,u=Date.now(),l=a.modified,c=l?Up({timestamp:l,now:u,windowMs:Hx}):!1,p=i.recentlyModifiedItems.length,m=p>0,h=c||m,y=await gt({promptText:Qx,schema:Zx,modelTier:"default",inputVariables:{context:JSON.stringify(o),deterministicSignals:JSON.stringify({isGroupActive:h,isGroupRecentlyModified:c,hasRecentlyAddedOrUpdatedContent:m,recentItemCount:p})}}),{followUpQuestions:A,summary:C}=y,g=va(t),b={latestGroupId:r,memory:{...g.memory,[r]:{summary:C,followUpQuestions:A,fullContext:o}}};return A.length&&await Aa({type:"suggested-prompts",data:{prompts:A}},e),{status:"success",outputMessage:C,sharedStatePatch:{portalGroupSummaryMemory:{value:b}}}},Zx=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Qx=`
574
+ You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
575
+
576
+ ${qp}
577
+
578
+ Output format requirements:
579
+ - Return concise markdown with clear sections in this order:
580
+ 1) Overview
581
+ 2) Activity
582
+ 3) Members
583
+ 4) Content Theme
584
+ 5) Contribution Model
585
+ 6) Unknowns / Data Gaps
586
+ - Keep total response about 180-280 words unless the user asked for extra detail.
587
+ - Avoid internal-only implementation details and do not expose raw IDs unless user explicitly asks.
588
+
589
+ Reasoning rules:
590
+ - Use deterministicSignals as the source of truth for active/recent status.
591
+ - If group description/snippet are empty, infer purpose from tags, item title patterns, and item type distribution.
592
+ - For members, report owner/admin/user counts when available; if unavailable due to permission scope, explicitly say so.
593
+ - For contribution model, use membershipAccess, capabilities, and sourceJSON flags to characterize collaboration vs distribution behavior.
594
+ - Be explicit when signals are heuristic or unavailable.
595
+
596
+ Follow-up prompt rules:
597
+ - Generate exactly 3 follow-up prompts.
598
+ - Write them as direct first-person user chat prompts that can be clicked and sent as-is.
599
+ - Do not write meta-questions such as "Would you like..." or "Do you want me to...".
600
+ - Keep each prompt short, specific, and actionable.
601
+ - Every prompt must be answerable using only the provided group context and deterministic signals.
602
+ - Do not require external data, navigation, or additional fetches.
603
+ - Tailor each prompt to this specific group's available signals (content mix, activity, members, and contribution model).
604
+ - Avoid repeating phrasing from prior prompts or using generic template wording.
605
+ - If a signal is unavailable (for example members), do not ask follow-ups that depend on that missing signal.
606
+
607
+ Group context:
608
+ {context}
609
+
610
+ Deterministic signals:
611
+ {deterministicSignals}
612
+ `,ol=(t,e)=>e??t,Bp=O.Root({...Yo(),groupSummaryIntent:O({reducer:ol,default:()=>"clarify"}),groupSummaryGroupId:O({reducer:ol,default:()=>null}),groupSummaryQuestion:O({reducer:ol,default:()=>""})}),Yx=()=>new de(Bp).addNode("detectGroupSummaryIntent",jx).addNode("summarizePortalGroup",Jx).addNode("answerGroupSummaryFollowUp",Rx).addNode("suggestGroupSummaryNavigation",Dx).addEdge(ue,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":q).addEdge("summarizePortalGroup",q).addEdge("answerGroupSummaryFollowUp",q).addEdge("suggestGroupSummaryNavigation",q),Xx=String.raw`- **portal-group-analytics** - Portal group analytics assistant:
613
+ - summarizes ArcGIS portal groups from group context and sourceJSON details
614
+ - answers follow-up questions grounded in the summarized group
615
+ - suggests navigation to groups when relevant
616
+ `,eA={id:"portal-group-analytics",name:"Portal Group Analytics",description:Xx,createGraph:Yx,workspace:Bp},tA=ul`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`,rA=(t,e)=>{let{destinationType:r}=t,n=`${e.url}/home`;switch(r){case"portal-content":return`${n}/content.html`;case"portal-groups":return`${n}/groups.html`;case"portal-item":return`${n}/item.html?id=${t.itemId}`;case"portal-group":return`${n}/group.html?id=${t.groupId}`;default:return uo(r)}},sl=class extends pl{constructor(){super(...arguments),this.t9n=fl({blocking:!0}),this.assistantEl=io(),this.formEl=io(),this.voiceInputEl=io(),this.inputEl=io(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=dl()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,defaultClosed:5}}static{this.styles=tA}getNavigationAction(e){if(e?.type!==jp)return;let r=fx(e.data);if(!r)return;let n=rA(r,this.portal);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),cl(Rr`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?Rr`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-groups":return r.openGroups;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return uo(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,showVoiceInput:s,isListening:a,isVoiceInputDisabled:i}=this;return Rr`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:u})=>{this.interrupt=u}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:u})=>{this.inputText=u.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${lo(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${u=>{u.preventDefault();let l=r.trim();l&&(this.assistantEl.value?.submitMessage(l),this.inputText="")}} ${lo(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:u})=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:u})=>{this.inputText=u??""}} ${lo(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${u=>{u.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${u=>{this.inputText=u.detail.text}} ${lo(this.voiceInputEl)}></arcgis-portal-voice-input>${s&&Rr`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${i} .appearance=${a?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let u=this.voiceInputEl.value;a?await u?.stopListening():await u?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${ex} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${wx} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Ox} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${eA} .context=${{portal:n,user:o}}></arcgis-assistant-agent>${this.interrupt&&Rr`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:u})=>{this.assistantEl.value?.submitInterrupt(u)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};ml("arcgis-portal-ai-assistant",sl);return sl},"identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","request",a)