@arcgis/portal-components 5.2.0-next.53 → 5.2.0-next.55

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.
@@ -0,0 +1,619 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a as ml,b as fl,d as hl,e as gl,f as yl}from"./6AGZRMJC.js";import c from"./LDCSQHZX.js";import b from"./AWIVXH7M.js";import"./6D3PU4ZT.js";import a from"./DALGPO36.js";import{a as Gn,b as Ui,d as qi}from"./2GBRZSEC.js";import{a as Bi}from"./OFDH6CTA.js";import"./BUKOHPY6.js";import"./XQJNAQVO.js";import{K as Bn,L as Kn,M as Di,S as Fi,h as Ni,j as pr,n as zi,w as ji,z as Li}from"./STZRXY35.js";import{$ as Ji,Aa as Ko,Ba as Go,Bb as Wo,Ca as al,Cb as Vo,Da as fr,Db as pe,Ea as hr,Fa as v,Ga as $,Ha as aa,J as Gi,K as De,L as Wi,M as No,N as Xs,O as ea,P as zo,Q as Wn,R as U,Ra as O,S as ta,T as D,U as et,V as tt,W as jo,X as Vi,Y as Hi,Z as ra,_ as Lo,a as de,aa as Zi,b as B,ba as Vn,ca as Do,da as Qi,ea as Yi,fa as Xi,g as Ki,ga as Fo,ha as el,ia as Tt,j as Le,ja as na,k as vt,ka as Uo,kb as il,la as N,ma as A,na as St,oa as rt,pa as qo,qa as tl,ra as rl,s as Ro,sa as Bo,ta as oa,ua as mr,va as sa,wa as nl,xa as ol,xb as Hn,y as $o,za as sl}from"./IZOGASBD.js";import"./UZLQALHY.js";export default $arcgis.t(([PK,MK,ad,qh,Bh,ng,LK,FK,ZV,kb,wd,ur,fi,Sd,,bd,ig,{addressToLocations:lg},ug,cg,kd,{createRenderer:dg},{getSchemesByTag:pg,getSchemes:mg},{getBackgroundColorTheme:xd},{createAgeRenderer:fg,createContinuousRenderer:hg},{getSchemesByTag:vi},{createContinuousRenderer:gg},{createRenderer:yg},{getSchemesByTag:_g},{createRenderer:wg},{getSchemesByTag:bg},{createRenderer:xg},{getSchemesByTag:Ag},{createRenderer:Ig},{getSchemesByTag:vg},{createAgeRenderer:Tg,createContinuousRenderer:Sg},{createRenderer:kg},{getSchemesByTag:Cg},Eg,Cd,Ed,{formatDateOnly:Pg,convertDateFormatToIntlOptions:Ds,formatTimeOnly:Og,formatDate:Ad},Mg,Rg,$g,Ng,zg,Pd,,{fetchKnowledgeGraph:Id,executeQueryStreaming:jg,executeSearchStreaming:Lg},Dg,{getBindParametersFromCypherQuery:Fg},,,,,,,,,,,,,,,,,,,,,,,,,ZW,YW,,,,,,,,,,,,,Cb,Bd,,{a:dl,b:pl},{a:ll,b:ul,c:cl}])=>{var c=v;async function ia(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
+
4
+ If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
+
6
+ Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
7
+ |`,`
8
+ \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
9
+ `].join(" "));let n=await Zi(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var H=async(t,e)=>{await ia("trace_message",t,e)},me=async(t,e)=>{await ia("graph_ux_suggestion",t,e)};var pp={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"}},lA=Object.keys(pp);var ca=Symbol.for("langgraph-zod");ca in globalThis||(globalThis[ca]=new WeakSet);function bl(t){let e=globalThis[ca];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return Vo(r,{jsonSchemaExtra:n})},reducer(n,o){return Vo(r,{default:Uo(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{bl(A.ZodType.prototype),bl(v.ZodType.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var xl=class extends Yi{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=Uo(t);n!=null&&(r.default=n)}return super.add(t,...e)}},gp=new xl(Wo);var Mp=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Rp=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),$p=["approve","edit","reject"],Np=A.enum($p),zp=A.object({allowedDecisions:A.array(Np),description:A.union([A.string(),Rp]).optional(),argsSchema:A.record(A.any()).optional(),when:Mp.optional()}),yT=A.object({interruptOn:A.record(A.union([A.boolean(),zp])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var Dp=`<role>
10
+ Context Extraction Assistant
11
+ </role>
12
+
13
+ <primary_objective>
14
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
15
+ </primary_objective>
16
+
17
+ <objective_information>
18
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
19
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
20
+ </objective_information>
21
+
22
+ <instructions>
23
+ The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
24
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
25
+ </instructions>
26
+
27
+ The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
28
+
29
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
30
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
31
+
32
+ <messages>
33
+ Messages to summarize:
34
+ {messages}
35
+ </messages>`;var Fp=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),ga=A.object({fraction:A.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().positive("Tokens must be greater than 0").optional(),messages:A.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Pl=A.object({fraction:A.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:A.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),NT=A.object({model:A.custom(),trigger:A.union([ga,A.array(ga)]).optional(),keep:Pl.optional(),tokenCounter:Fp.optional(),summaryPrompt:A.string().default(Dp),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var WT=A.object({model:A.string().or(A.instanceof(tl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var XT=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var oS=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Up=["continue","error","end"],qp="continue";var Bp=A.enum(Up).default(qp);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Bp});var hS=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Kp=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Gp=A.object({content:A.string().describe("Content of the todo item"),status:Kp}),IS=A.object({todos:A.array(Gp).default([])});var CS=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),ES=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var Ho=A.object({maxRetries:A.number().min(0).default(2),retryOn:A.union([A.function().args(A.instanceof(Error)).returns(A.boolean()),A.array(A.custom())]).default(()=>()=>!0),backoffFactor:A.number().min(0).default(2),initialDelayMs:A.number().min(0).default(1e3),maxDelayMs:A.number().min(0).default(6e4),jitter:A.boolean().default(!0)});var BS=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(Ho);var QS=A.object({tools:A.array(A.union([A.custom(),A.custom(),A.string()])).optional(),onFailure:A.union([A.literal("error"),A.literal("continue"),A.literal("raise"),A.literal("return_message"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(Ho);var pk=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var gk=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function Jn(t,e){return t.lc_error_code=e,t.message=`${t.message}
36
+
37
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
38
+ `,t}function C(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 ya=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return ya=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 Zn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Qn=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var k=class extends Error{},G=class t extends k{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new ot({message:n,cause:Qn(r)});let s=r?.error;return e===400?new yr(e,s,n,o):e===401?new _r(e,s,n,o):e===403?new wr(e,s,n,o):e===404?new br(e,s,n,o):e===409?new xr(e,s,n,o):e===422?new Ar(e,s,n,o):e===429?new Ir(e,s,n,o):e>=500?new vr(e,s,n,o):new t(e,s,n,o)}},W=class extends G{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ot=class extends G{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ee=class extends ot{constructor({message:e}={}){super({message:e??"Request timed out."})}},yr=class extends G{},_r=class extends G{},wr=class extends G{},br=class extends G{},xr=class extends G{},Ar=class extends G{},Ir=class extends G{},vr=class extends G{},Tr=class extends k{constructor(){super("Could not parse response content as the length limit was reached")}},Sr=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Pe=class extends Error{constructor(e){super(e)}},Ct=class extends G{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}},Yn=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var tm=/^[a-z][a-z0-9+.-]*:/i,Ol=t=>tm.test(t),ie=t=>(ie=Array.isArray,ie(t)),_a=ie;function Jo(t){return typeof t!="object"?{}:t??{}}function wa(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ml(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Xn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Rl=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e};var $l=t=>{try{return JSON.parse(t)}catch{return}};var Oe=t=>new Promise(e=>setTimeout(e,t));var st="6.45.0";var Ll=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function rm(){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 nm=()=>{let t=rm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"X-Stainless-OS":zl(Deno.build.os),"X-Stainless-Arch":Nl(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":st,"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":st,"X-Stainless-OS":zl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=om();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"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":st,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function om(){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 Nl=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",zl=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"),jl,Dl=()=>jl??(jl=nm());function Zo(){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 ba(...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 Qo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return ba({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function xa(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 Aa(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 Ul=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ia="RFC3986",va=t=>String(t),Ta={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:va},ql="RFC1738";var Yo=(t,e)=>(Yo=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Yo(t,e)),Me=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Sa=1024,Bl=(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+=Sa){let u=s.length>=Sa?s.slice(i,i+Sa):s,l=[];for(let d=0;d<u.length;++d){let m=u.charCodeAt(d);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===ql&&(m===40||m===41)){l[l.length]=u.charAt(d);continue}if(m<128){l[l.length]=Me[m];continue}if(m<2048){l[l.length]=Me[192|m>>6]+Me[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Me[224|m>>12]+Me[128|m>>6&63]+Me[128|m&63];continue}d+=1,m=65536+((m&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Me[240|m>>18]+Me[128|m>>12&63]+Me[128|m>>6&63]+Me[128|m&63]}a+=l.join("")}return a};function Kl(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ka(t,e){if(ie(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Wl={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Vl=function(t,e){Array.prototype.push.apply(t,ie(e)?e:[e])},Gl,X={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Bl,encodeValuesOnly:!1,format:Ia,formatter:va,indices:!1,serializeDate(t){return(Gl??(Gl=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function am(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Ca={};function Hl(t,e,r,n,o,s,a,i,u,l,d,m,f,I,w,b,y,h){let x=t,S=h,E=0,F=!1;for(;(S=S.get(Ca))!==void 0&&!F;){let Z=S.get(t);if(E+=1,typeof Z<"u"){if(Z===E)throw new RangeError("Cyclic object value");F=!0}typeof S.get(Ca)>"u"&&(E=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&ie(x)&&(x=ka(x,function(Z){return Z instanceof Date?f?.(Z):Z})),x===null){if(s)return u&&!b?u(e,X.encoder,y,"key",I):e;x=""}if(am(x)||Kl(x)){if(u){let Z=b?e:u(e,X.encoder,y,"key",I);return[w?.(Z)+"="+w?.(u(x,X.encoder,y,"value",I))]}return[w?.(e)+"="+w?.(String(x))]}let q=[];if(typeof x>"u")return q;let K;if(r==="comma"&&ie(x))b&&u&&(x=ka(x,u)),K=[{value:x.length>0?x.join(",")||null:void 0}];else if(ie(l))K=l;else{let Z=Object.keys(x);K=d?Z.sort(d):Z}let V=i?String(e).replace(/\./g,"%2E"):String(e),ae=n&&ie(x)&&x.length===1?V+"[]":V;if(o&&ie(x)&&x.length===0)return ae+"[]";for(let Z=0;Z<K.length;++Z){let Y=K[Z],Ri=typeof Y=="object"&&typeof Y.value<"u"?Y.value:x[Y];if(a&&Ri===null)continue;let Ys=m&&i?Y.replace(/\./g,"%2E"):Y,cp=ie(x)?typeof r=="function"?r(ae,Ys):ae:ae+(m?"."+Ys:"["+Ys+"]");h.set(t,E);let $i=new WeakMap;$i.set(Ca,h),Vl(q,Hl(Ri,cp,r,n,o,s,a,i,r==="comma"&&b&&ie(x)?null:u,l,d,m,f,I,w,b,y,$i))}return q}function im(t=X){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||X.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=Ia;if(typeof t.format<"u"){if(!Yo(Ta,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Ta[r],o=X.filter;(typeof t.filter=="function"||ie(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Wl?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=X.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:X.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:X.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:X.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:X.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?X.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:X.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:X.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:X.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:X.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:X.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:X.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:X.strictNullHandling}}function Jl(t,e={}){let r=t,n=im(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ie(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=Wl[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let f=0;f<o.length;++f){let I=o[f];n.skipNulls&&r[I]===null||Vl(a,Hl(r[I],I,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 d=a.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),d.length>0?m+d:""}function Zl(t){return Jl(t,{arrayFormat:"brackets"})}function Xl(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 Ql;function kr(t){let e;return(Ql??(e=new globalThis.TextEncoder,Ql=e.encode.bind(e)))(t)}var Yl;function Ea(t){let e;return(Yl??(e=new globalThis.TextDecoder,Yl=e.decode.bind(e)))(t)}var he,ge,Et=class{constructor(){he.set(this,void 0),ge.set(this,void 0),C(this,he,new Uint8Array,"f"),C(this,ge,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kr(e):e;C(this,he,Xl([_(this,he,"f"),r]),"f");let n=[],o;for(;(o=um(_(this,he,"f"),_(this,ge,"f")))!=null;){if(o.carriage&&_(this,ge,"f")==null){C(this,ge,o.index,"f");continue}if(_(this,ge,"f")!=null&&(o.index!==_(this,ge,"f")+1||o.carriage)){n.push(Ea(_(this,he,"f").subarray(0,_(this,ge,"f")-1))),C(this,he,_(this,he,"f").subarray(_(this,ge,"f")),"f"),C(this,ge,null,"f");continue}let s=_(this,ge,"f")!==null?o.preceding-1:o.preceding,a=Ea(_(this,he,"f").subarray(0,s));n.push(a),C(this,he,_(this,he,"f").subarray(o.index),"f"),C(this,ge,null,"f")}return n}flush(){return _(this,he,"f").length?this.decode(`
39
+ `):[]}};he=new WeakMap,ge=new WeakMap;Et.NEWLINE_CHARS=new Set([`
40
+ `,"\r"]);Et.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function um(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 eu(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 es={off:0,error:200,warn:300,info:400,debug:500},Pa=(t,e,r)=>{if(t){if(Ml(es,t))return t;J(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(es))}`)}};function eo(){}function Xo(t,e,r){return!e||es[t]>es[r]?eo:e[t].bind(e)}var cm={error:eo,warn:eo,info:eo,debug:eo},tu=new WeakMap;function J(t){let e=t.logger,r=t.logLevel??"off";if(!e)return cm;let n=tu.get(e);if(n&&n[0]===r)return n[1];let o={error:Xo("error",e,r),warn:Xo("warn",e,r),info:Xo("info",e,r),debug:Xo("debug",e,r)};return tu.set(e,[r,o]),o}var Fe=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var to,Re=class t{constructor(e,r,n){this.iterator=e,to.set(this,void 0),this.controller=r,C(this,to,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,a=n?J(n):console;async function*i(){if(s)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of dm(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let d;try{d=JSON.parse(l.data)}catch(m){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),m}if(d&&d.error)throw new G(void 0,d.error,void 0,e.headers);yield o?{event:l.event,data:d}:d}else{let d;try{d=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new G(void 0,d.error,d.message,void 0);yield{event:l.event,data:d}}}u=!0}catch(l){if(Zn(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 Et,u=xa(e);for await(let l of u)for(let d of i.decode(l))yield d;for(let l of i.flush())yield l}async function*a(){if(o)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(Zn(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,_(this,to,"f")),new t(()=>o(r),this.controller,_(this,to,"f"))]}toReadableStream(){let e=this,r;return ba({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=kr(JSON.stringify(o)+`
41
+ `);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 k("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new k("Attempted to iterate over a response with no body");let r=new Oa,n=new Et,o=xa(t.body);for await(let s of pm(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*pm(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"?kr(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=eu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Oa=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
42
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=mm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function mm(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 J(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):Re.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 f=await r.json();return Ma(f,r)}return await r.text()})();return J(t).debug(`[${n}] response parsed`,Fe({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function Ma(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 ro,Pt=class t extends Promise{constructor(e,r,n=ts){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,ro.set(this,void 0),C(this,ro,e,"f")}_thenUnwrap(e){return new t(_(this,ro,"f"),this.responsePromise,async(r,n)=>Ma(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,ro,"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)}};ro=new WeakMap;var rs,Cr=class{constructor(e,r,n,o){rs.set(this,void 0),C(this,rs,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,rs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(rs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},no=class extends Pt{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}},le=class extends Cr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Cr{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:{...Jo(this.options.query),after:r}}:null}},j=class extends Cr{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:{...Jo(this.options.query),after:e}}:null}},Q=class extends Cr{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:{...Jo(this.options.query),after:e}}:null}};var hm={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},gm="urn:ietf:params:oauth:grant-type:token-exchange",ns=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Zo()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r={grant_type:gm,subject_token:e,subject_token_type:hm[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let u=await n.text(),l;try{l=JSON.parse(u)}catch{}throw n.status===400||n.status===401||n.status===403?new Ct(n.status,l,n.headers):G.generate(n.status,l,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new k("Token exchange response missing 'access_token' field");let s=o.access_token,a=o.expires_in??3600,i=Date.now()+a*1e3;return this.cachedToken={token:s,expiresAt:i},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Na=()=>{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 Er(t,e,r){return Na(),new File(t,e??"unknown_file",r)}function oo(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 os=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",at=async(t,e)=>Ra(t.body)?{...t,body:await nu(t.body,e)}:t,ue=async(t,e)=>({...t,body:await nu(t.body,e)}),ru=new WeakMap;function ym(t){let e=typeof t=="function"?t:t.fetch,r=ru.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 ru.set(e,n),n}var nu=async(t,e)=>{if(!await ym(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])=>$a(r,n,o))),r},ou=t=>t instanceof Blob&&"name"in t,_m=t=>typeof t=="object"&&t!==null&&(t instanceof Response||os(t)||ou(t)),Ra=t=>{if(_m(t))return!0;if(Array.isArray(t))return t.some(Ra);if(t&&typeof t=="object"){for(let e in t)if(Ra(t[e]))return!0}return!1},$a=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,Er([await r.blob()],oo(r)));else if(os(r))t.append(e,Er([await new Response(Qo(r)).blob()],oo(r)));else if(ou(r))t.append(e,r,oo(r));else if(Array.isArray(r))await Promise.all(r.map(n=>$a(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>$a(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 su=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",wm=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&su(t),bm=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function so(t,e,r){if(Na(),t=await t,wm(t))return t instanceof File?t:Er([await t.arrayBuffer()],t.name);if(bm(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Er(await za(o),e,r)}let n=await za(t);if(e||(e=oo(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Er(n,e,r)}async function za(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(su(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(os(t))for await(let r of t)e.push(...await za(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${xm(t)}`)}return e}function xm(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function iu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var au=Object.freeze(Object.create(null)),Im=(t=iu)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],a=r.reduce((d,m,f)=>{/[?#]/.test(m)&&(o=!0);let I=n[f],w=(o?encodeURIComponent:t)(""+I);return f!==n.length&&(I==null||typeof I=="object"&&I.toString===Object.getPrototypeOf(Object.getPrototypeOf(I.hasOwnProperty??au)??au)?.toString)&&(w=I+"",s.push({start:d.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(I).slice(8,-1)} is not a valid path parameter`})),d+m+(f===n.length?"":w)},""),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((d,m)=>d.start-m.start),s.length>0){let d=0,m=s.reduce((f,I)=>{let w=" ".repeat(I.start-d),b="^".repeat(I.length);return d=I.start+I.length,f+w+b},"");throw new k(`Path parameters result in path with invalid segments:
43
+ ${s.map(f=>f.error).join(`
44
+ `)}
45
+ ${a}
46
+ ${m}`)}return a},p=Im(iu);var Ot=class extends g{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function ao(t){return t!==void 0&&"function"in t&&t.function!==void 0}function uu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function io(t){return t?.$brand==="auto-parseable-response-format"}function Mt(t){return t?.$brand==="auto-parseable-tool"}function cu(t,e){return!e||!ja(e)?{...t,choices:t.choices.map(r=>(pu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:lo(t,e)}function lo(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Tr;if(n.finish_reason==="content_filter")throw new Sr;return pu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Sm(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Tm(e,n.message.content):null}}});return{...t,choices:r}}function Tm(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 Sm(t,e){let r=t.tools?.find(n=>ao(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Mt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function du(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>ao(n)&&n.function?.name===e.function.name);return ao(r)&&(Mt(r)||r?.function.strict||!1)}function ja(t){return io(t.response_format)?!0:t.tools?.some(e=>Mt(e)||e.type==="function"&&e.function.strict===!0)??!1}function pu(t){for(let e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function mu(t){for(let e of t??[]){if(e.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new k(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Pr=t=>t?.role==="assistant",La=t=>t?.role==="tool";var ss,as,is,uo,co,ls,po,Ue,us,mo,cs,ds,Or,fu,hu,it=class{constructor(){ss.add(this),this.controller=new AbortController,as.set(this,void 0),is.set(this,()=>{}),uo.set(this,()=>{}),co.set(this,void 0),ls.set(this,()=>{}),po.set(this,()=>{}),Ue.set(this,{}),us.set(this,[]),mo.set(this,!1),cs.set(this,!1),ds.set(this,!1),Or.set(this,!1),C(this,as,new Promise((e,r)=>{C(this,is,e,"f"),C(this,uo,r,"f")}),"f"),C(this,co,new Promise((e,r)=>{C(this,ls,e,"f"),C(this,po,r,"f")}),"f"),_(this,as,"f").catch(()=>{}),_(this,co,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,ss,"m",hu).bind(this))},0)}_connected(){this.ended||(_(this,is,"f").call(this),this._emit("connect"))}get ended(){return _(this,mo,"f")}get errored(){return _(this,cs,"f")}get aborted(){return _(this,ds,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),_(this,us,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ue,"f")[e]||(_(this,Ue,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,Ue,"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,Ue,"f")[e]||(_(this,Ue,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{C(this,Or,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){C(this,Or,!0,"f"),await _(this,co,"f")}_emit(e,...r){if(_(this,mo,"f"))return;e==="end"&&(_(this,ss,"m",fu).call(this),C(this,mo,!0,"f"),_(this,ls,"f").call(this));let n=_(this,Ue,"f")[e];if(n&&(_(this,Ue,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,Or,"f")&&!n?.length&&Promise.reject(o),_(this,uo,"f").call(this,o),_(this,po,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Or,"f")&&!n?.length&&Promise.reject(o),_(this,uo,"f").call(this,o),_(this,po,"f").call(this,o),this._emit("end")}}_emitFinal(){}};as=new WeakMap,is=new WeakMap,uo=new WeakMap,co=new WeakMap,ls=new WeakMap,po=new WeakMap,Ue=new WeakMap,us=new WeakMap,mo=new WeakMap,cs=new WeakMap,ds=new WeakMap,Or=new WeakMap,ss=new WeakSet,fu=function(){for(let{signal:e,listener:r}of _(this,us,"f").splice(0))e.removeEventListener("abort",r)},hu=function(e){if(C(this,cs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new W),e instanceof W)return C(this,ds,!0,"f"),this._emit("abort",e);if(e instanceof k)return this._emit("error",e);if(e instanceof Error){let r=new k(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new k(String(e)))};function gu(t){return typeof t.parse=="function"}var fe,Da,ps,Fa,Ua,qa,yu,_u,km=10,Mr=class extends it{constructor(){super(...arguments),fe.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),La(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Pr(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new k("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,fe,"m",Da).call(this)}async finalMessage(){return await this.done(),_(this,fe,"m",ps).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,fe,"m",Fa).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,fe,"m",Ua).call(this)}async totalUsage(){return await this.done(),_(this,fe,"m",qa).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,fe,"m",ps).call(this);r&&this._emit("finalMessage",r);let n=_(this,fe,"m",Da).call(this);n&&this._emit("finalContent",n);let o=_(this,fe,"m",Fa).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,fe,"m",Ua).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,fe,"m",qa).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),_(this,fe,"m",yu).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(lo(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=km,afterCompletion:m}=o||{},f=r.tools.map(y=>{if(Mt(y)){if(!y.$callback)throw new k("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),I={};for(let y of f)y.type==="function"&&(I[y.function.name||y.function.function.name]=y.function);let w="tools"in r?f.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(let y of r.messages)this._addMessage(y,!1);let b=async y=>{if(y.type!=="function")return{message:void 0,functionCalled:!1};let h=y.id,{name:x,arguments:S}=y.function,E=I[x];if(!E){let K=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(I).map(V=>JSON.stringify(V)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:h,content:K},functionCalled:!1}}if(l&&l!==x){let K=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:h,content:K},functionCalled:!1}}let F;if(gu(E)){let K;try{K=await E.parse(S)}catch(V){let ae=V instanceof Error?V.message:String(V);return{message:{role:s,tool_call_id:h,content:ae},functionCalled:!1}}F=await E.function(K,n)}else F=await E.function(S,n);let q=_(this,fe,"m",_u).call(this,F);return{message:{role:s,tool_call_id:h,content:q},functionCalled:!0}};for(let y=0;y<d;++y){let h=await this._createChatCompletion(e,{...u,tool_choice:a,tools:w,messages:[...this.messages]},o),x=h.choices[0]?.message;if(!x)throw new k("missing message in ChatCompletion response");if(!x.tool_calls?.length){await m?.(h,n);return}if(l||r.parallel_tool_calls===!1)for(let S of x.tool_calls){let E=await b(S);if(E.message&&this._addMessage(E.message),l&&E.functionCalled){await m?.(h,n);return}}else{let S=await Promise.allSettled(x.tool_calls.map(b));for(let E of S)if(E.status==="rejected")throw E.reason;for(let E of S)E.status==="fulfilled"&&E.value.message&&this._addMessage(E.value.message)}await m?.(h,n)}}};fe=new WeakSet,Da=function(){return _(this,fe,"m",ps).call(this).content??null},ps=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Pr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},Fa=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Pr(r)&&r?.tool_calls?.length)for(let n=r.tool_calls.length-1;n>=0;n--){let o=r.tool_calls[n];if(o?.type==="function")return o.function}}},Ua=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(La(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}},qa=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},yu=function(e){if(e.n!=null&&e.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_u=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var fo=class t extends Mr{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),Pr(e)&&e.content&&this._emit("content",e.content)}};var re={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},Ba=class extends Error{},Ka=class extends Error{};function Cm(t,e=re.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Em(t.trim(),e)}var Em=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Ba(`${f} at position ${n}`)},s=f=>{throw new Ka(`${f} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||re.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||re.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||re.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||re.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||re.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||re.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):d()),i=()=>{let f=n,I=!1;for(n++;n<r&&(t[n]!=='"'||I&&t[n-1]==="\\");)I=t[n]==="\\"?!I:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(I)))}catch(w){s(String(w))}else if(re.STR&e)try{return JSON.parse(t.substring(f,n-Number(I))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&re.OBJ&e)return f;let I=i();m(),n++;try{let w=a();Object.defineProperty(f,I,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(re.OBJ&e)return f;throw w}m(),t[n]===","&&n++}}catch{if(re.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(a()),m(),t[n]===","&&n++}catch{if(re.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},d=()=>{if(n===0){t==="-"&&re.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(I){if(re.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(I))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(re.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&re.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},m=()=>{for(;n<r&&`
47
+ \r `.includes(t[n]);)n++};return a()},Ga=t=>Cm(t,re.ALL^re.NUM);var ee,qe,Rr,lt,Wa,ms,Va,Ha,Ja,fs,Za,wu,Rt=class t extends Mr{constructor(e){super(),ee.add(this),qe.set(this,void 0),Rr.set(this,void 0),lt.set(this,void 0),C(this,qe,e,"f"),C(this,Rr,[],"f")}get currentChatCompletionSnapshot(){return _(this,lt,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion,this._listenForAbort(n?.signal),_(this,ee,"m",Wa).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)_(this,ee,"m",Va).call(this,s);if(o.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,ee,"m",fs).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,ee,"m",Wa).call(this),this._connected();let n=Re.fromReadableStream(e,this.controller),o;for await(let s of n)o&&o!==s.id&&this._addChatCompletion(_(this,ee,"m",fs).call(this)),_(this,ee,"m",Va).call(this,s),o=s.id;if(n.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,ee,"m",fs).call(this))}[(qe=new WeakMap,Rr=new WeakMap,lt=new WeakMap,ee=new WeakSet,Wa=function(){this.ended||C(this,lt,void 0,"f")},ms=function(r){let n=_(this,Rr,"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,Rr,"f")[r.index]=n,n)},Va=function(r){if(this.ended)return;let n=_(this,ee,"m",wu).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,ee,"m",ms).call(this,s);s.finish_reason&&(_(this,ee,"m",Ja).call(this,s),a.current_tool_call_index!=null&&_(this,ee,"m",Ha).call(this,s,a.current_tool_call_index));for(let i of o.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(_(this,ee,"m",Ja).call(this,s),a.current_tool_call_index!=null&&_(this,ee,"m",Ha).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))}}},Ha=function(r,n){if(_(this,ee,"m",ms).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,qe,"f")?.tools?.find(i=>ao(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:Mt(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},Ja=function(r){let n=_(this,ee,"m",ms).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,ee,"m",Za).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}))},fs=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,lt,"f");if(!r)throw new k("request ended without sending any chunks");return C(this,lt,void 0,"f"),C(this,Rr,[],"f"),Pm(r,_(this,qe,"f"))},Za=function(){let r=_(this,qe,"f")?.response_format;return io(r)?r:null},wu=function(r){var n,o,s,a;let i=_(this,lt,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=C(this,lt,{...l,choices:[]},"f");for(let{delta:d,finish_reason:m,index:f,logprobs:I=null,...w}of r.choices){let b=i.choices[f];if(b||(b=i.choices[f]={finish_reason:m,index:f,message:{},logprobs:I,...w}),I)if(!b.logprobs)b.logprobs=Object.assign({},I);else{let{content:q,refusal:K,...V}=I;Object.assign(b.logprobs,V),q&&((n=b.logprobs).content??(n.content=[]),b.logprobs.content.push(...q)),K&&((o=b.logprobs).refusal??(o.refusal=[]),b.logprobs.refusal.push(...K))}if(m&&(b.finish_reason=m,_(this,qe,"f")&&ja(_(this,qe,"f")))){if(m==="length")throw new Tr;if(m==="content_filter")throw new Sr}if(Object.assign(b,w),!d)continue;let{content:y,refusal:h,function_call:x,role:S,tool_calls:E,...F}=d;if(Object.assign(b.message,F),h&&(b.message.refusal=(b.message.refusal||"")+h),S&&(b.message.role=S),x&&(b.message.function_call?(x.name&&(b.message.function_call.name=x.name),x.arguments&&((s=b.message.function_call).arguments??(s.arguments=""),b.message.function_call.arguments+=x.arguments)):b.message.function_call=x),y&&(b.message.content=(b.message.content||"")+y,!b.message.refusal&&_(this,ee,"m",Za).call(this)&&(b.message.parsed=b.message.content.trim()?Ga(b.message.content):null)),E){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:q,id:K,type:V,function:ae,...Z}of E){let Y=(a=b.message.tool_calls)[q]??(a[q]={});Object.assign(Y,Z),K&&(Y.id=K),V&&(Y.type=V),ae&&(Y.function??(Y.function={name:ae.name??"",arguments:""})),ae?.name&&(Y.function.name=ae.name),ae?.arguments&&(Y.function.arguments+=ae.arguments,du(_(this,qe,"f"),Y)&&(Y.function.parsed_arguments=Ga(Y.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 Re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Pm(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:d,index:m,logprobs:f,...I})=>{if(!d)throw new k(`missing finish_reason for choice ${m}`);let{content:w=null,function_call:b,tool_calls:y,...h}=l,x=l.role;if(!x)throw new k(`missing role for choice ${m}`);if(b){let{arguments:S,name:E}=b;if(S==null)throw new k(`missing function_call.arguments for choice ${m}`);if(!E)throw new k(`missing function_call.name for choice ${m}`);return{...I,message:{content:w,function_call:{arguments:S,name:E},role:x,refusal:l.refusal??null},finish_reason:d,index:m,logprobs:f}}return y?{...I,index:m,finish_reason:d,logprobs:f,message:{...h,role:x,content:w,refusal:l.refusal??null,tool_calls:y.map((S,E)=>{let{function:F,type:q,id:K,...V}=S,{arguments:ae,name:Z,...Y}=F||{};if(K==null)throw new k(`missing choices[${m}].tool_calls[${E}].id
48
+ ${hs(t)}`);if(q==null)throw new k(`missing choices[${m}].tool_calls[${E}].type
49
+ ${hs(t)}`);if(Z==null)throw new k(`missing choices[${m}].tool_calls[${E}].function.name
50
+ ${hs(t)}`);if(ae==null)throw new k(`missing choices[${m}].tool_calls[${E}].function.arguments
51
+ ${hs(t)}`);return{...V,id:K,type:q,function:{...Y,name:Z,arguments:ae}}})}}:{...I,message:{...h,content:w,role:x,refusal:l.refusal??null},finish_reason:d,index:m,logprobs:f}}),created:o,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return cu(u,e)}function hs(t){return JSON.stringify(t)}var ho=class t extends Rt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var Be=class extends g{constructor(){super(...arguments),this.messages=new Ot(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return mu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>lo(n,e))}runTools(e,r){return e.stream?ho.runTools(this._client,e,r):fo.runTools(this._client,e,r)}stream(e,r){return Rt.createChatCompletion(this._client,e,r)}};Be.Messages=Ot;var ut=class extends g{constructor(){super(...arguments),this.completions=new Be(this._client)}};ut.Completions=Be;var $r=class extends g{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",R,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Nr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var zr=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",le,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",le,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var jr=class extends g{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Lr=class extends g{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Dr=class extends g{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",Q,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Fr=class extends g{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=class extends g{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends g{create(e,r,n){return this._client.post(p`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends g{create(e,r,n){return this._client.post(p`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/users`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ct=class extends g{constructor(){super(...arguments),this.users=new Br(this._client),this.roles=new qr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",Q,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};ct.Users=Br;ct.Roles=qr;var Kr=class extends g{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/api_keys`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends g{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/activate`,le,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/deactivate`,le,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends g{create(e,r,n){return this._client.post(p`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/projects/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends g{create(e,r,n){return this._client.post(p`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/service_accounts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{create(e,r,n){return this._client.post(p`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/spend_alerts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,group_id:s}=r;return this._client.get(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/groups/${e}/roles`,Q,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var $t=class extends g{constructor(){super(...arguments),this.roles=new Xr(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(p`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/groups`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};$t.Roles=Xr;var en=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,user_id:s}=r;return this._client.get(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/users/${e}/roles`,Q,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Nt=class extends g{constructor(){super(...arguments),this.roles=new en(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/users`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Nt.Roles=en;var ne=class extends g{constructor(){super(...arguments),this.users=new Nt(this._client),this.serviceAccounts=new Qr(this._client),this.apiKeys=new Kr(this._client),this.rateLimits=new Jr(this._client),this.modelPermissions=new Hr(this._client),this.hostedToolPermissions=new Vr(this._client),this.groups=new $t(this._client),this.roles=new Zr(this._client),this.dataRetention=new Wr(this._client),this.spendAlerts=new Yr(this._client),this.certificates=new Gr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ne.Users=Nt;ne.ServiceAccounts=Qr;ne.APIKeys=Kr;ne.RateLimits=Jr;ne.ModelPermissions=Hr;ne.HostedToolPermissions=Vr;ne.Groups=$t;ne.Roles=Zr;ne.DataRetention=Wr;ne.SpendAlerts=Yr;ne.Certificates=Gr;var tn=class extends g{create(e,r,n){return this._client.post(p`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/users/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends g{constructor(){super(...arguments),this.roles=new tn(this._client)}retrieve(e,r){return this._client.get(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};zt.Roles=tn;var oe=class extends g{constructor(){super(...arguments),this.auditLogs=new Nr(this._client),this.adminAPIKeys=new $r(this._client),this.usage=new Ur(this._client),this.invites=new Lr(this._client),this.users=new zt(this._client),this.groups=new ct(this._client),this.roles=new Dr(this._client),this.dataRetention=new jr(this._client),this.spendAlerts=new Fr(this._client),this.certificates=new zr(this._client),this.projects=new ne(this._client)}};oe.AuditLogs=Nr;oe.AdminAPIKeys=$r;oe.Usage=Ur;oe.Invites=Lr;oe.Users=zt;oe.Groups=ct;oe.Roles=Dr;oe.DataRetention=jr;oe.SpendAlerts=Fr;oe.Certificates=zr;oe.Projects=ne;var dt=class extends g{constructor(){super(...arguments),this.organization=new oe(this._client)}};dt.Organization=oe;var bu=Symbol("brand.privateNullableHeaders");function*af(t){if(!t)return;if(bu 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():_a(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=_a(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 T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,a]of af(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{[bu]:!0,values:e,nulls:r}};var rn=class extends g{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:T([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var nn=class extends g{create(e,r){return this._client.post("/audio/transcriptions",ue({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var on=class extends g{create(e,r){return this._client.post("/audio/translations",ue({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var $e=class extends g{constructor(){super(...arguments),this.transcriptions=new nn(this._client),this.translations=new on(this._client),this.speech=new rn(this._client)}};$e.Transcriptions=nn;$e.Translations=on;$e.Speech=rn;var jt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var sn=class extends g{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/assistants/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var an=class extends g{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var ln=class extends g{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var pt=class extends g{constructor(){super(...arguments),this.sessions=new an(this._client),this.transcriptionSessions=new ln(this._client)}};pt.Sessions=an;pt.TranscriptionSessions=ln;var un=class extends g{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var cn=class extends g{retrieve(e,r){return this._client.get(p`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",j,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(p`/chatkit/threads/${e}/items`,j,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var mt=class extends g{constructor(){super(...arguments),this.sessions=new un(this._client),this.threads=new cn(this._client)}};mt.Sessions=un;mt.Threads=cn;var dn=class extends g{create(e,r,n){return this._client.post(p`/threads/${e}/messages`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/messages/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/messages`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var pn=class extends g{retrieve(e,r,n){let{thread_id:o,run_id:s,...a}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:a,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(p`/threads/${o}/runs/${e}/steps`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var xu=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 be=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 se,Dt,Qa,Ne,gs,xe,Ft,mn,Lt,ws,ye,ys,_s,_o,go,yo,Au,Iu,vu,Tu,Su,ku,Cu,Ke=class extends it{constructor(){super(...arguments),se.add(this),Qa.set(this,[]),Ne.set(this,{}),gs.set(this,{}),xe.set(this,void 0),Ft.set(this,void 0),mn.set(this,void 0),Lt.set(this,void 0),ws.set(this,void 0),ye.set(this,void 0),ys.set(this,void 0),_s.set(this,void 0),_o.set(this,void 0)}[(Qa=new WeakMap,Ne=new WeakMap,gs=new WeakMap,xe=new WeakMap,Ft=new WeakMap,mn=new WeakMap,Lt=new WeakMap,ws=new WeakMap,ye=new WeakMap,ys=new WeakMap,_s=new WeakMap,_o=new WeakMap,se=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 Dt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=Re.fromReadableStream(e,this.controller);for await(let o of n)_(this,se,"m",go).call(this,o);if(n.controller.signal?.aborted)throw new W;return this._addRun(_(this,se,"m",yo).call(this))}toReadableStream(){return new Re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Dt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)_(this,se,"m",go).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,se,"m",yo).call(this))}static createThreadAssistantStream(e,r,n){let o=new Dt;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 Dt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,ys,"f")}currentRun(){return _(this,_s,"f")}currentMessageSnapshot(){return _(this,xe,"f")}currentRunStepSnapshot(){return _(this,_o,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Ne,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,gs,"f"))}async finalRun(){if(await this.done(),!_(this,Ft,"f"))throw Error("Final run was not received.");return _(this,Ft,"f")}async _createThreadAssistantStream(e,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of s)_(this,se,"m",go).call(this,a);if(s.controller.signal?.aborted)throw new W;return this._addRun(_(this,se,"m",yo).call(this))}async _createAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.create(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)_(this,se,"m",go).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,se,"m",yo).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(Xn(s)&&Xn(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(!Xn(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)}};Dt=Ke,go=function(e){if(!this.ended)switch(C(this,ys,e,"f"),_(this,se,"m",vu).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,se,"m",Cu).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,se,"m",Iu).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,se,"m",Au).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},yo=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!_(this,Ft,"f"))throw Error("Final run has not been received");return _(this,Ft,"f")},Au=function(e){let[r,n]=_(this,se,"m",Su).call(this,e,_(this,xe,"f"));C(this,xe,r,"f"),_(this,gs,"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,mn,"f")){if(_(this,Lt,"f"))switch(_(this,Lt,"f").type){case"text":this._emit("textDone",_(this,Lt,"f").text,_(this,xe,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Lt,"f").image_file,_(this,xe,"f"));break}C(this,mn,o.index,"f")}C(this,Lt,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,mn,"f")!==void 0){let o=e.data.content[_(this,mn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,xe,"f"));break;case"text":this._emit("textDone",o.text,_(this,xe,"f"));break}}_(this,xe,"f")&&this._emit("messageDone",e.data),C(this,xe,void 0,"f")}},Iu=function(e){let r=_(this,se,"m",Tu).call(this,e);switch(C(this,_o,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,ws,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,ye,"f")&&this._emit("toolCallDone",_(this,ye,"f")),C(this,ws,s.index,"f"),C(this,ye,r.step_details.tool_calls[s.index],"f"),_(this,ye,"f")&&this._emit("toolCallCreated",_(this,ye,"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":C(this,_o,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,ye,"f")&&(this._emit("toolCallDone",_(this,ye,"f")),C(this,ye,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},vu=function(e){_(this,Qa,"f").push(e),this._emit("event",e)},Tu=function(e){switch(e.event){case"thread.run.step.created":return _(this,Ne,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Ne,"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=Dt.accumulateDelta(r,n.delta);_(this,Ne,"f")[e.data.id]=o}return _(this,Ne,"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,Ne,"f")[e.data.id]=e.data;break}if(_(this,Ne,"f")[e.data.id])return _(this,Ne,"f")[e.data.id];throw new Error("No snapshot available")},Su=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,se,"m",ku).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")},ku=function(e,r){return Dt.accumulateDelta(r,e)},Cu=function(e){switch(C(this,_s,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":C(this,Ft,e.data,"f"),_(this,ye,"f")&&(this._emit("toolCallDone",_(this,ye,"f")),C(this,ye,void 0,"f"));break;case"thread.run.cancelling":break}};var Ut=class extends g{constructor(){super(...arguments),this.steps=new pn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/runs/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/runs`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(p`/threads/${o}/runs/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return Ke.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response: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 Oe(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Ke.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return Ke.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Ut.Steps=pn;var ft=class extends g{constructor(){super(...arguments),this.runs=new Ut(this._client),this.messages=new dn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/threads/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ke.createThreadAssistantStream(e,this._client.beta.threads,r)}};ft.Runs=Ut;ft.Messages=dn;var Ae=class extends g{constructor(){super(...arguments),this.realtime=new pt(this._client),this.chatkit=new mt(this._client),this.assistants=new sn(this._client),this.threads=new ft(this._client)}};Ae.Realtime=pt;Ae.ChatKit=mt;Ae.Assistants=sn;Ae.Threads=ft;var qt=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var fn=class extends g{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Bt=class extends g{constructor(){super(...arguments),this.content=new fn(this._client)}create(e,r,n){return this._client.post(p`/containers/${e}/files`,at({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/containers/${e}/files`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(p`/containers/${o}/files/${e}`,{...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Bt.Content=fn;var ht=class extends g{constructor(){super(...arguments),this.files=new Bt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};ht.Files=Bt;var hn=class extends g{create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/conversations/${e}/items`,{query:{include:o},body:s,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{conversation_id:o,...s}=r;return this._client.get(p`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/conversations/${e}/items`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(p`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var gt=class extends g{constructor(){super(...arguments),this.items=new hn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};gt.Items=hn;var Kt=class extends g{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&J(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:(J(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=xu(u)}),a)))}};var gn=class extends g{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(p`/evals/${o}/runs/${s}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r,n){let{eval_id:o,...s}=r;return this._client.getAPIList(p`/evals/${o}/runs/${e}/output_items`,R,{query:s,...n,__security:{bearerAuth:!0}})}};var Gt=class extends g{constructor(){super(...arguments),this.outputItems=new gn(this._client)}create(e,r,n){return this._client.post(p`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/evals/${e}/runs`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Gt.OutputItems=gn;var yt=class extends g{constructor(){super(...arguments),this.runs=new Gt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};yt.Runs=Gt;var Wt=class extends g{create(e,r){return this._client.post("/files",ue({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(p`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!o.has(a.status);)if(await Oe(r),a=await this.retrieve(e),Date.now()-s>n)throw new Ee({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var yn=class extends g{};var _n=class extends g{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 Vt=class extends g{constructor(){super(...arguments),this.graders=new _n(this._client)}};Vt.Graders=_n;var wn=class extends g{create(e,r,n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,le,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(p`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends g{constructor(){super(...arguments),this.permissions=new wn(this._client)}};Ht.Permissions=wn;var bn=class extends g{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var Jt=class extends g{constructor(){super(...arguments),this.checkpoints=new bn(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/events`,R,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};Jt.Checkpoints=bn;var Ie=class extends g{constructor(){super(...arguments),this.methods=new yn(this._client),this.jobs=new Jt(this._client),this.checkpoints=new Ht(this._client),this.alpha=new Vt(this._client)}};Ie.Methods=yn;Ie.Jobs=Jt;Ie.Checkpoints=Ht;Ie.Alpha=Vt;var xn=class extends g{};var _t=class extends g{constructor(){super(...arguments),this.graderModels=new xn(this._client)}};_t.GraderModels=xn;var Zt=class extends g{createVariation(e,r){return this._client.post("/images/variations",ue({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",ue({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 Qt=class extends g{retrieve(e,r){return this._client.get(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",le,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var Yt=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var An=class extends g{accept(e,r,n){return this._client.post(p`/realtime/calls/${e}/accept`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(p`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(p`/realtime/calls/${e}/refer`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(p`/realtime/calls/${e}/reject`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var In=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Ge=class extends g{constructor(){super(...arguments),this.clientSecrets=new In(this._client),this.calls=new An(this._client)}};Ge.ClientSecrets=In;Ge.Calls=An;function Eu(t,e){if(!e||!Lf(e)){let r={...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(o=>({...o,parsed:null}))}:n)};return Pu(t,r)&&_e(r),r}return Ya(t,e)}function Ya(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?Uf(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?jf(e,i.text):null}:i);return{...s,content:a}}return s}),o=Object.assign({},t,{output:n});return Pu(t,o)&&_e(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let s of o.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),o}function jf(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Lf(t){return!!io(t.text?.format)}function Df(t){return t?.$brand==="auto-parseable-tool"}function Ff(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Uf(t,e){let r=Ff(t.tools??[],e.name);return{...e,...e,parsed_arguments:Df(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Pu(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function _e(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}function Mu(t,e){if(!e){if(t.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Ou(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&_e(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&_e(e);break}case"response.content_part.added":{let r=z(e,t.output_index),n=r.type,o=t.part;n==="message"&&o.type!=="reasoning_text"?(r.content.push(structuredClone(o)),o.type==="output_text"&&_e(e)):n==="reasoning"&&o.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(o)));break}case"response.content_part.done":{let r=z(e,t.output_index),n=t.part;if(r.type==="message"&&n.type!=="reasoning_text")we(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&_e(e);else if(r.type==="reasoning"&&n.type==="reasoning_text"){let o=r.content;if(!o)throw new k(`missing content at index ${t.content_index}`);we(o,t.content_index),o[t.content_index]=structuredClone(n)}break}case"response.output_text.delta":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.text=t.text,_e(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}break}case"response.refusal.done":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=z(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=z(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=z(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new k(`missing content at index ${t.content_index}`);let n=we(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.reasoning_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new k(`missing content at index ${t.content_index}`);let n=we(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.text=t.text}break}case"response.reasoning_summary_part.added":{let r=z(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=z(e,t.output_index);r.type==="reasoning"&&(we(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=z(e,t.output_index);if(r.type==="reasoning"){let n=we(r.summary,t.summary_index);n.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){let n=we(r.summary,t.summary_index);n.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=z(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=z(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=Ou(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:qf(t)}return e}function Ou(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&_e(e),e}function z(t,e){let r=t.output[e];if(!r)throw new k(`missing output at index ${e}`);return r}function we(t,e){let r=t[e];if(!r)throw new k(`missing content at index ${e}`);return r}function qf(t){throw new k(`Unhandled response stream event: ${JSON.stringify(t)}`)}var wo,bs,Xt,xs,Ru,$u,Nu,As=class t extends it{constructor(e){super(),wo.add(this),bs.set(this,void 0),Xt.set(this,void 0),xs.set(this,void 0),C(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){this._listenForAbort(n?.signal),_(this,wo,"m",Ru).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)_(this,wo,"m",$u).call(this,a,s);if(o.controller.signal?.aborted)throw new W;return _(this,wo,"m",Nu).call(this)}[(bs=new WeakMap,Xt=new WeakMap,xs=new WeakMap,wo=new WeakSet,Ru=function(){this.ended||C(this,Xt,void 0,"f")},$u=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=Mu(r,_(this,Xt,"f"));switch(C(this,Xt,s,"f"),o("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new k(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new k(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new k(`expected content to be 'output_text', got ${i.type}`);o("response.output_text.delta",{...r,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=s.output[r.output_index];if(!a)throw new k(`missing output at index ${r.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:o(r.type,r);break}},Nu=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,Xt,"f");if(!r)throw new k("request ended without sending any events");C(this,Xt,void 0,"f");let n=Bf(r,_(this,bs,"f"));return C(this,xs,n,"f"),n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=_(this,xs,"f");if(!e)throw new k("stream ended without producing a ChatCompletion");return e}};function Bf(t,e){return Eu(t,e)}var vn=class extends g{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var Tn=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var ze=class extends g{constructor(){super(...arguments),this.inputItems=new vn(this._client),this.inputTokens=new Tn(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"&&_e(n),n))}retrieve(e,r={},n){return this._client.get(p`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&_e(o),o))}delete(e,r){return this._client.delete(p`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Ya(n,e))}stream(e,r){return As.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(p`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};ze.InputItems=vn;ze.InputTokens=Tn;var Sn=class extends g{retrieve(e,r){return this._client.get(p`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var kn=class extends g{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var er=class extends g{constructor(){super(...arguments),this.content=new kn(this._client)}create(e,r={},n){return this._client.post(p`/skills/${e}/versions`,at({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/skills/${e}/versions`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};er.Content=kn;var We=class extends g{constructor(){super(...arguments),this.content=new Sn(this._client),this.versions=new er(this._client)}create(e={},r){return this._client.post("/skills",at({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};We.Content=Sn;We.Versions=er;var Cn=class extends g{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,ue({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var wt=class extends g{constructor(){super(...arguments),this.parts=new Cn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(p`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};wt.Parts=Cn;var zu=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 En=class extends g{create(e,r,n){return this._client.post(p`/vector_stores/${e}/file_batches`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/file_batches/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(p`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(p`/vector_stores/${o}/file_batches/${e}/files`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response: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 Oe(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 d(f){for(let I of f){let w=await i.files.create({file:I,purpose:"assistants"},o);l.push(w.id)}}let m=Array(a).fill(u).map(d);return await zu(m),await this.createAndPoll(e,{file_ids:l})}};var Pn=class extends g{create(e,r,n){return this._client.post(p`/vector_stores/${e}/files`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(p`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/vector_stores/${e}/files`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),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 Oe(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(p`/vector_stores/${o}/files/${e}/content`,le,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ve=class extends g{constructor(){super(...arguments),this.files=new Pn(this._client),this.fileBatches=new En(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/vector_stores/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(p`/vector_stores/${e}/search`,le,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};Ve.Files=Pn;Ve.FileBatches=En;var tr=class extends g{create(e,r){return this._client.post("/videos",ue({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",ue({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(p`/videos/${e}/content`,{query:r,...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",ue({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",ue({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(p`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(p`/videos/${e}/remix`,at({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var On,ju,Is,rr=class extends g{constructor(){super(...arguments),On.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,On,"m",ju).call(this,n);let s=T([r]).values,a=_(this,On,"m",Is).call(this,s,"webhook-signature"),i=_(this,On,"m",Is).call(this,s,"webhook-timestamp"),u=_(this,On,"m",Is).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Pe("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>o)throw new Pe("Webhook timestamp is too old");if(l>d+o)throw new Pe("Webhook timestamp is too new");let m=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),I=u?`${u}.${i}.${e}`:`${i}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of m)try{let y=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,y,new TextEncoder().encode(I)))return}catch{continue}throw new Pe("The given webhook signature does not match the expected signature")}};On=new WeakSet,ju=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")},Is=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 Du=Symbol.for("openai.node.providerDefinitions.v1"),Fu=globalThis,Uu=Fu[Du],qu=Uu??new WeakMap;Uu||Object.defineProperty(Fu,Du,{value:qu});function Bu(t){let e=qu.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Xa,ei,bo,Ku,Yf="workload-identity-auth",P=class{constructor(e={}){Xa.add(this),bo.set(this,void 0),this.completions=new qt(this),this.chat=new ut(this),this.embeddings=new Kt(this),this.files=new Wt(this),this.images=new Zt(this),this.audio=new $e(this),this.moderations=new Yt(this),this.models=new Qt(this),this.fineTuning=new Ie(this),this.graders=new _t(this),this.vectorStores=new Ve(this),this.webhooks=new rr(this),this.beta=new Ae(this),this.batches=new jt(this),this.uploads=new wt(this),this.admin=new dt(this),this.responses=new ze(this),this.realtime=new Ge(this),this.conversations=new gt(this),this.evals=new yt(this),this.containers=new ht(this),this.skills=new We(this),this.videos=new tr(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(b.length)throw new k(`The \`provider\` option cannot be used with ${b.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=r?null:be("OPENAI_BASE_URL"),apiKey:o=r?null:be("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:be("OPENAI_ADMIN_KEY")??null,organization:a=r?null:be("OPENAI_ORG_ID")??null,project:i=r?null:be("OPENAI_PROJECT_ID")??null,webhookSecret:u=be("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,m=r?Bu(r):void 0,f={apiKey:o,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...d,baseURL:m?.baseURL??(n||"https://api.openai.com/v1")};if(o&&l)throw new k("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!m&&!o&&!s&&!l)throw new k("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Ll())throw new k(`It looks like you're running in a browser-like environment.
52
+
53
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
54
+ If you understand the risks and have appropriate mitigations in place,
55
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
56
+
57
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
58
+
59
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
60
+ `);this.baseURL=f.baseURL,this.timeout=f.timeout??ei.DEFAULT_TIMEOUT,this.logger=f.logger??console;let I="warn";this.logLevel=I,this.logLevel=Pa(f.logLevel,"ClientOptions.logLevel",this)??Pa(be("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??I,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??Zo(),C(this,bo,Ul,"f");let w=r?void 0:be("OPENAI_CUSTOM_HEADERS");if(w){let b={};for(let y of w.split(`
61
+ `)){let h=y.indexOf(":");h>=0&&(b[y.substring(0,h).trim()]=y.substring(h+1).trim())}f.defaultHeaders=T([b,f.defaultHeaders])}this._options=f,this._provider=m,l&&(this._workloadIdentityAuth=new ns(l,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,n=e.provider??r,o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,n!==r&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return T([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return T([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return T([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return T([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Zl(e)}getUserAgent(){return`${this.constructor.name}/JS ${st}`}defaultIdempotencyKey(){return`stainless-node-retry-${ya()}`}makeStatusError(e,r,n,o){return G.generate(e,r,n,o)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof k?n:new k(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,Xa,"m",Ku).call(this)&&n||this.baseURL,s=Ol(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){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Pt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:a,url:i,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:o}),await this._provider?.prepareRequest?.(a,{url:i,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(J(this).debug(`[${l}] sending request`,Fe({retryOfRequestLogID:n,method:o.method,url:i,options:o,headers:a.headers})),o.signal?.aborted)throw new W;let f=o.__security??{bearerAuth:!0},I=new AbortController,w=await this.fetchWithAuth(i,a,u,I,f).catch(Qn),b=Date.now();if(w instanceof globalThis.Error){let x=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new W;let S=Zn(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return J(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${x}`),J(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${x})`,Fe({retryOfRequestLogID:n,url:i,durationMs:b-m,message:w.message})),this.retryRequest(o,r,n??l);throw J(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),J(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,Fe({retryOfRequestLogID:n,url:i,durationMs:b-m,message:w.message})),w instanceof Ct||w instanceof Yn?w:S?new Ee:new ot({message:Xf(w),cause:w})}let y=[...w.headers.entries()].filter(([x])=>x==="x-request-id").map(([x,S])=>", "+x+": "+JSON.stringify(S)).join(""),h=`[${l}${d}${y}] ${a.method} ${i} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-m}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Aa(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let x=await this.shouldRetry(w);if(r&&x){let V=`retrying, ${r} attempts remaining`;return await Aa(w.body),J(this).info(`${h} - ${V}`),J(this).debug(`[${l}] response error (${V})`,Fe({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),this.retryRequest(o,r,n??l,w.headers)}let S=x?"error; no more retries left":"error; not retryable";J(this).info(`${h} - ${S}`);let E=await w.text().catch(V=>Qn(V).message),F=$l(E),q=F?void 0:E;throw J(this).debug(`[${l}] response error (${S})`,Fe({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:q,durationMs:Date.now()-m})),this.makeStatusError(w.status,F,q,w.headers)}return J(this).info(h),J(this).debug(`[${l}] response start`,Fe({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),{response:w,options:o,controller:I,requestLogID:l,retryOfRequestLogID:n,startTime:m}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new no(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 ${Yf}`){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),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,m={signal:o.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(m.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,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 Oe(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&&Rl("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:d,isStreamingBody:m}=this.buildBody({options:n});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...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=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Dl(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:n}=e;if(!r)return r===void 0&&"body"in e?{..._(this,bo,"f").call(this,{body:r,headers:T([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=T([n]),s=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,a=!s&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&o.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||s?{bodyHeaders:void 0,body:r,isStreamingBody:!a}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:Qo(r),isStreamingBody:!0}:typeof r=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,bo,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};ei=P,bo=new WeakMap,Xa=new WeakSet,Ku=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=ei;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=k;P.APIError=G;P.APIConnectionError=ot;P.APIConnectionTimeoutError=Ee;P.APIUserAbortError=W;P.NotFoundError=br;P.ConflictError=xr;P.RateLimitError=Ir;P.BadRequestError=yr;P.AuthenticationError=_r;P.InternalServerError=vr;P.PermissionDeniedError=wr;P.UnprocessableEntityError=Ar;P.InvalidWebhookSignatureError=Pe;P.toFile=so;P.Completions=qt;P.Chat=ut;P.Embeddings=Kt;P.Files=Wt;P.Images=Zt;P.Audio=$e;P.Moderations=Yt;P.Models=Qt;P.FineTuning=Ie;P.Graders=_t;P.VectorStores=Ve;P.Webhooks=rr;P.Beta=Ae;P.Batches=jt;P.Uploads=wt;P.Admin=dt;P.Responses=ze;P.Realtime=Ge;P.Conversations=gt;P.Evals=yt;P.Containers=ht;P.Skills=We;P.Videos=tr;function Xf(t){if(eh(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function eh(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}function th(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 ve(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Ee.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===W.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):th(t)?e=Wi.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Jn(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Jn(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Jn(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Jn(t,"MODEL_NOT_FOUND"):e=t,e}var Te=t=>t();function He(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function rh(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function vs(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var nh="LC_AUTOGENERATED";function nr(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'."),nh)}function Je(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(!jo.isInstance(t))throw new Error("Invalid generic chat message");return rh(t);default:throw new Error(`Unknown message type: ${e}`)}}function Gu(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-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 ri(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Wu(t){let e=Te(()=>{if(ri(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&ri(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 Vu(){let t=Gi();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function xt(t,e=!1,r="1.0.0"){let n=Wu(t),o=Vu(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function Hu(t,e){let r;return hr(t)?r=aa(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function oh(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ju(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(Zu(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
62
+ `)}function Zu(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}: ${Ts(o,e)},`):r.push(`${n}?: ${Ts(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
63
+ `)}function Ts(t,e){if(oh(t))return t.anyOf.map(r=>Ts(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["{",Zu(t,e+2),"}"].join(`
64
+ `);case"array":return t.items?`${Ts(t.items,e)}[]`:"any[]";default:return""}}function Ss(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 Mn(t){return"type"in t&&t.type!=="function"}function Qu(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 Yu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function or(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function ks(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Xu(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 tc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function rc(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function nc(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 oc(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 ac=Symbol("Let zodToJsonSchema decide on which parser to use"),sc={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"},ic=t=>typeof t=="string"?{...sc,basePath:["#"],definitions:{},name:t}:{...sc,basePath:["#"],definitions:{},...t};var xo=t=>"_def"in t?t._def:t;function lc(t){if(!t)return!0;for(let e in t)return!1;return!0}var uc=t=>{let e=ic(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])=>[xo(o),{def:xo(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ni(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function L(t,e,r,n,o){t[e]=r,ni(t,e,n,o)}function cc(){return{}}function dc(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=M(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&L(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&L(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(L(r,"minItems",t.exactLength.value,t.exactLength.message,e),L(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function pc(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?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function mc(){return{type:"boolean"}}function fc(t,e,r){return M(t.type._def,e,r)}var hc=(t,e,r)=>M(t.innerType._def,e,r);function oi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>oi(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":L(r,"minimum",n.value,n.message,e);break;case"max":L(r,"maximum",n.value,n.message,e);break}return r};function gc(t,e,r){return{...M(t.innerType._def,e,r),default:t.defaultValue()}}function yc(t,e,r){return e.effectStrategy==="input"?M(t.schema._def,e,r):{}}function _c(t){return{type:"string",enum:[...t.values]}}var ah=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function wc(t,e){let r=[M(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),M(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(ah(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 bc(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 si,sr={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:()=>(si===void 0&&(si=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),si),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 Cs(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?ih(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":L(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":L(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":Se(r,"email",o.message,e);break;case"format:idn-email":Se(r,"idn-email",o.message,e);break;case"pattern:zod":ke(r,sr.email,o.message,e);break}break;case"url":Se(r,"uri",o.message,e);break;case"uuid":Se(r,"uuid",o.message,e);break;case"regex":ke(r,o.regex,o.message,e);break;case"cuid":ke(r,sr.cuid,o.message,e);break;case"cuid2":ke(r,sr.cuid2,o.message,e);break;case"startsWith":ke(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":ke(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Se(r,"date-time",o.message,e);break;case"date":Se(r,"date",o.message,e);break;case"time":Se(r,"time",o.message,e);break;case"duration":Se(r,"duration",o.message,e);break;case"length":L(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),L(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ke(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Se(r,"ipv4",o.message,e),o.version!=="v4"&&Se(r,"ipv6",o.message,e);break}case"emoji":ke(r,sr.emoji,o.message,e);break;case"ulid":{ke(r,sr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Se(r,"binary",o.message,e);break}case"contentEncoding:base64":{L(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ke(r,sr.base64,o.message,e);break}}break}case"nanoid":ke(r,sr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var ih=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Se=(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}}})):L(t,"format",e,r,n)},ke=(t,e,r,n)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:xc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):L(t,"pattern",xc(e,n),r,n)},xc=(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
65
+ ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
66
+ ]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
67
+ `:`[${o[l]}\r
68
+ ]`;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 Es(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Cs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function Ac(t,e){if(e.mapStrategy==="record")return Es(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ic(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 vc(){return{not:{}}}function Tc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ao={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function kc(t,e){if(e.target==="openApi3")return Sc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ao&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Ao[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 Sc(t,e)}var Sc=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Cc(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Ao[t.innerType._def.typeName],nullable:!0}:{type:[Ao[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=M(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Ec(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",ni(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function lh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Pc(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=M(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:lh(t,e)};return r.required.length||delete r.required,r}var Oc=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return M(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Mc=(t,e,r)=>{if(e.pipeStrategy==="input")return M(t.in._def,e,r);if(e.pipeStrategy==="output")return M(t.out._def,e,r);let n=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Rc(t,e,r){return M(t.type._def,e,r)}function $c(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&L(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&L(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Nc(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function zc(){return{not:{}}}function jc(){return{}}var Lc=(t,e,r)=>M(t.innerType._def,e,r);function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==ac)return s}if(n&&!r){let s=uh(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=ph(t,t.typeName,e,r);return s&&mh(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var uh=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((n,o)=>o===0?n:ch(n)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:dh(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}},Dc="_x_",ch=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Dc))return t;let e=Dc;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},dh=(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 N.ZodString:return Cs(t,r);case N.ZodNumber:return Ec(t,r);case N.ZodObject:return Pc(t,r);case N.ZodBigInt:return pc(t,r);case N.ZodBoolean:return mc();case N.ZodDate:return oi(t,r);case N.ZodUndefined:return zc();case N.ZodNull:return Tc(r);case N.ZodArray:return dc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return kc(t,r);case N.ZodIntersection:return wc(t,r);case N.ZodTuple:return Nc(t,r);case N.ZodRecord:return Es(t,r);case N.ZodLiteral:return bc(t,r);case N.ZodEnum:return _c(t);case N.ZodNativeEnum:return Ic(t);case N.ZodNullable:return Cc(t,r,n);case N.ZodOptional:return Oc(t,r,n);case N.ZodMap:return Ac(t,r);case N.ZodSet:return $c(t,r);case N.ZodLazy:return M(t.getter()._def,r,n);case N.ZodPromise:return Rc(t,r,n);case N.ZodNaN:case N.ZodNever:return vc();case N.ZodEffects:return yc(t,r,n);case N.ZodAny:return cc();case N.ZodUnknown:return jc();case N.ZodDefault:return gc(t,r,n);case N.ZodBranded:return fc(t,r,n);case N.ZodReadonly:return Lc(t,r,n);case N.ZodCatch:return hc(t,r,n);case N.ZodPipeline:return Mc(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},mh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ai=(t,e)=>{let r=uc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=M(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(lc(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,I]of m)u[f]=M(xo(I),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}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 Fc(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 Ze(e,[],e)}function ii(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(ii(e))return!0;for(let e of t.anyOf??[])if(ii(e))return!0;return!1}function Ze(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ar(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(ar(n))for(let[f,I]of Object.entries(n))Ze(I,[...e,"$defs",f],r);let o=t.definitions;if(ar(o))for(let[f,I]of Object.entries(o))Ze(I,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(ar(i)){for(let[f,I]of Object.entries(i))if(!ii(I)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(i),t.properties=Object.fromEntries(Object.entries(i).map(([f,I])=>[f,Ze(I,[...e,"properties",f],r)]))}let u=t.items;ar(u)&&(t.items=Ze(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,I)=>Ze(f,[...e,"anyOf",String(I)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=Ze(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,I)=>Ze(f,[...e,"allOf",String(I)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&hh(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=fh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!ar(f))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,Ze(t,e,r)}return t}function fh(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(!ar(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 ar(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function gh(t,e){return ai(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function yh(t){return Fc(Xi(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function _h(t){return"_zod"in t}function Uc(t,e,r){return uu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:_h(t)?yh(t):gh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var qc=["jsonSchema","functionCalling","jsonMode"];function Bc(t,e){if(typeof e<"u"&&!qc.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${qc.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 wh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Kc(t,e,r){if(el(t))return Uc(t,e,r);if(Fo(t))return wh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:St(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Qi(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function Gc(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 Wc={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Rn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var ir=class extends Ko{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??De("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??De("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!He(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)?Kc(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=xt(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return or(t)?oc(t.metadata.customTool):qo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Hu(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(Mn(n)||or(n))return n;if(Qu(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return hr(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(Je(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,d=s;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.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=Ju(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 ve(o)}})}get profile(){return Wc[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=Bc(this.model,e?.method);if(i==="jsonMode"){n=sa(o);let u=St(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=St(o),l={name:s??"extract",description:na(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)||Do(o)){let d=sa(o);n=rt.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d.invoke(m.content))}else n=new rl}else{let u=s??"extract",l=St(o),d;Tt(o)||Do(o)?d={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(d=o,u=o.name):(u=o.title??u,d={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],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=nl(o,u)}return ol(r,n,a)}};var Ps={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=ea({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=Xs(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=Xs(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=ea({dataUrl:t.url}),r=nr(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=nr(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`)}},li=({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(Bo(l,{returnId:!0}))}catch(d){a.push(mr(l,d.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 D({content:Gc(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 jo(t.content||"",t.role??"unknown")}},ui=({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 ra({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 tt({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new Lo({content:s,response_metadata:i}):o==="developer"?new Lo({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Hi({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new ta({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new Vi({content:s,role:o,response_metadata:i})},Vc=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=Ji(()=>{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=nr(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}}}},Hc=({message:t,model:e})=>{let r=Je(t);if(r==="system"&&He(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return D.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(oa):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&U.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=Vc(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},$n=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Hc({message:r});let n=Je(r);n==="system"&&He(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>No(a)?zo(a,Ps):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),D.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(oa):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),U.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 Os=class extends ir{constructor(t,e){super(Rn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Ss(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),He(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=$n({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let I of a){I.message.response_metadata={...I.generationInfo,...I.message.response_metadata};let w=I.generationInfo?.completion??0;i[w]===void 0?i[w]=I:i[w]=i[w].concat(I)}let u=Object.entries(i).sort(([I],[w])=>parseInt(I,10)-parseInt(w,10)).map(([I,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{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:d,completion_tokens_details:m}=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),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(n.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let I of a?.choices??[]){let w={text:I.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(I.message??{role:"assistant"},a)};w.generationInfo={...I.finish_reason?{finish_reason:I.finish_reason}:{},...I.logprobs?{logprobs:I.logprobs}:{}},et(w.message)&&(w.message.usage_metadata=n),w.message=new D(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=$n({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),a=this.streamUsage??e.streamUsage;yield*Go(async function*(u,l){for await(let d of u){if(l?.aborted)return;yield d}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=$n({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:d}=l;if(!d)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let I={...f};l.finish_reason!=null&&(I.finish_reason=l.finish_reason,I.system_fingerprint=u.system_fingerprint,I.model_name=u.model,I.service_tier=u.service_tier),this.logprobs&&(I.logprobs=l.logprobs);let w=new Vn({message:m,text:m.content,generationInfo:I});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}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}},d=new Vn({message:new tt({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 d,await r?.handleLLMNewToken(d.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:d})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let 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 ve(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return ui({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return li({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Ms="__openai_function_call_ids__",Rs="__openai_custom_tool_call_ids__";function td(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 xh(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 Io=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}},$s=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],n=[],o=t.output.map(i=>{if(i.type==="function_call"&&"parsed_arguments"in i){let u={...i};return delete u.parsed_arguments,u}return i}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let i of t.output)if(i.type==="message")e.push(...i.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(td),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(Bo(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),n.push(mr(u,d))}a[Ms]??={},i.id&&(a[Ms][i.call_id]=i.id)}else if(i.type==="reasoning"){a.reasoning=i;let u=i.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(i.type==="custom_tool_call"){let u=Xu(i);u?(r.push(u),a[Rs]??={},i.id&&i.call_id&&(a[Rs][i.call_id]=i.id)):n.push(mr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=ec(i);u?r.push(u):n.push(mr(i,"Malformed computer call"))}else i.type==="image_generation_call"?(i.result&&e.push({type:"image",mimeType:"image/png",data:i.result,id:i.id,metadata:{status:i.status}}),a.tool_outputs??=[],a.tool_outputs.push(i)):(a.tool_outputs??=[],a.tool_outputs.push(i));return new D({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Io(t.usage),additional_kwargs:a,response_metadata:s})},rd=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}},ci=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:[td(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Ms]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Rs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")i=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){i=t.response.id;let u=$s(t.response);if(n=Io(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{a.parsed??=JSON.parse(u.text)}catch{}for(let[l,d]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=d)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,u,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:u,status:l}}}else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((d,m)=>({...d,index:m})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(d=>d.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new Vn({text:e.map(u=>u.text).join(""),message:new tt({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},nd=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Te(()=>{try{let h=Je(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let d=(h,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},m=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{let x=Te(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:x,file_id:h.fileId};if(h.url)return{type:"input_image",detail:x,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},I=h=>{if(h.fileId){let x=vs(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=vs(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=nr(h),S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${S}`,filename:x}}},w=h=>{let x=Te(()=>{if(Array.isArray(h.summary)){let E=h.summary?.map(F=>F?.text).filter(F=>typeof F=="string")??[];if(E.length>0)return E}return h.reasoning?[h.reasoning]:[]}),S=x.length>0?x.map(E=>({type:"summary_text",text:E})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:S}},b=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:m(h.args)}),y=h=>{let x=m(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:x,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let x=Te(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});d([{type:"input_text",text:h.text}],x)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield w(h);else if(h.type==="tool_call"){yield*l();let x=h.id??"";x&&(s.add(x),i.delete(x)),yield b(h)}else if(h.type==="tool_call_chunk"){if(h.id){let x=i.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),i.set(h.id,x)}}else if(h.type==="server_tool_call"){yield*l();let x=h.id??"";x&&(a.add(x),u.delete(x)),yield b(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let x=u.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),u.set(h.id,x)}}else if(h.type==="server_tool_call_result")yield*l(),yield y(h);else if(h.type!=="audio")if(h.type==="file"){let x=I(h);x&&d([x])}else if(h.type==="image"){let x=f(h);x&&d([x])}else if(h.type==="video"){let x=I(h);x&&d([x])}else h.type==="text-plain"?h.text&&d([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,x]of i){if(!h||s.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}for(let[h,x]of u){if(!h||a.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}}return Array.from(r())},vo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return nd(n);let s=n.additional_kwargs,a=Je(n);if(a==="system"&&He(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(f=>f.type==="input_image");if(l)return l;let d=i.content.find(f=>f.type==="computer_screenshot");if(d)return d;let m=i.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id: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(b=>"type"in b))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=rd(u);i.push(b)}let{content:d}=n;if(s?.refusal&&(typeof d=="string"&&(d=[{type:"output_text",text:d,annotations:[]}]),d=[...d,{type:"refusal",refusal:s.refusal}]),typeof d=="string"||d.length>0){let b={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Te(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let h=y;return{type:"output_text",text:h.text,annotations:(h.annotations??[]).map(xh)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Te(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let m=s?.[Ms],f=s?.[Rs];D.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(b=>rc(b,f)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:f?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:tc(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:m?.[b.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:m?.[b.id]}})));let I=o?.output?.length?o?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(I!=null){let b=I?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),No(l)){if(l.type==="file"){let d=vs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...d?{filename:d}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...d?{filename:d}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:nr(l)}}return zo(l,Ps)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Te(()=>{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:Te(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*di(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,a=0,i=!1,u,l,d,m,f=new Set,I=(y,h)=>{let x=s.get(y);if(x!==void 0)return{index:x,isNew:!1};let S=a++;return s.set(y,S),o.set(S,{...h}),{index:S,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let h=o.get(y);h&&(f.add(y),yield{event:"content-block-finish",index:y,content:sl(h)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:h,isNew:x}=I(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let S=o.get(h);S.text=(S.text??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:h,isNew:x}=I(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let S=o.get(h);S.reasoning=(S.reasoning??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"reasoning-delta",reasoning:y.delta}};continue}if(y.type==="response.output_item.added"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="custom_tool_call",S=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:E,isNew:F}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index,...x?{isCustomTool:!0}:{}});if(F&&(yield{event:"content-block-start",index:E,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index}}),S){let q=o.get(E);yield{event:"content-block-delta",index:E,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...q.id!=null?{id:q.id}:{},...q.name!=null?{name:q.name}:{},args:q.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:h,isNew:x}=I(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:h,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let S=o.get(h);S.args=(S.args??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:S,isNew:E}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index});if(E)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index}};else{let F=o.get(S);F.args=x,F.id=y.item.call_id,F.name=y.item.name}yield*b(S);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=Ah(y.response.status,y.type),m={model_provider:n,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=Io(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of o)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function Ah(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Ns=class extends ir{constructor(t,e){super(Rn(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:Yu(t?.tool_choice)?t?.tool_choice:(()=>{let o=Ss(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:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:$s(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*di(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of n){if(e.signal?.aborted)return;let s=ci(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(o){throw ve(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw ve(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Mn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(or(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(qo(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 ks(n)&&r.push(nc(n));return r}};var zs=class od extends ir{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=Rn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Ns(n),this.completions=n?.completions??new Os(n)}_useResponsesApi(e){let r=e?.tools?.some(Mn),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(ks)||e?.tools?.some(or);return this.useResponsesApi||r||n||o||Gu(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamChatModelEvents(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new od(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var kh=v.object({type:v.literal("screenshot")}),Ch=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Eh=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Ph=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),Oh=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),Mh=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),Rh=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),$h=v.object({type:v.literal("type"),text:v.string()}),Nh=v.object({type:v.literal("wait"),duration:v.number().optional()}),zh=v.union([kh,Ch,Eh,Ph,Oh,Mh,Rh,$h,Nh]),Fq=v.object({action:zh});var jh=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),Kq=v.union([jh]);var Hq=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var Lh=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),Dh=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),Fh=v.object({type:v.literal("delete_file"),path:v.string()}),Yq=v.union([Lh,Dh,Fh]);var id={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Kh={default:"text-embedding-ada-002"},pi=new Map,js=null,Gh=()=>{let t=ad.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},Wh=async t=>{let e=Gh();pi.size===0&&(js||(js=(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=>pi.set(o.name,o))}catch(n){throw js=null,n}})()),await js);let r=pi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Vh=async(t="default")=>await Wh(id[t]);var zn=(t,e)=>e,ld=(t,e)=>({...t,...e}),ud=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
69
+
70
+ `);return o[o.length-1]?.trim()===r?t:`${t}
71
+
72
+ ${r}`},cd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),lr=()=>({agentExecutionContext:O({reducer:ld,default:cd}),outputMessage:O({reducer:ud,default:()=>""}),summary:O({reducer:zn,default:()=>""}),status:O({reducer:zn})}),Ls=()=>({...lr(),sharedStatePatch:O({reducer:zn})}),Hh=O.Root({agentExecutionContext:O({default:cd,reducer:ld}),currentIntent:O({default:()=>"none",reducer:zn}),lastExecutedAgent:O({default:()=>"",reducer:zn}),requiresFollowUp:O({default:()=>!0,reducer:zn}),stepCount:O({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:O({default:()=>"",reducer:ud})});var Jh=t=>typeof t=="string"&&t.length>0?t:void 0,Zh=()=>Li(),Qh=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Yh=t=>{let e=t?.configurable;return{conversationId:Jh(e?.thread_id),abortSignal:t?.signal,requestId:Zh(),requestSource:Qh(Bh.applicationName)}},Xh=async({config:t})=>{let e=ad.getDefault(),r=(await qh.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Yh(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",u)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i);let d=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:l,signal:d})}},mi=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=id[e],s=await Vh(e);return new zs({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await Xh({config:n})}})};var eg=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(eg);var dd="0.1",Nn=1536,pd="openai",md=Kh.default,fd=`Name: {name}
73
+ Title: {title}
74
+ Description: {description}`,hd=`Name: {name}
75
+ Alias: {alias}
76
+ Description: {description}`,gd=v.object({schemaVersion:v.literal(dd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(pd),model:v.literal(md),dimensions:v.literal(Nn),templates:v.object({layer:v.string().default(fd),field:v.string().default(hd)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Nn,{message:`Layer vector must be exactly ${Nn} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Nn,{message:`Field vector must be exactly ${Nn} dimensions`})}))})).default([])});var tg=(t,e)=>{let r=al.fromTemplate(t);return fr.fromMessages([r,...e])};var To=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=tg(e,o??[]),l=(await mi({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var rg=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),xK=c.object({fields:c.array(rg)});var AK=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var _d=t=>Array.isArray(t)&&t.every(Wn),og=t=>typeof t=="object"&&t!=null&&"messages"in t&&_d(t.messages),sg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,Qe=class extends il{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e,r){let n=this.tools.find(o=>o.name===t.name);try{if(n===void 0)throw new Error(`Tool "${t.name}" not found.`);let o={...t,type:"tool_call"},s={...e,state:r,toolCallId:t.id??"",config:e,context:e.context,store:e.store??null,writer:e.writer??e.configurable?.writer??null},a=await n.invoke(o,s);return Wn(a)&&a.getType()==="tool"||vt(a)?a:new U({status:"success",name:n.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||$o(o))throw o;return new U({status:"error",content:`Error: ${o.message}
77
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(sg(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(_d(t))s=t;else if(og(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(et(l)){i=l;break}}if(i==null||!et(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(vt))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)vt(s)?s.graph===Le.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Ki(a))?o?o.goto.push(...s.goto):o=new Le({graph:Le.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var IG=O.Root({llmInputMessages:O({reducer:(t,e)=>Hn([],e),default:()=>[]})});var So=(t,e)=>e??t,Ug=O.Root({...Ls(),intent:O({reducer:So}),vectorSearchLayerResults:O({reducer:So,default:()=>[]}),vectorSearchFieldResults:O({reducer:So}),navigationInternalState:O({reducer:So,default:()=>({toolCallMessage:void 0})})});async function qg(t,e){let r=ur.getDefault().helperServices,n=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${fi.assetsPath?.endsWith("/")?fi.assetsPath:`${fi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await lg(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 ug({url:s,width:24,height:24}),u=new ig({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 Bg=["mapView"];function je(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Bg.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Kg({address:t},e){let{mapView:r}=je(e);return await qg(t,r)}var Gg=c.object({address:c.string().describe("The full address or place name to locate.")}),Wg=$(Kg,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Gg});async function Vg(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 Hg({bookmarkName:t},e){let{mapView:r}=je(e);return await Promise.resolve(Vg(t,r))}var Jg=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),Zg=$(Hg,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Jg});async function Qg(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 Yg({layerId:t,where:e},r){let{mapView:n}=je(r);return await Qg(t,e,n)}var Xg=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),ey=$(Yg,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Xg});async function ty(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 ry(t,e){let{mapView:r}=je(e);return await ty(r)}var ny=v.object({}),oy=$(ry,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ny});async function sy(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 ay(t,e){let{mapView:r}=je(e);return await sy(r)}var iy=c.object({}),ly=$(ay,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:iy});async function uy(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 cy({layerId:t},e){let{mapView:r}=je(e);return await uy(t,r)}var dy=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),py=$(cy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:dy});async function my(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function fy({scale:t},e){let{mapView:r}=je(e);return await my(t,r)}var hy=c.object({scale:c.number().describe("The map scale of the view to go to.")}),gy=$(fy,{name:"goToScale",description:"Go to the specified view scale.",schema:hy});async function yy(t,e,r){let n={target:new kd({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 _y({center:t,zoom:e,scale:r},n){let{mapView:o}=je(n);return await yy(t,o,{zoom:e,scale:r})}var wy=c.object({center:c.object({longitude:c.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:c.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:c.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:c.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),by=$(_y,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:wy});async function xy(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Ay({zoom:t},e){let{mapView:r}=je(e);return await xy(t,r)}var Iy=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),vy=$(Ay,{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:Iy}),vd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function Ye(t){let e=Object.entries(vd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
78
+ Available prompts:
79
+ ${Object.keys(vd).join(`
80
+ `)}`);return await e[1]()}var Dn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Ty(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=pg({basemapTheme:await xd(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=mg({basemapTheme:await xd(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 Sy(t){return await dg(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 Ty(u),d=await Sy(l);return i.renderer=d.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 Cy=["mapView"];function Ce(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Cy.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Ey({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await ky({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Py=c.object({layerId:c.string().describe("The id of the layer to apply the chart renderer to"),fields:c.array(c.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Oy=$(Ey,{name:"chart",description:`Label: Charts
81
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
82
+ Keywords: pie, chart, all categories, breakdown, proportion
83
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
84
+ Fields: This style requires 2-8 number fields.
85
+
86
+ Label: Charts and Size
87
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
88
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
89
+ Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
90
+ Fields: This style requires 2-8 number fields.`,schema:Py});function My(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=vi({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 Ry(t){return await fg(t)}async function $y({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=My(u),d=await Ry(l);return i.renderer=d.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 Ny({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await $y({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var zy=c.object({layerId:c.string().describe("The id of the layer to apply the color-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),jy=$(Ny,{name:"color-age",description:`Label: Age (color)
91
+ Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
92
+ Keywords: since, age, how old, how long
93
+ Example: Show the age of each feature based on its reported date.
94
+ Fields: This style requires at least one field with a date type.`,schema:zy});function Ly(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=vi({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 Dy(t){return await hg(t)}async function Fy({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=Ly(u),d=await Dy(l);return i.renderer=d.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 Uy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Fy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var qy=c.object({layerId:c.string().describe("The id of the layer to apply the color renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),By=$(Uy,{name:"color",description:`Label: Counts and Amounts (color)
95
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
96
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
97
+ Example: Color each feature based on the population density.
98
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:qy});function Ky(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=vi({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 Gy(t){return await gg(t)}async function Wy({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=Ky(u),d=await Gy(l);return i.renderer=d.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 Vy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Wy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Hy=c.object({layerId:c.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:c.array(c.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Jy=$(Vy,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
99
+ Description: Vary symbol size and color based on the values of two numeric attributes.
100
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
101
+ Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
102
+ Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:Hy});function Zy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=_g({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 Qy(t){return await yg(t)}async function Yy({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=Zy(i),l=await Qy(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 Xy({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await Yy({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var e_=c.object({layerId:c.string().describe("The id of the layer to apply the dot density renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),t_=$(Xy,{name:"dot-density",description:`Dot Density
103
+ Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
104
+ **Use cases:**
105
+ - Population distribution visualization
106
+ - Comparing multiple categories within areas
107
+ - Showing spatial distribution patterns
108
+ **Examples:**
109
+ - Show the density of the population based on various race/ethnic groups
110
+ - Visualize distribution of different crops across regions
111
+ - Display demographic patterns within census tracts
112
+ **Fields:** Requires 2-8 number fields.
113
+ **Keywords:** density, how much, how many, total, number, amount`,schema:e_});function r_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=bg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function n_(t){return await wg(t)}async function o_({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=r_(i),l=await n_(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 s_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await o_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var a_=c.object({layerId:c.string().describe("The id of the layer to apply the heatmap renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),i_=$(s_,{name:"heatmap",description:`Label: Heat Map
114
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
115
+ Keywords: density, heatmap, hot spots, pattern, cluster
116
+ Example: Create a heatmap
117
+ Fields: This typically requires zero or one field of type number.`,schema:a_});function l_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Ag({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 u_(t){return await xg(t)}async function c_({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=l_(u),d=await u_(l);return i.renderer=d.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 d_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await c_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var p_=c.object({layerId:c.string().describe("The id of the layer to apply the predominance renderer to"),fields:c.array(c.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),m_=$(d_,{name:"predominance",description:`Label: Predominant category
118
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
119
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
120
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
121
+ Fields: This style relies on 2-10 number fields.
122
+
123
+ Label: Predominant category and Size
124
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
125
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
126
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
127
+ Fields: This style relies on 2-10 number fields.`,schema:p_});function f_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=vg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function h_(t){return await Ig(t)}async function g_({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=f_(i),l=await h_(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 y_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await g_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var __=c.object({layerId:c.string().describe("The id of the layer to apply the relationship renderer to"),fields:c.array(c.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),w_=$(y_,{name:"relationship",description:`Label: Relationship
128
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
129
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
130
+ Example: Show the relationship between tree height and carbon storage
131
+ Fields: This style requires two number fields.`,schema:__});function b_(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 Tg(t)}async function A_({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=b_(u),d=await x_(l);return i.renderer=d.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 I_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await A_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var v_=c.object({layerId:c.string().describe("The id of the layer to apply the size-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),T_=$(I_,{name:"size-age",description:`Label: Age (size)
132
+ Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
133
+ Keywords: since, age, how old, how long
134
+ Example: Change the size of features so older features are larger than new features.
135
+ Fields: This style requires at least one field with a date type.`,schema:v_});function S_(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 k_(t){return await Sg(t)}async function C_({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=S_(u),d=await k_(l);return i.renderer=d.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 E_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await C_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var P_=c.object({layerId:c.string().describe("The id of the layer to apply the size renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),O_=$(E_,{name:"size",description:`Label: Counts and Amounts (size)
136
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
137
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
138
+ Example: Vary the size of each point based on the total population.
139
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.
140
+
141
+ Label: Continuous Timeline (size)
142
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
143
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
144
+ Example: Vary the size of each feature based on the date a ticket was completed.
145
+ Fields: This style requires a single field with a date type.`,schema:P_});function M_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Cg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function R_(t){return await kg(t)}async function $_({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=M_(u),d=await R_(l);return i.renderer=d.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 N_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await $_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var z_=c.object({layerId:c.string().describe("The id of the layer to apply the type renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),j_=$(N_,{name:"type",description:`Label: Types (unique symbols)
146
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
147
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
148
+ Example: Color each feature based on the region it belongs to
149
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:z_}),L_=O.Root({...lr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),selectedLayerId:O()}),D_=O.Root({...lr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),queryResponse:O(),dataExplorationMessages:O({reducer:Hn,default:()=>[]})}),F_=["mapView"];function At(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=F_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var U_=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."},q_=async(t,e)=>{let{mapView:r}=At(e);return U_(r)},R2=$(q_,{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:c.object({})}),B_=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."},K_=async(t,e)=>{let{mapView:r}=At(e);return await B_(r)},$2=$(K_,{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:c.object({})}),Td=750;function qs(t){return"point"in t&&t.point!==void 0}function ko(t){return"layerId"in t&&t.layerId!==void 0}var Gs=async(t,e)=>{if(qs(t)){let{point:r}=t;return{geometry:new kd({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(ko(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:Td+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Td)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]:Ed.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"}},G_=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)}}},W_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(m=>m.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let m=await Gs(o,e);if("error"in m)return m.error;i=m.geometry}if(a.featureEffect=null,a.featureEffect=new Eg({filter:new Cd({...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 G_(e,t.layerId,u,i,o?.distance,o?.units),d=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 "${d}" but no features matched. ${l.error}`},V_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],It=c.enum(V_),H_=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}=At(s);return await W_(t,a,n,o,e,r)},J_=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Z_=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.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:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Q_=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer on which to set a feature effect."),where:c.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:c.array(c.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:c.union([J_,Z_]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:c.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:c.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:c.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.")}),N2=$(H_,{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:Q_}),Y_=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Od=t=>{if(!t)return!1;let e=t.toLowerCase();return Y_.has(e)},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},X_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,ew=t=>{if(typeof t=="string"&&t)return t;let e=gi(t);return e?e.toISOString().slice(0,10):null};var tw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Od(n))return t;if(n==="date-only"){let s=ew(t);return s?Pg(s,Ds("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Og(t,Ds("long-time"));let s=gi(t);return s?Ad(s,{...Ds("long-time"),timeZone:"UTC"}):t}let o=gi(t);return o?Ad(o,{...Ds("short-date-short-time"),timeZone:X_(r)}):t},Md=(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}},Rd=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,$d=(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"?!n||Od(n)?sw(r,s,o):r:tw(r,n,o)},aw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Md(e,r,t)??r;return $d(t,e,s,o?.type,n)},iw=(t,e)=>Rd(t,e),Nd=(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 d=i[l.name];if(l.name===n){u[l.name]=d;return}let m=Md(l.name,d,t)??d,f=Rd(t,l.name);u[f]=$d(t,l.name,m,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(d=>d.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}=At(n),s=await uw(t,e,r,o);return JSON.stringify(s,null,2)}var dw=c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:c.string().describe("The name of the field/attribute from which to get a field value."),query:c.object({where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),pw=$(cw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:dw}),Ti=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function Bs(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(h=>h.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),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(a){let h=await Gs(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw ko(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(ko(a)){let x=o.map?.allLayers.find(S=>S.id===a.layerId);m={geometryLayerName:x?.title??x?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else qs(a)&&(m={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new Cd({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let I=Ti(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Bs(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await Mg(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await Rg({layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Bs(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((E,F)=>F.count-E.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(E=>({...E,value:S?S.getName(E.value)??E.value:E.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:m}}};async function fw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Dn(o,"layersAndFieldsRegistry"),{mapView:a}=At(o),i=await mw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var hw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),gw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.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:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),yw=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:c.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:c.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:c.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),_w=$(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.
150
+
151
+ USE THIS TOOL FOR:
152
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
153
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
154
+ - Questions requiring a mathematical aggregation across many features
155
+
156
+ DO NOT USE FOR:
157
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
158
+ - "Show / list / find features" \u2014 use queryFeatures instead
159
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
160
+
161
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:yw}),ww=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),bw=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let f=await Gs(n,r);if("error"in f)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.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=f.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new $g({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Ng({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=Bs(s.definitionExpression,t.where||"1=1"),b.outFields=m.length?m:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),n?.distance&&(b.distance=n.distance),n?.units&&(b.units=n.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...ww(e.orderByFields)])],h=Ti(a,y,o??!1);try{f=h?await a.queryFeatures(b):await s.queryFeatures(b)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(b)}}let I=f.features.map(b=>b.attributes[d]),{attributes:w}=Nd(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:I,objectIdField:d,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},xw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=At(o),a=await bw(t,e,s,r,n);return JSON.stringify(a,null,2)},Aw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Iw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.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:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),vw=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.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:c.union([Aw,Iw]).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:c.object({topCount:c.number().describe("Number of top features to return per group."),orderByFields:c.array(c.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:c.array(c.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:c.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).")}),Tw=$(xw,{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:vw}),hi=25,Sw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),kw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let y=await Gs(r,e);if("error"in y){let h={error:y.error};if(ko(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else qs(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!y.geometry){let h={};if(ko(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else qs(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=y.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...Sw(t.orderByFields)])],l=Ti(s,u,n??!1),d=o.objectIdField,m=o.createQuery();m.where=Bs(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],m.orderByFields=t.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,I;try{f=l?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=hi&&(I=l?await s.queryFeatures(m):await o.queryFeatures(m))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await o.queryFeatureCount(m),f>0&&f<=hi&&(I=await o.queryFeatures(m))}let{objectIds:w,attributes:b}=I?Nd(o,I,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...w&&{objectIds:w,objectIdField:d},...b&&{attributes:b},...f>hi&&{note:`${f} features found.`}}}};async function Cw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=At(n),s=await kw(t,o,e,r);return JSON.stringify(s,null,2)}var Ew=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Pw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.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:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Ow=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.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:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.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:c.union([Ew,Pw]).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:c.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).")}),Mw=$(Cw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
162
+
163
+ USE THIS TOOL FOR:
164
+ - "Show / display / list features where..." \u2014 finding and listing features
165
+ - "How many X are Y?" \u2014 counting features that match a condition
166
+ - "Which features..." / "Find features..." \u2014 identifying specific features
167
+ - Spatial queries \u2014 finding features near/within/intersecting other features
168
+ - Any question where the user wants to SEE or COUNT matching features
169
+
170
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Ow}),zd=[pw,_w,Tw,Mw];var z2=new Qe(zd,{handleToolErrors:!1});var Rw=O.Root({...lr(),helpInternalState:O({reducer:So,default:()=>({toolCallMessage:void 0})})}),$w=(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(`
171
+ `);return`**${r.layerItem.title}** has ${n.length} field(s):
172
+
173
+ ${o}`},Nw=async({layerTitle:t},e)=>{let r=Dn(e,"layersAndFieldsRegistry");return $w(r,t)},zw=$(Nw,{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:c.object({layerTitle:c.string().describe("The title or partial title of the layer to list fields for.")})}),jw=O.Root({...lr(),intent:O({reducer:(t,e)=>e}),arcgisKnowledgeMessages:O({reducer:Hn,default:()=>[]}),arcgisKnowledgeToolResult:O({reducer:(t,e)=>e,default:()=>null})});function jd(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 Fn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function Ws(t){!t||Fn(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Eo(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)&&jd(r),{view:r}}async function Un(t){let e=t?.configurable?.context;if(Lw(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 Id(n)}}else{jd(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 Id(n)}}}}function Lw(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 yi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Ks.fromDataModel(e)}},Ks=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(Co.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(_i.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Dw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
174
+ Relationship Types: ${n}.`}},Co=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=Fw(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Uw(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}},_i=class extends Co{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Co.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},Dw=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Fw=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Uw(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 Vs(t){return t?.signal}async function qw(t,e){let r=await Ye("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
175
+
176
+ Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
177
+
178
+ Attempt Number: ${e.attemptCount}
179
+ Execution Error: ${e.executionError}
180
+ Failed Query:
181
+ ${e.failedGraphQuery}`:`${t} ${r}`}async function Bw(t,e,r,n){let{graphQuery:o,explanation:s}=await Si(t,e,r,n);return{graphQuery:o,explanation:s}}async function Si(t,e,r,n,o){let s={message:await qw(t,o),context:new yi(e)},a=Vs(n);await H({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await bd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:wd.findCredential(ur.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),d=i.data.sequenceNumber,m="",f="",I=1;for(;!u;){await new Promise(b=>setTimeout(b,1e3)),await H({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,I)}`},n),I=I%3+1;let w=await bd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:wd.findCredential(ur.getDefault().url)?.token??""},signal:a});if(w.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${w.httpStatus}`,{cause:w.data});if(w.data.context?.kind){if(w.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${w.data.message}`,{cause:w.data});m=w.data.context.graphQuery,f=w.data.message||"",u=!0}else if(!w.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=w.data.sequenceNumber}return{graphQuery:m,explanation:f}}function Kw(t,e){jn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function jn(t,e){if(!(!t||typeof t!="object")){if(Ww(t))for(let r of t.path)jn(r,e);else if(Gw(t))e(t);else if(Array.isArray(t))for(let r of t)jn(r,e);else if(Vw(t))for(let r of Object.values(t.properties??{}))jn(r,e)}}function Gw(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Ww(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Vw(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=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function Jw(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let d=o.namedTypeDefinitions.get(l.name);if(!d){a=!1,n.push(l.name);continue}if(!d.useAllData){a=!1,n.push(l.name);for(let[m]of d.members||[])u.push(m)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var Ln=3;function Ld(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 qn(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 Zw=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,d=o?.signal,m=()=>{l.abort(d?.reason)};d&&(d.aborted?l.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let f=await jg(t,e,o);i=f.resultHeader;let I=f.resultRowsStream.getReader(),w=0,b=Date.now(),y=!1;for(;;){let{done:h,value:x}=await I.read();if(h)break;if(!y&&a&&Date.now()-b>a)return l.abort(),{type:"timeout"};for(let S of x){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,S)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:qn(f),error:f}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function Dd({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let d;for(let m=1;m<=Ln;m++){let f;try{f=await Si(t,r.dataModel,n,l,d)}catch(y){return{type:"generation-error",errorMessage:qn(y),error:y}}await H({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let I=await Qw(f.graphQuery,e),w=await Zw({kg:r,queryParams:new Pd({openCypherQuery:f.graphQuery,bindParameters:I}),targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),b=w.type==="aborted"?"Query execution was aborted.":w.type==="timeout"?"Query execution timed out.":w.type==="error"?`Query failed with error: ${w.errorMessage}`:"";if(w.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:w.rowLimitReached,resultHeader:w.resultHeader,processedResult:w.processedResult};if(w.type==="aborted")return{type:"aborted",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation};if(m>=Ln)return w.type==="timeout"?{type:"timeout",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:b,error:w.error,graphQuery:f.graphQuery,explanation:f.explanation};d={failedGraphQuery:f.graphQuery,executionError:b,attemptCount:m},await H({text:`Attempt ${m} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Ln} attempts.`)}var Qw=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await Fg(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},Yw=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 d=u-a.length;if(d<=0)break;let m=(await Lg(t,new Dg({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:I,value:w}=await m.read();if(I){f=!0;break}for(let b of w)for(let y of b)a.push(y)}}}catch(l){let d=qn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},Fd="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Ud({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(Fd),!Fn(e)&&e.map){let d=await Ye("arcgis_knowledge_current_lc_context"),m=Hw(e.map,r);return o.push(d),{enhancedPrompt:o.join(`
182
+
183
+ `),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=Jw(s,r);if(a)return{enhancedPrompt:o.join(`
184
+
185
+ `),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await Ye("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return o.push(l),{enhancedPrompt:o.join(`
186
+
187
+ `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function Xw(t,e,r,n,o,s){let{view:a}=o,i=await Dd({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,I)=>{for(let w of I)Kw(w,f);return f},requestOptions:{signal:Vs(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let f=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:u,explanation:l,processedResult:d}=i,m=Array.from(d.values());return await H({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Fn(a)&&a?.map?(await a.map.addRecords(m),await Ws(a),{generatedQuery:u,explanation:l,addedIdTypePairs:m}):(await a?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:u,explanation:l,addedIdTypePairs:m})}var Fs="addRecords",eb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),tb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=Eo(e),{view:o}=n,s=ur.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await Ud({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:Fs,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:d,addedIdTypePairs:m}=await Xw(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Fs,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
188
+
189
+ Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:m}}}catch(l){let d=qn(l);return{toolName:Fs,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},rb=$(tb,{name:Fs,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
190
+
191
+ example prompts:
192
+ - "add all suppliers and the parts they produce to the link chart"
193
+ - "show me the competitors of company x and add them to the link chart"
194
+ - "add the relationships between company x and company y to the link chart"
195
+ - "expand all the companies"
196
+ - "expand company x through all the buildings it owns"
197
+ - "connect company x and company y"
198
+ - "connect all buildings on the link chart"
199
+ `,schema:eb});async function nb(t,e){return await e.map?.applyLayout(t),await Ws(e),{appliedLayout:t}}var wi="applyLayout",ob=c.object({layout:c.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")}),sb=async({layout:t},e)=>{let{view:r}=Eo(e);if(Fn(r))return{toolName:wi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await nb(t,r);return{toolName:wi,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},ab=$(sb,{name:wi,description:"Apply a diagram layout to the link chart",schema:ob});async function ib(t,e){return e.map?.changeNonspatialDataDisplay(t),await Ws(e),{appliedNonspatialDataDisplayMode:t}}var bi="changeNonspatialVisibility",lb=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),ub=async({setting:t},e)=>{let{view:r}=Eo(e);if(Fn(r))return{toolName:bi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await ib(t,r);return{toolName:bi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},cb=$(ub,{name:bi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:lb});async function db(t,e,r,n,o){let s,a="";for(let i=1;i<=Ln;i++){let{graphQuery:u,explanation:l}=await Si(t,e.dataModel,r,o,s);try{await H({text:`Attempting to create link chart from derived query: ${u}`},o);let d=await zg.fromCypherQuery(e,new Pd({openCypherQuery:u}));await H({text:"Link chart created successfully, loading..."},o),await d.load();let m=n.map;return n.map=d,await n.when(),await Sd.whenOnce(()=>!n.updating),d.entityCount===0&&d.relationshipCount===0?(n.map===d&&(n.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
200
+ ${u}
201
+
202
+ Explanation: ${l}`}):(await Ws(n),{type:"success",graphQuery:u,explanation:l})}catch(d){let m=qn(d);if(i>=Ln){a=m;break}s={failedGraphQuery:u,executionError:m,attemptCount:i},await H({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Ln} attempts. Last error: ${a}`}}var Us="createLinkChart",pb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),mb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),{view:n}=Eo(e);if(Fn(n))return{toolName:Us,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=ur.getDefault().helperServices,s=await db(`${t}
203
+
204
+ ${Fd}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:Us,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:Us,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
205
+ ${a}
206
+
207
+ Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},fb=$(mb,{name:Us,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:pb}),xi="queryGraphData",hb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),gb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=ur.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Eo(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await Ud({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await Dd({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,y)=>(b.push(y),b),requestOptions:{signal:Vs(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let b=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:xi,status:"error",errorMessage:`Failed to query the knowledge graph. ${b}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:d,resultHeader:m}=i,f=m.headerKeys;for(let b of d)for(let y of b)jn(y,h=>Ld(h));let I=50,w=d.slice(0,I).map(b=>JSON.stringify(b));return{toolName:xi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
208
+
209
+ \`\`\`cypher
210
+ ${u}
211
+ \`\`\`
212
+
213
+ Query Results:
214
+ ${w.length} result(s) found.
215
+
216
+ Column Headers: ${f.join(", ")}
217
+
218
+ ${w.length>I?`Showing top ${I} results:
219
+
220
+ `:`Results:
221
+
222
+ `}${w.join(`
223
+ `)}
224
+ `,details:{generatedQuery:u,explanation:l,resultHeader:m,queryResults:d}}},yb=$(gb,{name:xi,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:hb}),Ai="generateCypher",_b=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),wb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=ur.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await Bw(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Ai,status:"success",summary:`Generated Graph Query:
225
+ ${o}
226
+
227
+ Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=qn(o);return{toolName:Ai,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},bb=$(wb,{name:Ai,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:_b}),xb=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 d=r.get(u)??new Set;l.propertyNames.forEach(m=>d.add(m)),r.set(u,d)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
228
+ ${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
229
+ `)}`,a=`Relationship Types:
230
+ ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
231
+ `)}`;return`${s}
232
+
233
+ ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:xb(e)},s=c.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=c.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=c.array(c.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=c.object({query:c.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await To({promptText:n,inputVariables:o,schema:u,config:r})}var Ii="searchGraphData",Ib=c.object({prompt:c.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.")}),vb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e);await H({text:"Generating search query for the user inquiry"},e);let n=await Ab(t,r,e);await H({text:"Executing graph search with generated search query"},e);let o=await Yw({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:Vs(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Ii,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)jn(i,u=>Ld(u));let s=10,a=o.results.slice(0,s);return{toolName:Ii,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
234
+ Query: ${n.query}
235
+ Type Category Filter: ${n.typeCategoryFilter}
236
+ Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
237
+ Result Limit: ${n.resultLimit??"No limit"}
238
+
239
+ Search Results: ${o.results.length} result(s) found.
240
+
241
+ ${o.results.length>s?`Showing top ${s} results:
242
+
243
+ `:""}${a.map(i=>JSON.stringify(i)).join(`
244
+ `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},Tb=$(vb,{name:Ii,description:`
245
+ Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
246
+ Example prompts:
247
+ - "Find 'Bradley'"
248
+ - "find the person john smith"
249
+ - "find all people named smith"
250
+ - "Find all references to 'delayed parts shipment'"
251
+ - "Find all reports authored by someone with the title of 'Researcher'"
252
+ - "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
253
+ - "Search for all john smiths and show their global ids`,schema:Ib});var X2=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
254
+ This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
255
+
256
+ Supported actions:
257
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
258
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
259
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
260
+ - **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
261
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
262
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
263
+ - **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
264
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
265
+
266
+ _Example: “Zoom to Texas”_
267
+ _Example: “Go to the water mains layer”_
268
+ _Example: “Zoom to to the extent of my link chart”_
269
+ _Example: “Center the map on San Francisco at scale 50000”_
270
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
271
+ _Example: “Go to the Downtown bookmark”_
272
+ _Example: “Where is Mount Rainier?”_`;var EW=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
273
+ _Example: “Color points by sales amount”_
274
+ _Example: “Show population density with a color gradient”_
275
+ _Example: “Create a relationship map between height and depth”_
276
+ _Example: “Vary circle sizes according to population”_`;var XW=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
277
+ The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
278
+ _Example: “Only show stations where Brand is Shell”_
279
+ _Example: “Make Shell stations stand out on the map”_
280
+ _Example: “Gray out all stations that aren’t Shell”_
281
+ This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
282
+ _Example: “How many features are there?”_
283
+ _Example: “What’s the average population?”_
284
+ _Example: “Which values are in the status field?”_
285
+
286
+ This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var gV=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
287
+
288
+ _Example: “Tell me about this map”_
289
+ _Example: “List all layers in this map”_
290
+ _Example: “List fields in protected areas layer”_
291
+ _Example: “What agents are available to me?”_
292
+ _Example: “What can you do?”_
293
+ _Example: “What can I ask”_
294
+
295
+ If the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent so it can politely refuse and redirect to map-related questions.
296
+
297
+ IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
298
+ _Example: "Create a chart"_
299
+ _Example: "Create a table"_`;var $V=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
300
+ This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
301
+ For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
302
+ expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
303
+ that exist out from specified entities and adding those to the link chart, changing whether or not nonspatial data is visible, or changing the layout of the link chart.
304
+ This agent is designed to handle requests that manipulate the specific link chart.
305
+ For knowledge graph data more generally, the agent can generate Open Cypher queries based on user prompts that represent inquiries into the data of the knowledge service and its graph database,
306
+ and can alternatively use those queries to create a new link chart visualization from the results if requested.
307
+
308
+ Supported actions:
309
+ - **Change or Apply Layout**: Changes the current layout visualization strategy of the link chart (e.g., "Change the layout to basic-grid", "Apply hierarchical layout"). Valid layout types include organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline. A best effort should be made to transform the user's request into one of these layout types.
310
+ - **Change Nonspatial Data Visibility**: Changes whether or not nonspatial data is visible on the link chart (e.g., "Show nonspatial data", "Hide nonspatial data"). Valid settings are "hidden" and "visible". A best effort should be made to transform the user's request into one of these settings.
311
+ - **Generate a cypher query**: Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance. The user should explicitly request that a cypher query be returned - if they do not, the purpose of the query is for one of the other tools or skills.
312
+ - **Create a New Link Chart from a user prompt**: Identifies that the users prompt is an inquiry into the data of the knowledge service and its graph database and creates a new link chart from the results. The user should have requested that a link chart be created or made(or similar term) from their prompt
313
+ - **Add Records (entities or relationships)**: Identifies that the users prompt is an inquiry into the data of the knowledge graph service and its graph database, and that the user wants to take the result of the inquiry and add those entities and/or relationships to the link chart. The generated query should be syntactically correct and optimized for performance.
314
+ - **Search Graph Data**: Generates and runs a lucene syntax query based on the user's prompt, returning matching entity and relationship records from the knowledge graph.
315
+ - **Query Graph Data**: Generates and executes a cypher query based on the user's prompt, and displays the results in the chat pane, allowing the user to explore the data in their knowledge graph.
316
+
317
+ _example: "Change the layout to hierarchical-bottom-to-top"_
318
+ _example: "Apply radial-root-centric layout"_
319
+ _example: "Show nonspatial data"_
320
+ _example: "Hide nonspatial data"_
321
+ _example: "Turn off nonspatial visibility"_
322
+ _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
323
+ _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
324
+ _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
325
+ _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
326
+ _example: "Find all people who work for Microsoft and put them on a new link chart"_
327
+ _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
328
+ _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
329
+ _example: "Find all the products supplied by Supplier X and add them to my visualization"_
330
+ _example: "Expand the link chart from 'Entity D' to show its direct connections"_
331
+ _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
332
+ _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
333
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
334
+ _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
335
+ _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
336
+ _example: "Find John Smith and all people he has made phone calls to in the last year"_
337
+ _example: "What is the average age of all people who work for Esri?"_`;var Xe=To;var ce=H;var Oo=()=>Ls(),Js=async(t,e)=>await me(t,e),Zs=async({modelTier:t="default",temperature:e=0,config:r}={})=>await mi({modelTier:t,temperature:e,config:r});var Yd=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function cr(t){if(!Yd(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Eb=`
338
+ Write a concise, friendly success message for adding members to a group.
339
+
340
+ Rules:
341
+ - Keep it to 1-2 short sentences.
342
+ - Use plain text only.
343
+ - If there is no notAddedMembers, confirm that all requested members were added successfully.
344
+ - If there are notAddedMembers, acknowledge that some members could not be added and list the added and not added members separately then mention why based on the context
345
+ - Make sure to bold the usernames
346
+
347
+ Added members:
348
+ {addedMembers}
349
+
350
+ Not added members:
351
+ {notAddedMembers}
352
+ `,Pb=t=>t.map(e=>`"${e}"`).join(", "),Ob=c.object({successMessage:c.string().default("")}),Kd="portal-group-creation",Gd="approveAddMembers",Mb=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(m=>m.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:
353
+
354
+ ${n.map(m=>`- **@${m}**`).join(`
355
+ `)}
356
+
357
+ Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Kd||s.id!==Gd){let m={agentId:Kd,id:Gd,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new Ro(m)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ce({text:`Adding members ${Pb(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;cr(a);let{result:i,error:u}=await cl(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:d}=i;try{let m=(await Xe({promptText:Eb,schema:Ob,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(m)return{status:"success",outputMessage:m}}catch(m){console.error("Error generating add-members success message:",m)}return{}},Rb=`
358
+ Write a concise, friendly success message after creating a portal group.
359
+
360
+ Rules:
361
+ - Mention that the group was created successfully.
362
+ - Mention that the user can add members by using @mention usernames.
363
+ - Keep it to 1-2 short sentences.
364
+ - Make sure to bold the group title in the message.
365
+
366
+ Group title:
367
+ {groupTitle}
368
+ `,$b=`
369
+ Write a concise, friendly failure message after an attempt to create a portal group.
370
+
371
+ Rules:
372
+ - Keep it to 1-2 short sentences.
373
+ - Use plain text only.
374
+ - Mention that group creation failed.
375
+ - Include the failure reason in user-friendly language.
376
+ - End with a clear next step the user can try.
377
+
378
+ Group title:
379
+ {groupTitle}
380
+
381
+ Failure reason:
382
+ {failureReason}
383
+ `,Wd="portal-group-creation",Vd="approveCreateGroup",Nb=c.object({successMessage:c.string().default("")}),zb=c.object({failureMessage:c.string().default("")}),jb=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!==Wd||o.id!==Vd){let l={agentId:Wd,id:Vd,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new Ro(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ce({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;cr(s);let{result:a,error:i}=await ul(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let d=(await Xe({promptText:$b,schema:zb,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(d)return{status:"success",outputMessage:d}}catch(d){console.error("Error generating create-group failure message:",d)}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 Xe({promptText:Rb,schema:Nb,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{}},dr=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""},Lb=`
384
+ You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
385
+
386
+ Rules:
387
+ - Set intent="create" when the user asks to create a group and a title can be identified.
388
+ - Set intent="addMembers" when the user asks to add one or more members to a group.
389
+ - Set intent="clarify" when required data is missing or the request is ambiguous.
390
+ - For create requests, extract title only.
391
+ - For add-members requests, extract memberIdentifiers as ArcGIS usernames only (no @ prefix), but if you're returning a hint text asking for missing members, include the @ prefix.
392
+ - If the user includes mentions like @jsmith, return "jsmith" in memberIdentifiers.
393
+ - Do not extract group ids or group titles; add-members is a follow-up action that targets the most recently created group.
394
+ - When intent="clarify", provide a concise clarifyMessage describing exactly what is missing.
395
+ - If the user gives the title in quotes, extract exactly that title.
396
+ - If the user says create group <title> without quotes, extract only the title text after the create-group wording.
397
+ - If the user message looks like only a potential title (short phrase, not a question), treat it as the title and set intent="create".
398
+ - Return only extracted values. Do not add helper text into title or memberIdentifiers.
399
+ - Make sure to match the user's tone and texting style
400
+
401
+ Examples:
402
+ - help me create a new group "<title>" => intent="create", title="<title>", memberIdentifiers=[]
403
+ - add @<username1> and @<username2> => intent="addMembers", memberIdentifiers=["<username1>","<username2>"]
404
+ - add <member> => intent="addMembers", memberIdentifiers=["<member>"]
405
+ - help me create a new group => intent="clarify" with a question for missing title
406
+
407
+ User message:
408
+ {userMessage}
409
+ `,Db=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),Fb=async(t,e)=>{await ce({text:"Thinking about groups...",agentName:"group-creation"},e);let r=dr(t.agentExecutionContext.messages).trim(),n=await Xe({promptText:Lb,schema:Db,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:""}},Ub=c.enum(["portal-content","portal-content-favorites","portal-content-group","portal-content-living-atlas","portal-content-organization","portal-gallery","portal-groups","portal-groups-featured","portal-groups-my","portal-groups-organization","portal-map-viewer","portal-notebooks","portal-scene-viewer","portal-settings-security"]),qb=c.object({destinationType:Ub}),Bb=c.union([qb,c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1)})]),Xd="portal-navigation",Oi=async(t,e)=>{let r=e?.configurable?.context;!Yd(r)||!r.navigationTargetMap?.[t.destinationType]||await Js({type:Xd,data:{...t}},e)},Kb=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ce({text:"Preparing navigation...",agentName:"group-creation"},e),await Oi({destinationType:"portal-group",groupId:r},e),{}):{}},Hd=(t,e)=>e??t,ep=O.Root({...Oo(),intentParams:O({reducer:Hd,default:()=>({intent:"clarify"})}),createdGroupId:O({reducer:Hd,default:()=>""})}),Gb=()=>new pe(ep).addNode("detectGroupCreationIntent",Fb).addNode("createPortalGroup",jb).addNode("addMembersToPortalGroup",Mb).addNode("suggestCreatedGroupNavigation",Kb).addEdge(de,"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),Wb=String.raw`- **portal-group-creation** - Portal group creation assistant:
410
+ - creates a new ArcGIS Portal group for the signed-in user
411
+ - adds users to the newly created group using @mention usernames
412
+ `,Vb={id:"portal-group-creation",name:"Portal Group Creation",description:Wb,createGraph:Gb,workspace:ep},tp="portalDocAssistantMemory",Hb=()=>({conversationId:""}),Jb=t=>{let e=t?.[tp]?.value;if(!e||typeof e!="object")return Hb();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Zb=t=>({[tp]:{value:t}});async function Qb({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await Yb({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:Xb(a,s),conversationId:a[0]?.conversationId??""}}async function Yb({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Cb.findCredential(t.url)?.token??""},a=await Bd(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:d}=i,m=async(f,I)=>{if(!I)return;await Ui(1e3);let w=await Bd(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:d,ackSequenceNumber:f}),headers:s,signal:n.signal});if(w.httpStatus!==200)throw new Error(`Doc assistant poll failed (${w.httpStatus})`,{cause:w.data});let b=w.data;u.push(b),await m(b.sequenceNumber,b.hasMore)};return i.hasMore&&await m(i.sequenceNumber,i.hasMore),u}function Xb(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 Gn(e)}}var ex=async(t,e)=>{await ce({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=dr(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;cr(n);let o=Jb(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Qb({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:Zb({conversationId:a||o.conversationId})}},rp=$(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;cr(n);try{return(await ll(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:c.object({groupTitle:c.string().describe("The portal group title to resolve to a group id.")})}),np=$(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;cr(n);let{result:o,error:s}=await dl(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:c.object({itemTitle:c.string().describe("The portal item title to resolve to an item id.")})});function Mo(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let n=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return n?.[1]?n[1].trim():null}var op={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"],scope:"root"},"portal-content-favorites":{description:"The My favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"],scope:"collection"},"portal-content-group":{description:"The My groups view under Content in the portal.",hints:["Content my groups","My groups content","Group content"],scope:"collection"},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content Living Atlas"],scope:"collection"},"portal-content-organization":{description:"The My organization view under Content in the portal.",hints:["My organization content","Organization content","Content organization"],scope:"collection"},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"],scope:"collection"},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"],scope:"entity"},"portal-groups":{description:"The groups listing page of the portal.",hints:["My groups","Groups"],scope:"collection"},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"],scope:"collection"},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"],scope:"collection"},"portal-groups-organization":{description:"The My organization's groups view under Groups in the portal.",hints:["Organization's groups","My organization's groups","Groups organization"],scope:"collection"},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"],scope:"entity"},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"],scope:"entity"},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"],scope:"collection"},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"],scope:"entity"},"portal-settings-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],scope:"entity"}},tx=qi(op),rx=Object.entries(op).map(([t,{description:e,hints:r,scope:n}])=>` - ${t}: ${e} (scope: ${n}; hints: ${r.join(", ")})`).join(`
413
+ `),nx=`
414
+ You decide whether the assistant response should include a navigation action to ArcGIS Portal.
415
+
416
+ Given the user question and assistant response:
417
+ - Decide if a navigation action would help the user complete the task.
418
+ - If yes, choose one destination type:
419
+ ${rx}
420
+
421
+ Rules:
422
+ - Only suggest navigation when you are highly confident the destination will help complete the user's task.
423
+ - If confidence is below 0.85, set shouldSuggestNavigation=false and destinationType=none.
424
+ - If there is no clear destination from the allowed types, set shouldSuggestNavigation=false and destinationType=none.
425
+ - If no navigation is useful, set shouldSuggestNavigation=false and destinationType=none.
426
+ - Prefer the most specific destination that is clearly supported by the question and response.
427
+ - Use entity-level destinations over collection/root destinations when both could apply and the entity target is explicit.
428
+ - Use collection/root destinations only for generic browsing intent with no specific entity target.
429
+ - If a chosen destination requires parameters, include all required parameters.
430
+ - If required parameters are missing or uncertain, set shouldSuggestNavigation=false and destinationType=none.
431
+ - Do not invent required parameters.
432
+ - Always include a confidence score from 0 to 1 in the output.
433
+ - Confidence means confidence that a navigation suggestion should be shown to the user.
434
+ - If shouldSuggestNavigation=false or destinationType=none, confidence must be <= 0.5.
435
+ - Use confidence >= 0.85 only when shouldSuggestNavigation=true and destinationType is not none.
436
+
437
+ User question:
438
+ {question}
439
+
440
+ Assistant response:
441
+ {response}
442
+ `,Jd=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...tx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),ox=async(t,e)=>{await ce({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=dr(t.agentExecutionContext.messages).trim(),o=await fr.fromTemplate(nx).format({question:n,response:r}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Jd),a=Jd.parse(await s.invoke(o));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Mo(n,"#");u&&(a.itemId=await np.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Mo(n,"$")??Mo(n,"#");u&&(a.groupId=await rp.invoke({groupTitle:u},e)??"")}let i=sx(a);return i?(await Oi(i,e),{}):{}};function sx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":case"portal-gallery":case"portal-groups":case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":case"portal-settings-security":return{destinationType:t};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 Gn(t)}}var sp=O.Root({...Oo()}),ax=()=>new pe(sp).addNode("answerDocQuestion",ex).addNode("extractNavigationIntent",ox).addEdge(de,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",B),ix=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
443
+ - answers general ArcGIS, Portal, Enterprise, and JavaScript SDK questions
444
+ - acts as a fallback when specialized agents are not applicable
445
+ `,lx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:ix,createGraph:ax,workspace:sp},ux=()=>({latestGroupId:null,memory:{}}),Qs=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:ux()},ap=`
446
+ Shared markdown formatting rules:
447
+ - Use clear markdown headings (##) to separate sections.
448
+ - Use concise bullet points for lists of facts, counts, or signals.
449
+ - Emphasize key metrics with bold labels (for example: **Recent items:** 4).
450
+ - Keep wording direct and analytical; avoid filler language but make sure the language is friendly.
451
+ - Do not include raw internal IDs unless explicitly requested.
452
+ `,cx=`
453
+ You answer follow-up questions about ArcGIS group analytics.
454
+
455
+ ${ap}
456
+
457
+ Ground your answer in the provided group analytics summary and context.
458
+ If the answer is not available from the provided context, state that clearly and suggest what to check next.
459
+
460
+ Response rules:
461
+ - Reply in concise markdown with this section structure:
462
+ 1) ## Answer
463
+ 2) ## Evidence
464
+ 3) ## Gaps (only when data is missing)
465
+ - Keep the answer focused on the follow-up question.
466
+ - Do not include internal identifiers.
467
+ - Mark isRelevant=false when the question is not about this group or cannot be grounded in this group context.
468
+
469
+ Group analytics summary:
470
+ {summary}
471
+
472
+ Group full context:
473
+ {fullContext}
474
+
475
+ Question:
476
+ {question}
477
+ `,dx=async(t,e)=>{await ce({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=Qs(t),n=t.groupSummaryGroupId??r.latestGroupId,o=n?r.memory[n]:void 0,s=t.groupSummaryQuestion||dr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Xe({promptText:cx,schema:px,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>."}},px=c.object({answer:c.string(),isRelevant:c.boolean()}),mx=`
478
+ Classify the user's request for ArcGIS Portal group analytics.
479
+
480
+ Rules:
481
+ - intent="summarize" only when the user explicitly asks to summarize, analyze, overview, or recap a group.
482
+ - intent="followUp" for follow-up questions about a previously analyzed group.
483
+ - intent="navigation" when the user asks to open, go to, navigate to, or view the group page.
484
+ - intent="clarify" when intent or required group target is missing.
485
+ - groupId must be the final resolved group id.
486
+ - If request has explicit group id, set groupId directly.
487
+ - 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.
488
+ - Never return group titles in output fields.
489
+ - If intent is "followUp", set question to the user's full question/request text.
490
+ - If intent is "navigation", set question="".
491
+ - If intent is "summarize", set question="".
492
+ - If intent is "navigation" and no group is specified, leave groupId empty so the system can navigate to the groups listing page.
493
+ - If hasAnalyticsContext is true and the user asks about the same group context without an explicit summarize/analyze command, prefer "followUp".
494
+
495
+ Examples:
496
+ - "Analyze group 0123456789abcdef0123456789abcdef" => summarize, groupId="0123456789abcdef0123456789abcdef"
497
+ - "Analyze group $living atlas" => summarize, call resolvePortalGroupIdByTitle("living atlas") and set groupId to tool result
498
+ - "Analyze group $"living atlas basemaps"" => summarize, call resolvePortalGroupIdByTitle("living atlas basemaps") and set groupId to tool result
499
+ - "Is this group active?" with hasAnalyticsContext=true => followUp
500
+
501
+ hasAnalyticsContext:
502
+ {hasAnalyticsContext}
503
+
504
+ User message:
505
+ {userMessage}
506
+ `,fx=async(t,e)=>{await ce({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=dr(t.agentExecutionContext.messages),n=!!Qs(t).latestGroupId,o=await fr.fromTemplate(mx).format({userMessage:r,hasAnalyticsContext:String(n)}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Zd),a=Zd.parse(await s.invoke(o)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let I=Mo(r,"$");I&&(i=await rp.invoke({groupTitle:I},e)??"")}let{intent:u,question:l}=a,d=u==="summarize"&&!i,m=u==="followUp"&&!(l??"").trim(),f=u==="clarify"||d||m;return{groupSummaryIntent:f?"clarify":u,groupSummaryGroupId:i||null,groupSummaryQuestion:l||"",status:"success",outputMessage:f?"Please clarify with a group id or title":""}},Zd=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),hx=async(t,e)=>{let r=Qs(t),n=t.groupSummaryGroupId??r.latestGroupId;return await ce({text:"Preparing navigation...",agentName:"group-analytics"},e),await Oi(n?{destinationType:"portal-group",groupId:n}:{destinationType:"portal-groups"},e),{status:"success"}};function ip({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var gx=720*60*60*1e3;function yx(t){let e=ml(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:fl(t),membershipAccess:hl(t),isOpenData:gl(t),isDistributedCollaborationGroup:yl(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function _x(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 wx(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 bx(t,e){return t.filter(r=>r.modified?ip({timestamp:r.modified,now:e,windowMs:gx}):!1)}function xx(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 Ax(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=wx(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:bx(r,n),topItemTypes:xx(r)}}async function Ix(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=yx(r),o=await _x(r),s=await Ax(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 vx=`
507
+ You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
508
+
509
+ ${ap}
510
+
511
+ Output format requirements:
512
+ - Return concise markdown with clear sections in this order:
513
+ 1) Overview
514
+ 2) Activity
515
+ 3) Members
516
+ 4) Content Theme
517
+ 5) Contribution Model
518
+ 6) Unknowns / Data Gaps
519
+ - Keep total response about 180-280 words unless the user asked for extra detail.
520
+ - Avoid internal-only implementation details and do not expose raw IDs unless user explicitly asks.
521
+
522
+ Reasoning rules:
523
+ - Use deterministicSignals as the source of truth for active/recent status.
524
+ - If group description/snippet are empty, infer purpose from tags, item title patterns, and item type distribution.
525
+ - For members, report owner/admin/user counts when available; if unavailable due to permission scope, explicitly say so.
526
+ - For contribution model, use membershipAccess, capabilities, and sourceJSON flags to characterize collaboration vs distribution behavior.
527
+ - Be explicit when signals are heuristic or unavailable.
528
+
529
+ Follow-up prompt rules:
530
+ - Generate exactly 3 follow-up prompts.
531
+ - Write them as direct first-person user chat prompts that can be clicked and sent as-is.
532
+ - Do not write meta-questions such as "Would you like..." or "Do you want me to...".
533
+ - Keep each prompt short, specific, and actionable.
534
+ - Every prompt must be answerable using only the provided group context and deterministic signals.
535
+ - Do not require external data, navigation, or additional fetches.
536
+ - Tailor each prompt to this specific group's available signals (content mix, activity, members, and contribution model).
537
+ - Avoid repeating phrasing from prior prompts or using generic template wording.
538
+ - If a signal is unavailable (for example members), do not ask follow-ups that depend on that missing signal.
539
+
540
+ Group context:
541
+ {context}
542
+
543
+ Deterministic signals:
544
+ {deterministicSignals}
545
+ `,Tx=2160*60*60*1e3,Sx=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 ce({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let n=e?.configurable?.context;cr(n);let{result:o,error:s}=await Ix(n.portal,r);if(s||!o)return await ce({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,d=l?ip({timestamp:l,now:u,windowMs:Tx}):!1,m=i.recentlyModifiedItems.length,f=m>0,I=d||f,w=await Xe({promptText:vx,schema:kx,modelTier:"default",inputVariables:{context:JSON.stringify(o),deterministicSignals:JSON.stringify({isGroupActive:I,isGroupRecentlyModified:d,hasRecentlyAddedOrUpdatedContent:f,recentItemCount:m})}}),{followUpQuestions:b,summary:y}=w,h=Qs(t),x={latestGroupId:r,memory:{...h.memory,[r]:{summary:y,followUpQuestions:b,fullContext:o}}};return b.length&&await Js({type:"suggested-prompts",data:{prompts:b}},e),{status:"success",outputMessage:y,sharedStatePatch:{portalGroupSummaryMemory:{value:x}}}},kx=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Ci=(t,e)=>e??t,lp=O.Root({...Oo(),groupSummaryIntent:O({reducer:Ci,default:()=>"clarify"}),groupSummaryGroupId:O({reducer:Ci,default:()=>null}),groupSummaryQuestion:O({reducer:Ci,default:()=>""})}),Cx=()=>new pe(lp).addNode("detectGroupSummaryIntent",fx).addNode("summarizePortalGroup",Sx).addNode("answerGroupSummaryFollowUp",dx).addNode("suggestGroupSummaryNavigation",hx).addEdge(de,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":B).addEdge("summarizePortalGroup",B).addEdge("answerGroupSummaryFollowUp",B).addEdge("suggestGroupSummaryNavigation",B),Ex=String.raw`- **portal-group-analytics** - Portal group analytics assistant:
546
+ - summarizes ArcGIS portal groups from group context and sourceJSON details
547
+ - answers follow-up questions grounded in the summarized group
548
+ - suggests navigation to groups when relevant
549
+ `,Px={id:"portal-group-analytics",name:"Portal Group Analytics",description:Ex,createGraph:Cx,workspace:lp},Ox=()=>({latestItemId:null,memory:{}}),Mi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Ox()},Qd=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),Mx=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Rx=c.object({answer:c.string(),isRelevant:c.boolean()}),$x=`
550
+ You answer follow-up questions about an ArcGIS item.
551
+
552
+ Ground your answer in the provided item context.
553
+ If the answer is not available from the provided context, state that clearly and suggest what to check next.
554
+
555
+ Response rules:
556
+ - Reply in concise markdown.
557
+ - Keep the answer focused on the follow-up question.
558
+ - Do not include internal identifiers.
559
+ - Mark isRelevant=false when the question is not about this item or cannot be grounded in this item context.
560
+
561
+ Item summary:
562
+ {summary}
563
+
564
+ Item full context
565
+ {fullContext}
566
+
567
+ Question:
568
+ {question}
569
+ `,Nx=async(t,e)=>{await ce({text:"Answering follow-up...",agentName:"analytics"},e);let r=Mi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||dr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Xe({promptText:$x,schema:Rx,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>."}},zx=`
570
+ Classify the user analytics request.
571
+
572
+ Rules:
573
+ - intent="summarize" only when the user explicitly asks to summarize/overview/recap an item.
574
+ - intent="followUp" for analytical questions about item details, including schema/fields/attributes/layers.
575
+ - intent="clarify" when neither summarize nor follow-up intent is clear.
576
+ - itemId must be the final resolved item id.
577
+ - If request has explicit item id, set itemId directly.
578
+ - If request references item title (for example #title, #"title with spaces", or plain quoted title), call resolvePortalItemIdByTitle and set itemId to the returned value.
579
+ - Never return item titles in output fields.
580
+ - If intent is "followUp", set question to the user's full question/request text.
581
+ - If intent is "summarize", set question="".
582
+ - When user asks to show/list/explain fields, schema, attributes, columns, or layer details, classify as "followUp" unless they explicitly request a summary.
583
+ - If hasSummaryContext is true, prefer "followUp" for detail-oriented requests that do not explicitly ask to summarize.
584
+
585
+ Examples:
586
+ - "Summarize item 0123456789abcdef0123456789abcdef" => summarize, itemId="0123456789abcdef0123456789abcdef"
587
+ - "Summarize item #california" => summarize, call resolvePortalItemIdByTitle("california") and set itemId to tool result
588
+ - "Summarize item #"california farmland"" => summarize, call resolvePortalItemIdByTitle("california farmland") and set itemId to tool result
589
+ - "Show the layer's available fields" => followUp
590
+ - "List attributes and explain what status means" => followUp
591
+ - "What fields are available?" with hasSummaryContext=true => followUp
592
+ - "Give me an overview of item 0123456789abcdef0123456789abcdef" => summarize
593
+
594
+ hasSummaryContext:
595
+ {hasSummaryContext}
596
+
597
+ User message:
598
+ {userMessage}
599
+ `,jx=async(t,e)=>{await ce({text:"Analyzing intent...",agentName:"analytics"},e);let r=dr(t.agentExecutionContext.messages),n=!!Mi(t).latestItemId,o=await fr.fromTemplate(zx).format({userMessage:r,hasSummaryContext:String(n)}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Qd),a=Qd.parse(await s.invoke(o)),i=a.itemId;if(a.intent==="summarize"&&!i){let m=Mo(r,"#");m&&(i=await np.invoke({itemTitle:m},e)??"")}let{intent:u,question:l}=a,d=u==="clarify"||u==="summarize"&&!i||u==="followUp"&&!l;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:d?"clarify":u,analyticsItemId:i||null,analyticsQuestion:l||"",status:"success",outputMessage:d?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Lx=`
600
+ You are a item summary tool for ArcGIS. Your job is to summarize an item's info based on the provided context.
601
+ Summary rules:
602
+ - The summary should be concise markdown, make sure to format the output nicely so it's easy to read.
603
+ - Target length: 80-150 words.
604
+ - Provide one short descriptive paragraph.
605
+ - Also propose 3 concise follow-up questions grounded in the item summary.
606
+ - Keep follow-up questions specific and actionable.
607
+ Follow-up questions rules:
608
+ - These questions should be in the format of a prompt that the user can click on.
609
+ - Make sure the questions are relevant to the item summary and that you can answer based solely on the provided context.
610
+ Do not include internal identifiers.
611
+ If the user asks for a detailed summary, you may expand the response up to 300 words.
612
+ Item context:
613
+ {context}
614
+ `,Dx=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 ce({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;cr(n);let{portal:o,user:s}=n,{result:a,error:i}=await pl(s,o,r);if(i||!a)return await ce({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 Xe({promptText:Lx,schema:Mx,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:m}=l,f=Mi(t),I={latestItemId:r,memory:{...f.memory,[r]:{summary:m,followUpQuestions:d,fullContext:u}}};return d.length&&await Js({type:"suggested-prompts",data:{prompts:d}},e),{status:"success",outputMessage:m,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:I}}}},Ei=(t,e)=>e??t,up=O.Root({...Oo(),analyticsIntent:O({reducer:Ei,default:()=>"clarify"}),analyticsItemId:O({reducer:Ei,default:()=>null}),analyticsQuestion:O({reducer:Ei,default:()=>""})}),Fx=()=>new pe(up).addNode("detectAnalyticsIntent",jx).addNode("summarizePortalItem",Dx).addNode("answerAnalyticsFollowUp",Nx).addEdge(de,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":B).addEdge("summarizePortalItem",B).addEdge("answerAnalyticsFollowUp",B),Ux=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
615
+ - answers questions about one specific ArcGIS portal item when item context is present
616
+ - summarizes item details, metadata, and context grounded in that item
617
+ - suggests follow-up prompts grounded in the same item
618
+ - use for item-specific requests, not for gallery browsing, featured content, or opening Map Viewer
619
+ `,qx={id:"portal-item-analytics",name:"Portal Item Analytics",description:Ux,createGraph:Fx,workspace:up},Bx=Ni`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`;function Kx(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":case"portal-gallery":case"portal-groups":case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":case"portal-settings-security":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId);default:return Gn(r)}}function Gx(t){let e=Bb.safeParse(t);return e.success?e.data:void 0}var Pi=class extends Di{constructor(){super(...arguments),this.t9n=Bi({blocking:!0}),this.assistantEl=Bn(),this.formEl=Bn(),this.voiceInputEl=Bn(),this.inputEl=Bn(),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=ji()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,defaultClosed:5}}static{this.styles=Bx}getNavigationAction(e){if(e?.type!==Xd)return;let r=Gx(e.data);if(!r)return;let n=Kx(r,this.navigationTargetMap);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),zi(pr`<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?pr`<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-content-favorites":return r.openContentFavorites;case"portal-content-group":return r.openContentGroup;case"portal-content-living-atlas":return r.openContentLivingAtlas;case"portal-content-organization":return r.openContentOrganization;case"portal-gallery":return r.openGallery;case"portal-groups":return r.openGroups;case"portal-groups-featured":return r.openGroupsFeatured;case"portal-groups-my":return r.openGroupsMy;case"portal-groups-organization":return r.openGroupsOrganization;case"portal-map-viewer":return r.openMapViewer;case"portal-notebooks":return r.openNotebooks;case"portal-scene-viewer":return r.openSceneViewer;case"portal-settings-security":return r.openOrganizationSettingsSecurity;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return Gn(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return pr`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:l})=>{this.interrupt=l}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:l})=>{this.inputText=l.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${Kn(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${l=>{l.preventDefault();let d=r.trim();d&&(this.assistantEl.value?.submitMessage(d),this.inputText="")}} ${Kn(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:l})=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:l})=>{this.inputText=l??""}} ${Kn(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${l=>{l.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${l=>{this.inputText=l.detail.text}} ${Kn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&pr`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let l=this.voiceInputEl.value;i?await l?.stopListening():await l?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${qx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Vb} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${lx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Px} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>${this.interrupt&&pr`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:l})=>{this.assistantEl.value?.submitInterrupt(l)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};Fi("arcgis-portal-ai-assistant",Pi);return Pi},"identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","request",a,b,c)