@arcgis/portal-components 5.2.0-next.73 → 5.2.0-next.74

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,660 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import c from"./55FL7WQV.js";import b from"./A4AA5T6M.js";import{a as Gl,c as Vl,e as Wl,f as Hl,g as Jl}from"./UZCHLKLO.js";import a from"./F3ODJVJC.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as en,b as _l,d as Fn}from"./2GBRZSEC.js";import{a as wl}from"./W3UBNVKL.js";import"./QZD2UBOW.js";import"./JVGCIDQW.js";import{K as Yo,L as Xo,M as gl,S as yl,h as pl,j as ve,n as ml,w as fl,z as hl}from"./6BUBZ7WC.js";import{$ as wa,Aa as zl,Ca as Ll,Cb as on,Da as Yn,Ea as Xn,Fa as jl,Ga as br,Gb as es,Ha as Ar,Hb as ts,Ia as v,Ib as ce,J as Al,Ja as E,K as ge,Ka as Ia,L as Et,La as va,M as xl,Ma as Ta,N as Il,O as Bn,P as ga,Q as ya,R as Kn,S as tn,T as B,U as _a,V as F,W as st,Wa as M,X as at,Y as Gn,Z as vl,_ as Tl,a as ue,aa as Vn,b as K,ba as Sl,ca as Cl,da as rn,ea as Wn,fa as kl,g as bl,ga as El,ha as Ml,ia as Hn,j as Be,ja as Pl,k as kt,ka as Mt,la as ba,ma as Jn,na as $,oa as A,pa as Pt,pb as Dl,qa as it,ra as Ol,s as Un,sa as Zn,ta as Rl,ua as Nl,va as Qn,wa as Aa,xa as wr,y as qn,ya as xa,za as $l}from"./JCYCRSPL.js";import"./UZLQALHY.js";export default $arcgis.t(([ZV,YV,Ld,jd,dy,py,vy,nW,aW,bZ,WA,pp,Wo,mp,,yp,,{createRenderer:C_},{getSchemesByTag:k_,getSchemes:E_},{getBackgroundColorTheme:fp},{createAgeRenderer:M_,createContinuousRenderer:P_},{getSchemesByTag:Zi},{createContinuousRenderer:O_},{createRenderer:R_},{getSchemesByTag:N_},{createRenderer:$_},{getSchemesByTag:z_},{createRenderer:L_},{getSchemesByTag:j_},{createRenderer:D_},{getSchemesByTag:F_},{createAgeRenderer:U_,createContinuousRenderer:q_},{createRenderer:B_},{getSchemesByTag:K_},zy,Ly,Ny,ep,{formatDateOnly:Gy,convertDateFormatToIntlOptions:Xs,formatTimeOnly:Vy,formatDate:tp},s_,a_,i_,m_,f_,G_,_p,,{fetchKnowledgeGraph:hp,executeQueryStreaming:V_,executeSearchStreaming:W_},H_,{getBindParametersFromCypherQuery:J_},,,,,,,Yi,rA,oA,{addressToLocations:nA},sA,_A,$A,,,,,,,,,,,,,,,,,,,p3,f3,,,,,,,,,,,,,HA,Cp,JA,,{a:Bl,b:Kl},{a:Fl,b:Ul,c:ql}])=>{var lt=(t,e)=>e,Sa=(t,e)=>({...t,...e}),Ca=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let o=t.trim();if(!o)return r;if(o===r)return t;let n=o.split(`
3
+
4
+ `);return n[n.length-1]?.trim()===r?t:`${t}
5
+
6
+ ${r}`},ka=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Ot=()=>({agentExecutionContext:M({reducer:Sa,default:ka}),outputMessage:M({reducer:Ca,default:()=>""}),summary:M({reducer:lt,default:()=>""}),status:M({reducer:lt})}),rs=()=>({...Ot(),sharedStatePatch:M({reducer:lt})});var c=v;async function Ea(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
7
+
8
+ If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
9
+
10
+ Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
11
+ |`,`
12
+ \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
13
+ `].join(" "));let o=await Cl(r),n=o?.getParentRunId();o!==void 0&&n!==void 0&&await o.handleCustomEvent?.(t,e,n)}var J=async(t,e)=>{await Ea("trace_message",t,e)},fe=async(t,e)=>{await Ea("graph_ux_suggestion",t,e)};var dm={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},langsmith:{package:"@langchain/openai",className:"ChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},Gv=Object.keys(dm);var Na=Symbol.for("langgraph-zod");Na in globalThis||(globalThis[Na]=new WeakSet);function Ql(t){let e=globalThis[Na];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(o){return ts(r,{jsonSchemaExtra:o})},reducer(o,n){return ts(r,{default:Jn(r),reducer:{schema:n,fn:o}})}}}}),e.add(t))}try{Ql(A.ZodType.prototype),Ql(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 Yl=class extends El{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let o=Jn(t);o!=null&&(r.default=o)}return super.add(t,...e)}},hm=new Yl(es);var km=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Em=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),Mm=["approve","edit","reject"],Pm=A.enum(Mm),Om=A.object({allowedDecisions:A.array(Pm),description:A.union([A.string(),Em]).optional(),argsSchema:A.record(A.any()).optional(),when:km.optional()}),ek=A.object({interruptOn:A.record(A.union([A.boolean(),Om])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var as=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(()=>t=>xl(t)??!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 $m=`<role>
14
+ Context Extraction Assistant
15
+ </role>
16
+
17
+ <primary_objective>
18
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
19
+ </primary_objective>
20
+
21
+ <objective_information>
22
+ 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.
23
+ 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.
24
+ </objective_information>
25
+
26
+ <instructions>
27
+ 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.
28
+ 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.
29
+ </instructions>
30
+
31
+ 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:
32
+
33
+ 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.
34
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
35
+
36
+ <messages>
37
+ Messages to summarize:
38
+ {messages}
39
+ </messages>`;var zm=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),Da=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"}),cu=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"}),xk=A.object({model:A.custom(),trigger:A.union([Da,A.array(Da)]).optional(),keep:cu.optional(),tokenCounter:zm.optional(),summaryPrompt:A.string().default($m),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var Nk=A.object({model:A.string().or(A.instanceof(Rl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var Uk=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var Vk=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Lm=["continue","error","end"],jm="continue";var Dm=A.enum(Lm).default(jm);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Dm});var oE=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Fm=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Um=A.object({content:A.string().describe("Content of the todo item"),status:Fm}),dE=A.object({todos:A.array(Um).default([])});var gE=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),yE=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var EE=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(as);var LE=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(as);var nM=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var lM=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function nn(t,e){return t.lc_error_code=e,t.message=`${t.message}
40
+
41
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
42
+ `,t}function P(t,e,r,o,n){if(o==="m")throw new TypeError("Private method is not writable");if(o==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function _(t,e,r,o){if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?o:r==="a"?o.call(t):o?o.value:e.get(t)}var qa=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return qa=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,o=>(+o^r()&15>>+o/4).toString(16))};function sn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var an=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var C=class extends Error{},V=class t extends C{constructor(e,r,o,n){super(`${t.makeMessage(e,r,o)}`),this.status=e,this.headers=n,this.requestID=n?.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,o){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):o;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,o,n){if(!e||!n)return new ct({message:o,cause:an(r)});let s=r?.error;return e===400?new Ir(e,s,o,n):e===401?new vr(e,s,o,n):e===403?new Tr(e,s,o,n):e===404?new Sr(e,s,o,n):e===409?new Cr(e,s,o,n):e===422?new kr(e,s,o,n):e===429?new Er(e,s,o,n):e>=500?new Mr(e,s,o,n):new t(e,s,o,n)}},W=class extends V{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends V{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ne=class extends ct{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ir=class extends V{},vr=class extends V{},Tr=class extends V{},Sr=class extends V{},Cr=class extends V{},kr=class extends V{},Er=class extends V{},Mr=class extends V{},Pr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Or=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},$e=class extends Error{constructor(e){super(e)}},Nt=class extends V{constructor(e,r,o){let n="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?n=i:s&&(n=s)}super(e,r,n,o),this.error_code=s}},ln=class extends C{constructor(e,r,o){super(e),this.provider=r,this.cause=o}};var Tf=/^[a-z][a-z0-9+.-]*:/i,mu=t=>Tf.test(t),de=t=>(de=Array.isArray,de(t)),Ba=de;function is(t){return typeof t!="object"?{}:t??{}}function Ka(t){if(!t)return!0;for(let e in t)return!1;return!0}function fu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function un(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var hu=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var gu=t=>{try{return JSON.parse(t)}catch{return}};var ze=t=>new Promise(e=>setTimeout(e,t));var dt="6.45.0";var bu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Sf(){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 Cf=()=>{let t=Sf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":_u(Deno.build.os),"X-Stainless-Arch":yu(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":_u(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=kf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function kf(){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 o=r.exec(navigator.userAgent);if(o){let n=o[1]||0,s=o[2]||0,a=o[3]||0;return{browser:e,version:`${n}.${s}.${a}`}}}return null}var yu=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",_u=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),wu,Au=()=>wu??(wu=Cf());function ls(){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 Ga(...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 us(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ga({start(){},async pull(r){let{done:o,value:n}=await e.next();o?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function Va(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 Wa(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 Iu=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ha="RFC3986",Ja=t=>String(t),Za={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Ja},vu="RFC1738";var cs=(t,e)=>(cs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cs(t,e)),Le=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Qa=1024,Tu=(t,e,r,o,n)=>{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+=Qa){let u=s.length>=Qa?s.slice(i,i+Qa):s,l=[];for(let d=0;d<u.length;++d){let p=u.charCodeAt(d);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===vu&&(p===40||p===41)){l[l.length]=u.charAt(d);continue}if(p<128){l[l.length]=Le[p];continue}if(p<2048){l[l.length]=Le[192|p>>6]+Le[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Le[224|p>>12]+Le[128|p>>6&63]+Le[128|p&63];continue}d+=1,p=65536+((p&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Le[240|p>>18]+Le[128|p>>12&63]+Le[128|p>>6&63]+Le[128|p&63]}a+=l.join("")}return a};function Su(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Ya(t,e){if(de(t)){let r=[];for(let o=0;o<t.length;o+=1)r.push(e(t[o]));return r}return e(t)}var ku={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Eu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},Cu,te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Tu,encodeValuesOnly:!1,format:Ha,formatter:Ja,indices:!1,serializeDate(t){return(Cu??(Cu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Mf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Xa={};function Mu(t,e,r,o,n,s,a,i,u,l,d,p,f,x,w,b,y,S){let h=t,I=S,k=0,U=!1;for(;(I=I.get(Xa))!==void 0&&!U;){let Q=I.get(t);if(k+=1,typeof Q<"u"){if(Q===k)throw new RangeError("Cyclic object value");U=!0}typeof I.get(Xa)>"u"&&(k=0)}if(typeof l=="function"?h=l(e,h):h instanceof Date?h=f?.(h):r==="comma"&&de(h)&&(h=Ya(h,function(Q){return Q instanceof Date?f?.(Q):Q})),h===null){if(s)return u&&!b?u(e,te.encoder,y,"key",x):e;h=""}if(Mf(h)||Su(h)){if(u){let Q=b?e:u(e,te.encoder,y,"key",x);return[w?.(Q)+"="+w?.(u(h,te.encoder,y,"value",x))]}return[w?.(e)+"="+w?.(String(h))]}let q=[];if(typeof h>"u")return q;let G;if(r==="comma"&&de(h))b&&u&&(h=Ya(h,u)),G=[{value:h.length>0?h.join(",")||null:void 0}];else if(de(l))G=l;else{let Q=Object.keys(h);G=d?Q.sort(d):Q}let H=i?String(e).replace(/\./g,"%2E"):String(e),le=o&&de(h)&&h.length===1?H+"[]":H;if(n&&de(h)&&h.length===0)return le+"[]";for(let Q=0;Q<G.length;++Q){let ee=G[Q],cl=typeof ee=="object"&&typeof ee.value<"u"?ee.value:h[ee];if(a&&cl===null)continue;let ha=p&&i?ee.replace(/\./g,"%2E"):ee,um=de(h)?typeof r=="function"?r(le,ha):le:le+(p?"."+ha:"["+ha+"]");S.set(t,k);let dl=new WeakMap;dl.set(Xa,S),Eu(q,Mu(cl,um,r,o,n,s,a,i,r==="comma"&&b&&de(h)?null:u,l,d,p,f,x,w,b,y,dl))}return q}function Pf(t=te){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||te.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=Ha;if(typeof t.format<"u"){if(!cs(Za,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let o=Za[r],n=te.filter;(typeof t.filter=="function"||de(t.filter))&&(n=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in ku?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=te.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:te.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:te.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:te.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:te.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?te.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:te.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:te.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:te.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:te.encodeValuesOnly,filter:n,format:r,formatter:o,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:te.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:te.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:te.strictNullHandling}}function Pu(t,e={}){let r=t,o=Pf(e),n,s;typeof o.filter=="function"?(s=o.filter,r=s("",r)):de(o.filter)&&(s=o.filter,n=s);let a=[];if(typeof r!="object"||r===null)return"";let i=ku[o.arrayFormat],u=i==="comma"&&o.commaRoundTrip;n||(n=Object.keys(r)),o.sort&&n.sort(o.sort);let l=new WeakMap;for(let f=0;f<n.length;++f){let x=n[f];o.skipNulls&&r[x]===null||Eu(a,Mu(r[x],x,i,u,o.allowEmptyArrays,o.strictNullHandling,o.skipNulls,o.encodeDotInKeys,o.encode?o.encoder:null,o.filter,o.sort,o.allowDots,o.serializeDate,o.format,o.formatter,o.encodeValuesOnly,o.charset,l))}let d=a.join(o.delimiter),p=o.addQueryPrefix===!0?"?":"";return o.charsetSentinel&&(o.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),d.length>0?p+d:""}function Ou(t){return Pu(t,{arrayFormat:"brackets"})}function $u(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}var Ru;function Rr(t){let e;return(Ru??(e=new globalThis.TextEncoder,Ru=e.encode.bind(e)))(t)}var Nu;function ei(t){let e;return(Nu??(e=new globalThis.TextDecoder,Nu=e.decode.bind(e)))(t)}var ye,_e,$t=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),P(this,ye,new Uint8Array,"f"),P(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Rr(e):e;P(this,ye,$u([_(this,ye,"f"),r]),"f");let o=[],n;for(;(n=Rf(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(n.carriage&&_(this,_e,"f")==null){P(this,_e,n.index,"f");continue}if(_(this,_e,"f")!=null&&(n.index!==_(this,_e,"f")+1||n.carriage)){o.push(ei(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),P(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),P(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?n.preceding-1:n.preceding,a=ei(_(this,ye,"f").subarray(0,s));o.push(a),P(this,ye,_(this,ye,"f").subarray(n.index),"f"),P(this,_e,null,"f")}return o}flush(){return _(this,ye,"f").length?this.decode(`
43
+ `):[]}};ye=new WeakMap,_e=new WeakMap;$t.NEWLINE_CHARS=new Set([`
44
+ `,"\r"]);$t.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Rf(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function zu(t){for(let o=0;o<t.length-1;o++){if(t[o]===10&&t[o+1]===10||t[o]===13&&t[o+1]===13)return o+2;if(t[o]===13&&t[o+1]===10&&o+3<t.length&&t[o+2]===13&&t[o+3]===10)return o+4}return-1}var ps={off:0,error:200,warn:300,info:400,debug:500},ti=(t,e,r)=>{if(t){if(fu(ps,t))return t;Z(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ps))}`)}};function cn(){}function ds(t,e,r){return!e||ps[t]>ps[r]?cn:e[t].bind(e)}var Nf={error:cn,warn:cn,info:cn,debug:cn},Lu=new WeakMap;function Z(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Nf;let o=Lu.get(e);if(o&&o[0]===r)return o[1];let n={error:ds("error",e,r),warn:ds("warn",e,r),info:ds("info",e,r),debug:ds("debug",e,r)};return Lu.set(e,[r,n]),n}var Ke=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 dn,je=class t{constructor(e,r,o){this.iterator=e,dn.set(this,void 0),this.controller=r,P(this,dn,o,"f")}static fromSSEResponse(e,r,o,n){let s=!1,a=o?Z(o):console;async function*i(){if(s)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of $f(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(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(d&&d.error)throw new V(void 0,d.error,void 0,e.headers);yield n?{event:l.event,data:d}:d}else{let d;try{d=JSON.parse(l.data)}catch(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new V(void 0,d.error,d.message,void 0);yield{event:l.event,data:d}}}u=!0}catch(l){if(sn(l))return;throw l}finally{u||r.abort()}}return new t(i,r,o)}static fromReadableStream(e,r,o){let n=!1;async function*s(){let i=new $t,u=Va(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(n)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(sn(u))return;throw u}finally{i||r.abort()}}return new t(a,r,o)}[(dn=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],o=this.iterator(),n=s=>({next:()=>{if(s.length===0){let a=o.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>n(e),this.controller,_(this,dn,"f")),new t(()=>n(r),this.controller,_(this,dn,"f"))]}toReadableStream(){let e=this,r;return Ga({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:n,done:s}=await r.next();if(s)return o.close();let a=Rr(JSON.stringify(n)+`
45
+ `);o.enqueue(a)}catch(n){o.error(n)}},async cancel(){await r.return?.()}})}};async function*$f(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new C("Attempted to iterate over a response with no body");let r=new ri,o=new $t,n=Va(t.body);for await(let s of zf(n))for(let a of o.decode(s)){let i=r.decode(a);i&&(yield i)}for(let s of o.flush()){let a=r.decode(s);a&&(yield a)}}async function*zf(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let o=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Rr(r):r,n=new Uint8Array(e.length+o.length);n.set(e),n.set(o,e.length),e=n;let s;for(;(s=zu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ri=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(`
46
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,o,n]=Lf(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function Lf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ms(t,e){let{response:r,requestLogID:o,retryOfRequestLogID:n,startTime:s}=e,a=await(async()=>{if(e.options.stream)return Z(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):je.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 oi(f,r)}return await r.text()})();return Z(t).debug(`[${o}] response parsed`,Ke({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function oi(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 pn,zt=class t extends Promise{constructor(e,r,o=ms){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=o,pn.set(this,void 0),P(this,pn,e,"f")}_thenUnwrap(e){return new t(_(this,pn,"f"),this.responsePromise,async(r,o)=>oi(e(await this.parseResponse(r,o),o),o.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,pn,"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)}};pn=new WeakMap;var fs,Nr=class{constructor(e,r,o,n){fs.set(this,void 0),P(this,fs,e,"f"),this.options=n,this.response=r,this.body=o}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,fs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},mn=class extends zt{constructor(e,r,o){super(e,r,async(n,s)=>new o(n,s.response,await ms(n,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.object=o.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},N=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.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:{...is(this.options.query),after:r}}:null}},L=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.has_more||!1,this.last_id=o.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:{...is(this.options.query),after:e}}:null}},X=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.has_more||!1,this.next=o.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:{...is(this.options.query),after:e}}:null}};var Df={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Ff="urn:ietf:params:oauth:grant-type:token-exchange",hs=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ls()}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:Ff,subject_token:e,subject_token_type:Df[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 o=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){let u=await o.text(),l;try{l=JSON.parse(u)}catch{}throw o.status===400||o.status===401||o.status===403?new Nt(o.status,l,o.headers):V.generate(o.status,l,`Token exchange failed with status ${o.status}`,o.headers)}let n=await o.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new C("Token exchange response missing 'access_token' field");let s=n.access_token,a=n.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 o=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-o}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var ai=()=>{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 $r(t,e,r){return ai(),new File(t,e??"unknown_file",r)}function fn(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 gs=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pt=async(t,e)=>ni(t.body)?{...t,body:await Du(t.body,e)}:t,me=async(t,e)=>({...t,body:await Du(t.body,e)}),ju=new WeakMap;function Uf(t){let e=typeof t=="function"?t:t.fetch,r=ju.get(e);if(r)return r;let o=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new n(s).text()}catch{return!0}})();return ju.set(e,o),o}var Du=async(t,e)=>{if(!await Uf(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(([o,n])=>si(r,o,n))),r},Fu=t=>t instanceof Blob&&"name"in t,qf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||gs(t)||Fu(t)),ni=t=>{if(qf(t))return!0;if(Array.isArray(t))return t.some(ni);if(t&&typeof t=="object"){for(let e in t)if(ni(t[e]))return!0}return!1},si=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,$r([await r.blob()],fn(r)));else if(gs(r))t.append(e,$r([await new Response(us(r)).blob()],fn(r)));else if(Fu(r))t.append(e,r,fn(r));else if(Array.isArray(r))await Promise.all(r.map(o=>si(t,e+"[]",o)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([o,n])=>si(t,`${e}[${o}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Uu=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",Bf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Uu(t),Kf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function hn(t,e,r){if(ai(),t=await t,Bf(t))return t instanceof File?t:$r([await t.arrayBuffer()],t.name);if(Kf(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),$r(await ii(n),e,r)}let o=await ii(t);if(e||(e=fn(t)),!r?.type){let n=o.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof n=="string"&&(r={...r,type:n})}return $r(o,e,r)}async function ii(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Uu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(gs(t))for await(let r of t)e.push(...await ii(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Gf(t)}`)}return e}function Gf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function Bu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var qu=Object.freeze(Object.create(null)),Wf=(t=Bu)=>function(r,...o){if(r.length===1)return r[0];let n=!1,s=[],a=r.reduce((d,p,f)=>{/[?#]/.test(p)&&(n=!0);let x=o[f],w=(n?encodeURIComponent:t)(""+x);return f!==o.length&&(x==null||typeof x=="object"&&x.toString===Object.getPrototypeOf(Object.getPrototypeOf(x.hasOwnProperty??qu)??qu)?.toString)&&(w=x+"",s.push({start:d.length+p.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(x).slice(8,-1)} is not a valid path parameter`})),d+p+(f===o.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,p)=>d.start-p.start),s.length>0){let d=0,p=s.reduce((f,x)=>{let w=" ".repeat(x.start-d),b="^".repeat(x.length);return d=x.start+x.length,f+w+b},"");throw new C(`Path parameters result in path with invalid segments:
47
+ ${s.map(f=>f.error).join(`
48
+ `)}
49
+ ${a}
50
+ ${p}`)}return a},m=Wf(Bu);var Lt=class extends g{list(e,r={},o){return this._client.getAPIList(m`/chat/completions/${e}/messages`,N,{query:r,...o,__security:{bearerAuth:!0}})}};function gn(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Gu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function yn(t){return t?.$brand==="auto-parseable-response-format"}function jt(t){return t?.$brand==="auto-parseable-tool"}function Vu(t,e){return!e||!li(e)?{...t,choices:t.choices.map(r=>(Hu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:_n(t,e)}function _n(t,e){let r=t.choices.map(o=>{if(o.finish_reason==="length")throw new Pr;if(o.finish_reason==="content_filter")throw new Or;return Hu(o.message.tool_calls),{...o,message:{...o.message,...o.message.tool_calls?{tool_calls:o.message.tool_calls?.map(n=>Zf(e,n))??void 0}:void 0,parsed:o.message.content&&!o.message.refusal?Jf(e,o.message.content):null}}});return{...t,choices:r}}function Jf(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 Zf(t,e){let r=t.tools?.find(o=>gn(o)&&o.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:jt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Wu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(o=>gn(o)&&o.function?.name===e.function.name);return gn(r)&&(jt(r)||r?.function.strict||!1)}function li(t){return yn(t.response_format)?!0:t.tools?.some(e=>jt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Hu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ju(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var zr=t=>t?.role==="assistant",ui=t=>t?.role==="tool";var ys,_s,ws,wn,bn,bs,An,Ge,As,xn,xs,Is,Lr,Zu,Qu,mt=class{constructor(){ys.add(this),this.controller=new AbortController,_s.set(this,void 0),ws.set(this,()=>{}),wn.set(this,()=>{}),bn.set(this,void 0),bs.set(this,()=>{}),An.set(this,()=>{}),Ge.set(this,{}),As.set(this,[]),xn.set(this,!1),xs.set(this,!1),Is.set(this,!1),Lr.set(this,!1),P(this,_s,new Promise((e,r)=>{P(this,ws,e,"f"),P(this,wn,r,"f")}),"f"),P(this,bn,new Promise((e,r)=>{P(this,bs,e,"f"),P(this,An,r,"f")}),"f"),_(this,_s,"f").catch(()=>{}),_(this,bn,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,ys,"m",Qu).bind(this))},0)}_connected(){this.ended||(_(this,ws,"f").call(this),this._emit("connect"))}get ended(){return _(this,xn,"f")}get errored(){return _(this,xs,"f")}get aborted(){return _(this,Is,"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,As,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ge,"f")[e]||(_(this,Ge,"f")[e]=[])).push({listener:r}),this}off(e,r){let o=_(this,Ge,"f")[e];if(!o)return this;let n=o.findIndex(s=>s.listener===r);return n>=0&&o.splice(n,1),this}once(e,r){return(_(this,Ge,"f")[e]||(_(this,Ge,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,o)=>{P(this,Lr,!0,"f"),e!=="error"&&this.once("error",o),this.once(e,r)})}async done(){P(this,Lr,!0,"f"),await _(this,bn,"f")}_emit(e,...r){if(_(this,xn,"f"))return;e==="end"&&(_(this,ys,"m",Zu).call(this),P(this,xn,!0,"f"),_(this,bs,"f").call(this));let o=_(this,Ge,"f")[e];if(o&&(_(this,Ge,"f")[e]=o.filter(n=>!n.once),o.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!_(this,Lr,"f")&&!o?.length&&Promise.reject(n),_(this,wn,"f").call(this,n),_(this,An,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!_(this,Lr,"f")&&!o?.length&&Promise.reject(n),_(this,wn,"f").call(this,n),_(this,An,"f").call(this,n),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,ws=new WeakMap,wn=new WeakMap,bn=new WeakMap,bs=new WeakMap,An=new WeakMap,Ge=new WeakMap,As=new WeakMap,xn=new WeakMap,xs=new WeakMap,Is=new WeakMap,Lr=new WeakMap,ys=new WeakSet,Zu=function(){for(let{signal:e,listener:r}of _(this,As,"f").splice(0))e.removeEventListener("abort",r)},Qu=function(e){if(P(this,xs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new W),e instanceof W)return P(this,Is,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function Yu(t){return typeof t.parse=="function"}var he,ci,vs,di,pi,mi,Xu,ec,Qf=10,jr=class extends mt{constructor(){super(...arguments),he.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),ui(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(zr(e)&&e.tool_calls)for(let o of e.tool_calls)o.type==="function"&&this._emit("functionToolCall",o.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,he,"m",ci).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",vs).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",di).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",pi).call(this)}async totalUsage(){return await this.done(),_(this,he,"m",mi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,he,"m",vs).call(this);r&&this._emit("finalMessage",r);let o=_(this,he,"m",ci).call(this);o&&this._emit("finalContent",o);let n=_(this,he,"m",di).call(this);n&&this._emit("finalFunctionToolCall",n);let s=_(this,he,"m",pi).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,he,"m",mi).call(this))}async _createChatCompletion(e,r,o){this._listenForAbort(o?.signal),_(this,he,"m",Xu).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...o,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_n(n,r))}async _runChatCompletion(e,r,o){for(let n of r.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,r,o)}async _runTools(e,r,o,n){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=Qf,afterCompletion:p}=n||{},f=r.tools.map(y=>{if(jt(y)){if(!y.$callback)throw new C("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}),x={};for(let y of f)y.type==="function"&&(x[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 S=y.id,{name:h,arguments:I}=y.function,k=x[h];if(!k){let G=`Invalid tool_call: ${JSON.stringify(h)}. Available options are: ${Object.keys(x).map(H=>JSON.stringify(H)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:S,content:G},functionCalled:!1}}if(l&&l!==h){let G=`Invalid tool_call: ${JSON.stringify(h)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:S,content:G},functionCalled:!1}}let U;if(Yu(k)){let G;try{G=await k.parse(I)}catch(H){let le=H instanceof Error?H.message:String(H);return{message:{role:s,tool_call_id:S,content:le},functionCalled:!1}}U=await k.function(G,o)}else U=await k.function(I,o);let q=_(this,he,"m",ec).call(this,U);return{message:{role:s,tool_call_id:S,content:q},functionCalled:!0}};for(let y=0;y<d;++y){let S=await this._createChatCompletion(e,{...u,tool_choice:a,tools:w,messages:[...this.messages]},n),h=S.choices[0]?.message;if(!h)throw new C("missing message in ChatCompletion response");if(!h.tool_calls?.length){await p?.(S,o);return}if(l||r.parallel_tool_calls===!1)for(let I of h.tool_calls){let k=await b(I);if(k.message&&this._addMessage(k.message),l&&k.functionCalled){await p?.(S,o);return}}else{let I=await Promise.allSettled(h.tool_calls.map(b));for(let k of I)if(k.status==="rejected")throw k.reason;for(let k of I)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message)}await p?.(S,o)}}};he=new WeakSet,ci=function(){return _(this,he,"m",vs).call(this).content??null},vs=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(zr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},di=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(zr(r)&&r?.tool_calls?.length)for(let o=r.tool_calls.length-1;o>=0;o--){let n=r.tool_calls[o];if(n?.type==="function")return n.function}}},pi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ui(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(o=>o.role==="assistant"&&o.tool_calls?.some(n=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}},mi=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},Xu=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ec=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var In=class t extends jr{static runTools(e,r,o){let n=new t,s={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,s)),n}_addMessage(e,r=!0){super._addMessage(e,r),zr(e)&&e.content&&this._emit("content",e.content)}};var ne={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},fi=class extends Error{},hi=class extends Error{};function Yf(t,e=ne.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Xf(t.trim(),e)}var Xf=(t,e)=>{let r=t.length,o=0,n=f=>{throw new fi(`${f} at position ${o}`)},s=f=>{throw new hi(`${f} at position ${o}`)},a=()=>(p(),o>=r&&n("Unexpected end of input"),t[o]==='"'?i():t[o]==="{"?u():t[o]==="["?l():t.substring(o,o+4)==="null"||ne.NULL&e&&r-o<4&&"null".startsWith(t.substring(o))?(o+=4,null):t.substring(o,o+4)==="true"||ne.BOOL&e&&r-o<4&&"true".startsWith(t.substring(o))?(o+=4,!0):t.substring(o,o+5)==="false"||ne.BOOL&e&&r-o<5&&"false".startsWith(t.substring(o))?(o+=5,!1):t.substring(o,o+8)==="Infinity"||ne.INFINITY&e&&r-o<8&&"Infinity".startsWith(t.substring(o))?(o+=8,1/0):t.substring(o,o+9)==="-Infinity"||ne.MINUS_INFINITY&e&&1<r-o&&r-o<9&&"-Infinity".startsWith(t.substring(o))?(o+=9,-1/0):t.substring(o,o+3)==="NaN"||ne.NAN&e&&r-o<3&&"NaN".startsWith(t.substring(o))?(o+=3,NaN):d()),i=()=>{let f=o,x=!1;for(o++;o<r&&(t[o]!=='"'||x&&t[o-1]==="\\");)x=t[o]==="\\"?!x:!1,o++;if(t.charAt(o)=='"')try{return JSON.parse(t.substring(f,++o-Number(x)))}catch(w){s(String(w))}else if(ne.STR&e)try{return JSON.parse(t.substring(f,o-Number(x))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{o++,p();let f={};try{for(;t[o]!=="}";){if(p(),o>=r&&ne.OBJ&e)return f;let x=i();p(),o++;try{let w=a();Object.defineProperty(f,x,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(ne.OBJ&e)return f;throw w}p(),t[o]===","&&o++}}catch{if(ne.OBJ&e)return f;n("Expected '}' at end of object")}return o++,f},l=()=>{o++;let f=[];try{for(;t[o]!=="]";)f.push(a()),p(),t[o]===","&&o++}catch{if(ne.ARR&e)return f;n("Expected ']' at end of array")}return o++,f},d=()=>{if(o===0){t==="-"&&ne.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t)}catch(x){if(ne.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(x))}}let f=o;for(t[o]==="-"&&o++;t[o]&&!",]}".includes(t[o]);)o++;o==r&&!(ne.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(t.substring(f,o))}catch{t.substring(f,o)==="-"&&ne.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},p=()=>{for(;o<r&&`
51
+ \r `.includes(t[o]);)o++};return a()},gi=t=>Yf(t,ne.ALL^ne.NUM);var re,Ve,Dr,ft,yi,Ts,_i,wi,bi,Ss,Ai,tc,Dt=class t extends jr{constructor(e){super(),re.add(this),Ve.set(this,void 0),Dr.set(this,void 0),ft.set(this,void 0),P(this,Ve,e,"f"),P(this,Dr,[],"f")}get currentChatCompletionSnapshot(){return _(this,ft,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,o){let n=new t(r);return n._run(()=>n._runChatCompletion(e,{...r,stream:!0},{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,r,o){super._createChatCompletion,this._listenForAbort(o?.signal),_(this,re,"m",yi).call(this);let n=await e.chat.completions.create({...r,stream:!0},{...o,signal:this.controller.signal});this._connected();for await(let s of n)_(this,re,"m",_i).call(this,s);if(n.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,re,"m",Ss).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,re,"m",yi).call(this),this._connected();let o=je.fromReadableStream(e,this.controller),n;for await(let s of o)n&&n!==s.id&&this._addChatCompletion(_(this,re,"m",Ss).call(this)),_(this,re,"m",_i).call(this,s),n=s.id;if(o.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,re,"m",Ss).call(this))}[(Ve=new WeakMap,Dr=new WeakMap,ft=new WeakMap,re=new WeakSet,yi=function(){this.ended||P(this,ft,void 0,"f")},Ts=function(r){let o=_(this,Dr,"f")[r.index];return o||(o={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},_(this,Dr,"f")[r.index]=o,o)},_i=function(r){if(this.ended)return;let o=_(this,re,"m",tc).call(this,r);this._emit("chunk",r,o);for(let n of r.choices){let s=o.choices[n.index];n.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",n.delta.content,s.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),n.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:s.message.refusal}),n.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:s.logprobs?.content??[]}),n.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=_(this,re,"m",Ts).call(this,s);s.finish_reason&&(_(this,re,"m",bi).call(this,s),a.current_tool_call_index!=null&&_(this,re,"m",wi).call(this,s,a.current_tool_call_index));for(let i of n.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(_(this,re,"m",bi).call(this,s),a.current_tool_call_index!=null&&_(this,re,"m",wi).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of n.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))}}},wi=function(r,o){if(_(this,re,"m",Ts).call(this,r).done_tool_calls.has(o))return;let s=r.message.tool_calls?.[o];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,Ve,"f")?.tools?.find(i=>gn(i)&&i.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:o,arguments:s.function.arguments,parsed_arguments:jt(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},bi=function(r){let o=_(this,re,"m",Ts).call(this,r);if(r.message.content&&!o.content_done){o.content_done=!0;let n=_(this,re,"m",Ai).call(this);this._emit("content.done",{content:r.message.content,parsed:n?n.$parseRaw(r.message.content):null})}r.message.refusal&&!o.refusal_done&&(o.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!o.logprobs_content_done&&(o.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!o.logprobs_refusal_done&&(o.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Ss=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,ft,"f");if(!r)throw new C("request ended without sending any chunks");return P(this,ft,void 0,"f"),P(this,Dr,[],"f"),eh(r,_(this,Ve,"f"))},Ai=function(){let r=_(this,Ve,"f")?.response_format;return yn(r)?r:null},tc=function(r){var o,n,s,a;let i=_(this,ft,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=P(this,ft,{...l,choices:[]},"f");for(let{delta:d,finish_reason:p,index:f,logprobs:x=null,...w}of r.choices){let b=i.choices[f];if(b||(b=i.choices[f]={finish_reason:p,index:f,message:{},logprobs:x,...w}),x)if(!b.logprobs)b.logprobs=Object.assign({},x);else{let{content:q,refusal:G,...H}=x;Object.assign(b.logprobs,H),q&&((o=b.logprobs).content??(o.content=[]),b.logprobs.content.push(...q)),G&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...G))}if(p&&(b.finish_reason=p,_(this,Ve,"f")&&li(_(this,Ve,"f")))){if(p==="length")throw new Pr;if(p==="content_filter")throw new Or}if(Object.assign(b,w),!d)continue;let{content:y,refusal:S,function_call:h,role:I,tool_calls:k,...U}=d;if(Object.assign(b.message,U),S&&(b.message.refusal=(b.message.refusal||"")+S),I&&(b.message.role=I),h&&(b.message.function_call?(h.name&&(b.message.function_call.name=h.name),h.arguments&&((s=b.message.function_call).arguments??(s.arguments=""),b.message.function_call.arguments+=h.arguments)):b.message.function_call=h),y&&(b.message.content=(b.message.content||"")+y,!b.message.refusal&&_(this,re,"m",Ai).call(this)&&(b.message.parsed=b.message.content.trim()?gi(b.message.content):null)),k){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:q,id:G,type:H,function:le,...Q}of k){let ee=(a=b.message.tool_calls)[q]??(a[q]={});Object.assign(ee,Q),G&&(ee.id=G),H&&(ee.type=H),le&&(ee.function??(ee.function={name:le.name??"",arguments:""})),le?.name&&(ee.function.name=le.name),le?.arguments&&(ee.function.arguments+=le.arguments,Wu(_(this,Ve,"f"),ee)&&(ee.function.parsed_arguments=gi(ee.function.arguments)))}}}return i},Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("chunk",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{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 je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function eh(t,e){let{id:r,choices:o,created:n,model:s,system_fingerprint:a,...i}=t,u={...i,id:r,choices:o.map(({message:l,finish_reason:d,index:p,logprobs:f,...x})=>{if(!d)throw new C(`missing finish_reason for choice ${p}`);let{content:w=null,function_call:b,tool_calls:y,...S}=l,h=l.role;if(!h)throw new C(`missing role for choice ${p}`);if(b){let{arguments:I,name:k}=b;if(I==null)throw new C(`missing function_call.arguments for choice ${p}`);if(!k)throw new C(`missing function_call.name for choice ${p}`);return{...x,message:{content:w,function_call:{arguments:I,name:k},role:h,refusal:l.refusal??null},finish_reason:d,index:p,logprobs:f}}return y?{...x,index:p,finish_reason:d,logprobs:f,message:{...S,role:h,content:w,refusal:l.refusal??null,tool_calls:y.map((I,k)=>{let{function:U,type:q,id:G,...H}=I,{arguments:le,name:Q,...ee}=U||{};if(G==null)throw new C(`missing choices[${p}].tool_calls[${k}].id
52
+ ${Cs(t)}`);if(q==null)throw new C(`missing choices[${p}].tool_calls[${k}].type
53
+ ${Cs(t)}`);if(Q==null)throw new C(`missing choices[${p}].tool_calls[${k}].function.name
54
+ ${Cs(t)}`);if(le==null)throw new C(`missing choices[${p}].tool_calls[${k}].function.arguments
55
+ ${Cs(t)}`);return{...H,id:G,type:q,function:{...ee,name:Q,arguments:le}}})}}:{...x,message:{...S,content:w,role:h,refusal:l.refusal??null},finish_reason:d,index:p,logprobs:f}}),created:n,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Vu(u,e)}function Cs(t){return JSON.stringify(t)}var vn=class t extends Dt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,o){let n=new t(r),s={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,s)),n}};var We=class extends g{constructor(){super(...arguments),this.messages=new Lt(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(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/chat/completions/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Ju(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(o=>_n(o,e))}runTools(e,r){return e.stream?vn.runTools(this._client,e,r):In.runTools(this._client,e,r)}stream(e,r){return Dt.createChatCompletion(this._client,e,r)}};We.Messages=Lt;var ht=class extends g{constructor(){super(...arguments),this.completions=new We(this._client)}};ht.Completions=We;var Fr=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(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",N,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},o){return this._client.get(m`/organization/certificates/${e}`,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/certificates/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Br=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 Kr=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(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Gr=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(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/roles/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",X,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vr=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(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/spend_alerts/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=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 Hr=class extends g{create(e,r,o){return this._client.post(m`/organization/groups/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{group_id:n}=r;return this._client.get(m`/organization/groups/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/groups/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{group_id:n}=r;return this._client.delete(m`/organization/groups/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{create(e,r,o){return this._client.post(m`/organization/groups/${e}/users`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{group_id:n}=r;return this._client.get(m`/organization/groups/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/groups/${e}/users`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{group_id:n}=r;return this._client.delete(m`/organization/groups/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var gt=class extends g{constructor(){super(...arguments),this.users=new Jr(this._client),this.roles=new Hr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/groups/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",X,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};gt.Users=Jr;gt.Roles=Hr;var Zr=class extends g{retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/api_keys/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/api_keys`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/api_keys/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends g{list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/certificates`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}activate(e,r,o){return this._client.getAPIList(m`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,o){return this._client.getAPIList(m`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/data_retention`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}};var eo=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/model_permissions`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var to=class extends g{listRateLimits(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/rate_limits`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/rate_limits/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}};var ro=class extends g{create(e,r,o){return this._client.post(m`/projects/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/projects/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/roles/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/projects/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/projects/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var oo=class extends g{create(e,r,o){return this._client.post(m`/organization/projects/${e}/service_accounts`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/service_accounts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/service_accounts/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/service_accounts`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/service_accounts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var no=class extends g{create(e,r,o){return this._client.post(m`/organization/projects/${e}/spend_alerts`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/spend_alerts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/spend_alerts/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/spend_alerts`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/spend_alerts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var so=class extends g{create(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/groups/${e}/roles`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,group_id:s}=r;return this._client.get(m`/projects/${n}/groups/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r,o){let{project_id:n,...s}=r;return this._client.getAPIList(m`/projects/${n}/groups/${e}/roles`,X,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n,group_id:s}=r;return this._client.delete(m`/projects/${n}/groups/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends g{constructor(){super(...arguments),this.roles=new so(this._client)}create(e,r,o){return this._client.post(m`/organization/projects/${e}/groups`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,...s}=r;return this._client.get(m`/organization/projects/${n}/groups/${e}`,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/groups`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/groups/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};Ft.Roles=so;var ao=class extends g{create(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/users/${e}/roles`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,user_id:s}=r;return this._client.get(m`/projects/${n}/users/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r,o){let{project_id:n,...s}=r;return this._client.getAPIList(m`/projects/${n}/users/${e}/roles`,X,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n,user_id:s}=r;return this._client.delete(m`/projects/${n}/users/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends g{constructor(){super(...arguments),this.roles=new ao(this._client)}create(e,r,o){return this._client.post(m`/organization/projects/${e}/users`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/users/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/users`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};Ut.Roles=ao;var se=class extends g{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new oo(this._client),this.apiKeys=new Zr(this._client),this.rateLimits=new to(this._client),this.modelPermissions=new eo(this._client),this.hostedToolPermissions=new Xr(this._client),this.groups=new Ft(this._client),this.roles=new ro(this._client),this.dataRetention=new Yr(this._client),this.spendAlerts=new no(this._client),this.certificates=new Qr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(m`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};se.Users=Ut;se.ServiceAccounts=oo;se.APIKeys=Zr;se.RateLimits=to;se.ModelPermissions=eo;se.HostedToolPermissions=Xr;se.Groups=Ft;se.Roles=ro;se.DataRetention=Yr;se.SpendAlerts=no;se.Certificates=Qr;var io=class extends g{create(e,r,o){return this._client.post(m`/organization/users/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{user_id:n}=r;return this._client.get(m`/organization/users/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/users/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{user_id:n}=r;return this._client.delete(m`/organization/users/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends g{constructor(){super(...arguments),this.roles=new io(this._client)}retrieve(e,r){return this._client.get(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/users/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=io;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new Ur(this._client),this.adminAPIKeys=new Fr(this._client),this.usage=new Wr(this._client),this.invites=new Kr(this._client),this.users=new qt(this._client),this.groups=new gt(this._client),this.roles=new Gr(this._client),this.dataRetention=new Br(this._client),this.spendAlerts=new Vr(this._client),this.certificates=new qr(this._client),this.projects=new se(this._client)}};ae.AuditLogs=Ur;ae.AdminAPIKeys=Fr;ae.Usage=Wr;ae.Invites=Kr;ae.Users=qt;ae.Groups=gt;ae.Roles=Gr;ae.DataRetention=Br;ae.SpendAlerts=Vr;ae.Certificates=qr;ae.Projects=se;var yt=class extends g{constructor(){super(...arguments),this.organization=new ae(this._client)}};yt.Organization=ae;var rc=Symbol("brand.privateNullableHeaders");function*Mh(t){if(!t)return;if(rc in t){let{values:o,nulls:n}=t;yield*o.entries();for(let s of n)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Ba(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let o of r){let n=o[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let s=Ba(o[1])?o[1]:[o[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,i])}}var T=t=>{let e=new Headers,r=new Set;for(let o of t){let n=new Set;for(let[s,a]of Mh(o)){let i=s.toLowerCase();n.has(i)||(e.delete(s),n.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[rc]:!0,values:e,nulls:r}};var lo=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 uo=class extends g{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var co=class extends g{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var De=class extends g{constructor(){super(...arguments),this.transcriptions=new uo(this._client),this.translations=new co(this._client),this.speech=new lo(this._client)}};De.Transcriptions=uo;De.Translations=co;De.Speech=lo;var Bt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",N,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var po=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(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/assistants/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",N,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var mo=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 fo=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 _t=class extends g{constructor(){super(...arguments),this.sessions=new mo(this._client),this.transcriptionSessions=new fo(this._client)}};_t.Sessions=mo;_t.TranscriptionSessions=fo;var ho=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(m`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var go=class extends g{retrieve(e,r){return this._client.get(m`/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",L,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},o){return this._client.getAPIList(m`/chatkit/threads/${e}/items`,L,{query:r,...o,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},o?.headers]),__security:{bearerAuth:!0}})}};var wt=class extends g{constructor(){super(...arguments),this.sessions=new ho(this._client),this.threads=new go(this._client)}};wt.Sessions=ho;wt.Threads=go;var yo=class extends g{create(e,r,o){return this._client.post(m`/threads/${e}/messages`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{thread_id:n}=r;return this._client.get(m`/threads/${n}/messages/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/messages/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/threads/${e}/messages`,N,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r,o){let{thread_id:n}=r;return this._client.delete(m`/threads/${n}/messages/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var _o=class extends g{retrieve(e,r,o){let{thread_id:n,run_id:s,...a}=r;return this._client.get(m`/threads/${n}/runs/${s}/steps/${e}`,{query:a,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r,o){let{thread_id:n,...s}=r;return this._client.getAPIList(m`/threads/${n}/runs/${e}/steps`,N,{query:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var oc=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=e.charCodeAt(n);return Array.from(new Float32Array(o.buffer))}};var Te=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 ie,Gt,xi,Fe,ks,Se,Vt,wo,Kt,Ps,we,Es,Ms,Cn,Tn,Sn,nc,sc,ac,ic,lc,uc,cc,He=class extends mt{constructor(){super(...arguments),ie.add(this),xi.set(this,[]),Fe.set(this,{}),ks.set(this,{}),Se.set(this,void 0),Vt.set(this,void 0),wo.set(this,void 0),Kt.set(this,void 0),Ps.set(this,void 0),we.set(this,void 0),Es.set(this,void 0),Ms.set(this,void 0),Cn.set(this,void 0)}[(xi=new WeakMap,Fe=new WeakMap,ks=new WeakMap,Se=new WeakMap,Vt=new WeakMap,wo=new WeakMap,Kt=new WeakMap,Ps=new WeakMap,we=new WeakMap,Es=new WeakMap,Ms=new WeakMap,Cn=new WeakMap,ie=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("event",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{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 Gt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let o=je.fromReadableStream(e,this.controller);for await(let n of o)_(this,ie,"m",Tn).call(this,n);if(o.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,o,n){let s=new Gt;return s._run(()=>s._runToolAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,o,n){this._listenForAbort(n?.signal);let s={...o,stream:!0},a=await e.submitToolOutputs(r,s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ie,"m",Tn).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}static createThreadAssistantStream(e,r,o){let n=new Gt;return n._run(()=>n._threadAssistantStream(e,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,r,o,n){let s=new Gt;return s._run(()=>s._runAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Es,"f")}currentRun(){return _(this,Ms,"f")}currentMessageSnapshot(){return _(this,Se,"f")}currentRunStepSnapshot(){return _(this,Cn,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ks,"f"))}async finalRun(){if(await this.done(),!_(this,Vt,"f"))throw Error("Final run was not received.");return _(this,Vt,"f")}async _createThreadAssistantStream(e,r,o){this._listenForAbort(o?.signal);let n={...r,stream:!0},s=await e.createAndRun(n,{...o,signal:this.controller.signal});this._connected();for await(let a of s)_(this,ie,"m",Tn).call(this,a);if(s.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}async _createAssistantStream(e,r,o,n){this._listenForAbort(n?.signal);let s={...o,stream:!0},a=await e.create(r,s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ie,"m",Tn).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}static accumulateDelta(e,r){for(let[o,n]of Object.entries(r)){if(!e.hasOwnProperty(o)){e[o]=n;continue}let s=e[o];if(s==null){e[o]=n;continue}if(o==="index"||o==="type"){e[o]=n;continue}if(typeof s=="string"&&typeof n=="string")s+=n;else if(typeof s=="number"&&typeof n=="number")s+=n;else if(un(s)&&un(n))s=this.accumulateDelta(s,n);else if(Array.isArray(s)&&Array.isArray(n)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...n);continue}for(let a of n){if(!un(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: ${o}, deltaValue: ${n}, accValue: ${s}`);e[o]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,o){return await this._createThreadAssistantStream(r,e,o)}async _runAssistantStream(e,r,o,n){return await this._createAssistantStream(r,e,o,n)}async _runToolAssistantStream(e,r,o,n){return await this._createToolAssistantStream(r,e,o,n)}};Gt=He,Tn=function(e){if(!this.ended)switch(P(this,Es,e,"f"),_(this,ie,"m",ac).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,ie,"m",cc).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,ie,"m",sc).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,ie,"m",nc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Sn=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Vt,"f"))throw Error("Final run has not been received");return _(this,Vt,"f")},nc=function(e){let[r,o]=_(this,ie,"m",lc).call(this,e,_(this,Se,"f"));P(this,Se,r,"f"),_(this,ks,"f")[r.id]=r;for(let n of o){let s=r.content[n.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 n of e.data.delta.content){if(n.type=="text"&&n.text){let s=n.text,a=r.content[n.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(n.index!=_(this,wo,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Se,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Se,"f"));break}P(this,wo,n.index,"f")}P(this,Kt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,wo,"f")!==void 0){let n=e.data.content[_(this,wo,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,_(this,Se,"f"));break;case"text":this._emit("textDone",n.text,_(this,Se,"f"));break}}_(this,Se,"f")&&this._emit("messageDone",e.data),P(this,Se,void 0,"f")}},sc=function(e){let r=_(this,ie,"m",ic).call(this,e);switch(P(this,Cn,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let o=e.data.delta;if(o.step_details&&o.step_details.type=="tool_calls"&&o.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of o.step_details.tool_calls)s.index==_(this,Ps,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),P(this,Ps,s.index,"f"),P(this,we,r.step_details.tool_calls[s.index],"f"),_(this,we,"f")&&this._emit("toolCallCreated",_(this,we,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":P(this,Cn,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),P(this,we,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},ac=function(e){_(this,xi,"f").push(e),this._emit("event",e)},ic=function(e){switch(e.event){case"thread.run.step.created":return _(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Fe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let o=e.data;if(o.delta){let n=Gt.accumulateDelta(r,o.delta);_(this,Fe,"f")[e.data.id]=n}return _(this,Fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":_(this,Fe,"f")[e.data.id]=e.data;break}if(_(this,Fe,"f")[e.data.id])return _(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},lc=function(e,r){let o=[];switch(e.event){case"thread.message.created":return[e.data,o];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let s of n.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=_(this,ie,"m",uc).call(this,s,a)}else r.content[s.index]=s,o.push(s);return[r,o];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,o];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},uc=function(e,r){return Gt.accumulateDelta(r,e)},cc=function(e){switch(P(this,Ms,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":P(this,Vt,e.data,"f"),_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),P(this,we,void 0,"f"));break;case"thread.run.cancelling":break}};var Wt=class extends g{constructor(){super(...arguments),this.steps=new _o(this._client)}create(e,r,o){let{include:n,...s}=r;return this._client.post(m`/threads/${e}/runs`,{query:{include:n},body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{thread_id:n}=r;return this._client.get(m`/threads/${n}/runs/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/runs/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/threads/${e}/runs`,N,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,o){let{thread_id:n}=r;return this._client.post(m`/threads/${n}/runs/${e}/cancel`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r,o);return await this.poll(n.id,{thread_id:e},o)}createAndStream(e,r,o){return He.createAssistantStream(e,this._client.beta.threads.runs,r,o)}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...o,headers:{...o?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,o){return He.createAssistantStream(e,this._client.beta.threads.runs,r,o)}submitToolOutputs(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,o){let n=await this.submitToolOutputs(e,r,o);return await this.poll(n.id,r,o)}submitToolOutputsStream(e,r,o){return He.createToolAssistantStream(e,this._client.beta.threads.runs,r,o)}};Wt.Steps=_o;var bt=class extends g{constructor(){super(...arguments),this.runs=new Wt(this._client),this.messages=new yo(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(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/threads/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/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 o=await this.createAndRun(e,r);return await this.runs.poll(o.id,{thread_id:o.thread_id},r)}createAndRunStream(e,r){return He.createThreadAssistantStream(e,this._client.beta.threads,r)}};bt.Runs=Wt;bt.Messages=yo;var Ce=class extends g{constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new wt(this._client),this.assistants=new po(this._client),this.threads=new bt(this._client)}};Ce.Realtime=_t;Ce.ChatKit=wt;Ce.Assistants=po;Ce.Threads=bt;var Ht=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var bo=class extends g{retrieve(e,r,o){let{container_id:n}=r;return this._client.get(m`/containers/${n}/files/${e}/content`,{...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Jt=class extends g{constructor(){super(...arguments),this.content=new bo(this._client)}create(e,r,o){return this._client.post(m`/containers/${e}/files`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,o){let{container_id:n}=r;return this._client.get(m`/containers/${n}/files/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/containers/${e}/files`,N,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{container_id:n}=r;return this._client.delete(m`/containers/${n}/files/${e}`,{...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}};Jt.Content=bo;var At=class extends g{constructor(){super(...arguments),this.files=new Jt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};At.Files=Jt;var Ao=class extends g{create(e,r,o){let{include:n,...s}=r;return this._client.post(m`/conversations/${e}/items`,{query:{include:n},body:s,...o,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{conversation_id:n,...s}=r;return this._client.get(m`/conversations/${n}/items/${e}`,{query:s,...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/conversations/${e}/items`,L,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{conversation_id:n}=r;return this._client.delete(m`/conversations/${n}/items/${e}`,{...o,__security:{bearerAuth:!0}})}};var xt=class extends g{constructor(){super(...arguments),this.items=new Ao(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/conversations/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};xt.Items=Ao;var Zt=class extends g{create(e,r){let o=!!e.encoding_format,n=o?e.encoding_format:"base64";o&&Z(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:n},...r,__security:{bearerAuth:!0}});return o?s:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let u=i.embedding;i.embedding=oc(u)}),a)))}};var xo=class extends g{retrieve(e,r,o){let{eval_id:n,run_id:s}=r;return this._client.get(m`/evals/${n}/runs/${s}/output_items/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r,o){let{eval_id:n,...s}=r;return this._client.getAPIList(m`/evals/${n}/runs/${e}/output_items`,N,{query:s,...o,__security:{bearerAuth:!0}})}};var Qt=class extends g{constructor(){super(...arguments),this.outputItems=new xo(this._client)}create(e,r,o){return this._client.post(m`/evals/${e}/runs`,{body:r,...o,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{eval_id:n}=r;return this._client.get(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/evals/${e}/runs`,N,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{eval_id:n}=r;return this._client.delete(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}cancel(e,r,o){let{eval_id:n}=r;return this._client.post(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}};Qt.OutputItems=xo;var It=class extends g{constructor(){super(...arguments),this.runs=new Qt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/evals/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};It.Runs=Qt;var Yt=class extends g{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(m`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:o=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await ze(r),a=await this.retrieve(e),Date.now()-s>o)throw new Ne({message:`Giving up on waiting for file ${e} to finish processing after ${o} milliseconds.`});return a}};var Io=class extends g{};var vo=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 Xt=class extends g{constructor(){super(...arguments),this.graders=new vo(this._client)}};Xt.Graders=vo;var To=class extends g{create(e,r,o){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},o){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{fine_tuned_model_checkpoint:n}=r;return this._client.delete(m`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var er=class extends g{constructor(){super(...arguments),this.permissions=new To(this._client)}};er.Permissions=To;var So=class extends g{list(e,r={},o){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,N,{query:r,...o,__security:{bearerAuth:!0}})}};var tr=class extends g{constructor(){super(...arguments),this.checkpoints=new So(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(m`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",N,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},o){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,N,{query:r,...o,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};tr.Checkpoints=So;var ke=class extends g{constructor(){super(...arguments),this.methods=new Io(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};ke.Methods=Io;ke.Jobs=tr;ke.Checkpoints=er;ke.Alpha=Xt;var Co=class extends g{};var vt=class extends g{constructor(){super(...arguments),this.graderModels=new Co(this._client)}};vt.GraderModels=Co;var rr=class extends g{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var or=class extends g{retrieve(e,r){return this._client.get(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var nr=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var ko=class extends g{accept(e,r,o){return this._client.post(m`/realtime/calls/${e}/accept`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(m`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,o){return this._client.post(m`/realtime/calls/${e}/refer`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},o){return this._client.post(m`/realtime/calls/${e}/reject`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}};var Eo=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Je=class extends g{constructor(){super(...arguments),this.clientSecrets=new Eo(this._client),this.calls=new ko(this._client)}};Je.ClientSecrets=Eo;Je.Calls=ko;function dc(t,e){if(!e||!ig(e)){let r={...t,output_parsed:null,output:t.output.map(o=>o.type==="function_call"?{...o,parsed_arguments:null}:o.type==="message"?{...o,content:o.content.map(n=>({...n,parsed:null}))}:o)};return pc(t,r)&&be(r),r}return Ii(t,e)}function Ii(t,e){let r=!t.status||t.status==="completed",o=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?cg(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?ag(e,i.text):null}:i);return{...s,content:a}}return s}),n=Object.assign({},t,{output:o});return pc(t,n)&&be(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function ag(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function ig(t){return!!yn(t.text?.format)}function lg(t){return t?.$brand==="auto-parseable-tool"}function ug(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function cg(t,e){let r=ug(t.tools??[],e.name);return{...e,...e,parsed_arguments:lg(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function pc(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function be(t){let e=[];for(let r of t.output)if(r.type==="message")for(let o of r.content)o.type==="output_text"&&e.push(o.text);t.output_text=e.join("")}function fc(t,e){if(!e){if(t.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return mc(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&be(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&be(e);break}case"response.content_part.added":{let r=z(e,t.output_index),o=r.type,n=t.part;o==="message"&&n.type!=="reasoning_text"?(r.content.push(structuredClone(n)),n.type==="output_text"&&be(e)):o==="reasoning"&&n.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(n)));break}case"response.content_part.done":{let r=z(e,t.output_index),o=t.part;if(r.type==="message"&&o.type!=="reasoning_text")Ae(r.content,t.content_index),r.content[t.content_index]=structuredClone(o),o.type==="output_text"&&be(e);else if(r.type==="reasoning"&&o.type==="reasoning_text"){let n=r.content;if(!n)throw new C(`missing content at index ${t.content_index}`);Ae(n,t.content_index),n[t.content_index]=structuredClone(o)}break}case"response.output_text.delta":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.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 o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.text=t.text,be(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="refusal")throw new C(`expected content to be 'refusal', got ${o.type}`);o.refusal+=t.delta}break}case"response.refusal.done":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="refusal")throw new C(`expected content to be 'refusal', got ${o.type}`);o.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 C(`missing content at index ${t.content_index}`);let o=Ae(r.content,t.content_index);if(o.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${o.type}`);o.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 C(`missing content at index ${t.content_index}`);let o=Ae(r.content,t.content_index);if(o.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${o.type}`);o.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"&&(Ae(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 o=Ae(r.summary,t.summary_index);o.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){let o=Ae(r.summary,t.summary_index);o.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=mc(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:dg(t)}return e}function mc(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&be(e),e}function z(t,e){let r=t.output[e];if(!r)throw new C(`missing output at index ${e}`);return r}function Ae(t,e){let r=t[e];if(!r)throw new C(`missing content at index ${e}`);return r}function dg(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var kn,Os,sr,Rs,hc,gc,yc,Ns=class t extends mt{constructor(e){super(),kn.add(this),Os.set(this,void 0),sr.set(this,void 0),Rs.set(this,void 0),P(this,Os,e,"f")}static createResponse(e,r,o){let n=new t(r);return n._run(()=>n._createOrRetrieveResponse(e,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,r,o){this._listenForAbort(o?.signal),_(this,kn,"m",hc).call(this);let n,s=null;"response_id"in r?(n=await e.responses.retrieve(r.response_id,{stream:!0},{...o,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):n=await e.responses.create({...r,stream:!0},{...o,signal:this.controller.signal}),this._connected();for await(let a of n)_(this,kn,"m",gc).call(this,a,s);if(n.controller.signal?.aborted)throw new W;return _(this,kn,"m",yc).call(this)}[(Os=new WeakMap,sr=new WeakMap,Rs=new WeakMap,kn=new WeakSet,hc=function(){this.ended||P(this,sr,void 0,"f")},gc=function(r,o){if(this.ended)return;let n=(a,i)=>{(o==null||i.sequence_number>o)&&this._emit(a,i)},s=fc(r,_(this,sr,"f"));switch(P(this,sr,s,"f"),n("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new C(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new C(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new C(`expected content to be 'output_text', got ${i.type}`);n("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 C(`missing output at index ${r.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:n(r.type,r);break}},yc=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,sr,"f");if(!r)throw new C("request ended without sending any events");P(this,sr,void 0,"f");let o=pg(r,_(this,Os,"f"));return P(this,Rs,o,"f"),o},Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("event",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{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,Rs,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function pg(t,e){return dc(t,e)}var Mo=class extends g{list(e,r={},o){return this._client.getAPIList(m`/responses/${e}/input_items`,N,{query:r,...o,__security:{bearerAuth:!0}})}};var Po=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Ue=class extends g{constructor(){super(...arguments),this.inputItems=new Mo(this._client),this.inputTokens=new Po(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&be(o),o))}retrieve(e,r={},o){return this._client.get(m`/responses/${e}`,{query:r,...o,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&be(n),n))}delete(e,r){return this._client.delete(m`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(o=>Ii(o,e))}stream(e,r){return Ns.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(m`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};Ue.InputItems=Mo;Ue.InputTokens=Po;var Oo=class extends g{retrieve(e,r){return this._client.get(m`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Ro=class extends g{retrieve(e,r,o){let{skill_id:n}=r;return this._client.get(m`/skills/${n}/versions/${e}/content`,{...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ar=class extends g{constructor(){super(...arguments),this.content=new Ro(this._client)}create(e,r={},o){return this._client.post(m`/skills/${e}/versions`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,o){let{skill_id:n}=r;return this._client.get(m`/skills/${n}/versions/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/skills/${e}/versions`,N,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{skill_id:n}=r;return this._client.delete(m`/skills/${n}/versions/${e}`,{...o,__security:{bearerAuth:!0}})}};ar.Content=Ro;var Ze=class extends g{constructor(){super(...arguments),this.content=new Oo(this._client),this.versions=new ar(this._client)}create(e={},r){return this._client.post("/skills",pt({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/skills/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Ze.Content=Oo;Ze.Versions=ar;var No=class extends g{create(e,r,o){return this._client.post(m`/uploads/${e}/parts`,me({body:r,...o,__security:{bearerAuth:!0}},this._client))}};var Tt=class extends g{constructor(){super(...arguments),this.parts=new No(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,o){return this._client.post(m`/uploads/${e}/complete`,{body:r,...o,__security:{bearerAuth:!0}})}};Tt.Parts=No;var _c=async t=>{let e=await Promise.allSettled(t),r=e.filter(n=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let o=[];for(let n of e)n.status==="fulfilled"&&o.push(n.value);return o};var $o=class extends g{create(e,r,o){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{vector_store_id:n}=r;return this._client.get(m`/vector_stores/${n}/file_batches/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,o){let{vector_store_id:n}=r;return this._client.post(m`/vector_stores/${n}/file_batches/${e}/cancel`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r);return await this.poll(e,n.id,o)}listFiles(e,r,o){let{vector_store_id:n,...s}=r;return this._client.getAPIList(m`/vector_stores/${n}/file_batches/${e}/files`,N,{query:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...o,headers:n}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:o=[]},n){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=n?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...o];async function d(f){for(let x of f){let w=await i.files.create({file:x,purpose:"assistants"},n);l.push(w.id)}}let p=Array(a).fill(u).map(d);return await _c(p),await this.createAndPoll(e,{file_ids:l})}};var zo=class extends g{create(e,r,o){return this._client.post(m`/vector_stores/${e}/files`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{vector_store_id:n}=r;return this._client.get(m`/vector_stores/${n}/files/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{vector_store_id:n,...s}=r;return this._client.post(m`/vector_stores/${n}/files/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/vector_stores/${e}/files`,N,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r,o){let{vector_store_id:n}=r;return this._client.delete(m`/vector_stores/${n}/files/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r,o);return await this.poll(e,n.id,o)}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...o,headers:n}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"failed":case"completed":return a}}}async upload(e,r,o){let n=await this._client.files.create({file:r,purpose:"assistants"},o);return this.create(e,{file_id:n.id},o)}async uploadAndPoll(e,r,o){let n=await this.upload(e,r,o);return await this.poll(e,n.id,o)}content(e,r,o){let{vector_store_id:n}=r;return this._client.getAPIList(m`/vector_stores/${n}/files/${e}/content`,pe,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var Qe=class extends g{constructor(){super(...arguments),this.files=new zo(this._client),this.fileBatches=new $o(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(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/vector_stores/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",N,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,o){return this._client.getAPIList(m`/vector_stores/${e}/search`,pe,{body:r,method:"post",...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};Qe.Files=zo;Qe.FileBatches=$o;var ir=class extends g{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",L,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},o){return this._client.get(m`/videos/${e}/content`,{query:r,...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(m`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,o){return this._client.post(m`/videos/${e}/remix`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}};var Lo,wc,$s,lr=class extends g{constructor(){super(...arguments),Lo.add(this)}async unwrap(e,r,o=this._client.webhookSecret,n=300){return await this.verifySignature(e,r,o,n),JSON.parse(e)}async verifySignature(e,r,o=this._client.webhookSecret,n=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,Lo,"m",wc).call(this,o);let s=T([r]).values,a=_(this,Lo,"m",$s).call(this,s,"webhook-signature"),i=_(this,Lo,"m",$s).call(this,s,"webhook-timestamp"),u=_(this,Lo,"m",$s).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new $e("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>n)throw new $e("Webhook timestamp is too old");if(l>d+n)throw new $e("Webhook timestamp is too new");let p=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=o.startsWith("whsec_")?Buffer.from(o.replace("whsec_",""),"base64"):Buffer.from(o,"utf-8"),x=u?`${u}.${i}.${e}`:`${i}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of p)try{let y=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,y,new TextEncoder().encode(x)))return}catch{continue}throw new $e("The given webhook signature does not match the expected signature")}};Lo=new WeakSet,wc=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")},$s=function(e,r){if(!e)throw new Error("Headers are required");let o=e.get(r);if(o==null)throw new Error(`Missing required header: ${r}`);return o};var Ac=Symbol.for("openai.node.providerDefinitions.v1"),xc=globalThis,Ic=xc[Ac],vc=Ic??new WeakMap;Ic||Object.defineProperty(xc,Ac,{value:vc});function Tc(t){let e=vc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var vi,Ti,En,Sc,Ag="workload-identity-auth",O=class{constructor(e={}){vi.add(this),En.set(this,void 0),this.completions=new Ht(this),this.chat=new ht(this),this.embeddings=new Zt(this),this.files=new Yt(this),this.images=new rr(this),this.audio=new De(this),this.moderations=new nr(this),this.models=new or(this),this.fineTuning=new ke(this),this.graders=new vt(this),this.vectorStores=new Qe(this),this.webhooks=new lr(this),this.beta=new Ce(this),this.batches=new Bt(this),this.uploads=new Tt(this),this.admin=new yt(this),this.responses=new Ue(this),this.realtime=new Je(this),this.conversations=new xt(this),this.evals=new It(this),this.containers=new At(this),this.skills=new Ze(this),this.videos=new ir(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(b.length)throw new C(`The \`provider\` option cannot be used with ${b.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:o=r?null:Te("OPENAI_BASE_URL"),apiKey:n=r?null:Te("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Te("OPENAI_ADMIN_KEY")??null,organization:a=r?null:Te("OPENAI_ORG_ID")??null,project:i=r?null:Te("OPENAI_PROJECT_ID")??null,webhookSecret:u=Te("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,p=r?Tc(r):void 0,f={apiKey:n,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...d,baseURL:p?.baseURL??(o||"https://api.openai.com/v1")};if(n&&l)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!n&&!s&&!l)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&bu())throw new C(`It looks like you're running in a browser-like environment.
56
+
57
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
58
+ If you understand the risks and have appropriate mitigations in place,
59
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
60
+
61
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
62
+
63
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
64
+ `);this.baseURL=f.baseURL,this.timeout=f.timeout??Ti.DEFAULT_TIMEOUT,this.logger=f.logger??console;let x="warn";this.logLevel=x,this.logLevel=ti(f.logLevel,"ClientOptions.logLevel",this)??ti(Te("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??x,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??ls(),P(this,En,Iu,"f");let w=r?void 0:Te("OPENAI_CUSTOM_HEADERS");if(w){let b={};for(let y of w.split(`
65
+ `)){let S=y.indexOf(":");S>=0&&(b[y.substring(0,S).trim()]=y.substring(S+1).trim())}f.defaultHeaders=T([b,f.defaultHeaders])}this._options=f,this._provider=p,l&&(this._workloadIdentityAuth=new hs(l,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,o=e.provider??r,n={...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 o&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,o!==r&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:o})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&o.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 Ou(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${qa()}`}makeStatusError(e,r,o,n){return V.generate(e,r,o,n)}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(o){throw o instanceof C?o:new C(`Failed to get token from 'apiKey' function: ${o.message}`,{cause:o})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,o){let n=!_(this,vi,"m",Sc).call(this)&&o||this.baseURL,s=mu(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Ka(a)||!Ka(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:o}){}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,o){return this.request(Promise.resolve(o).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new zt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,o){let n=await e,s=n.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(n);let{req:a,url:i,timeout:u}=await this.buildRequest(n,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:n}),await this._provider?.prepareRequest?.(a,{url:i,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=o===void 0?"":`, retryOf: ${o}`,p=Date.now();if(Z(this).debug(`[${l}] sending request`,Ke({retryOfRequestLogID:o,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new W;let f=n.__security??{bearerAuth:!0},x=new AbortController,w=await this.fetchWithAuth(i,a,u,x,f).catch(an),b=Date.now();if(w instanceof globalThis.Error){let h=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new W;let I=sn(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Z(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${h}`),Z(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${h})`,Ke({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),this.retryRequest(n,r,o??l);throw Z(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ke({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),w instanceof Nt||w instanceof ln?w:I?new Ne:new ct({message:xg(w),cause:w})}let y=[...w.headers.entries()].filter(([h])=>h==="x-request-id").map(([h,I])=>", "+h+": "+JSON.stringify(I)).join(""),S=`[${l}${d}${y}] ${a.method} ${i} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-p}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Wa(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,o??l);let h=await this.shouldRetry(w);if(r&&h){let H=`retrying, ${r} attempts remaining`;return await Wa(w.body),Z(this).info(`${S} - ${H}`),Z(this).debug(`[${l}] response error (${H})`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:b-p})),this.retryRequest(n,r,o??l,w.headers)}let I=h?"error; no more retries left":"error; not retryable";Z(this).info(`${S} - ${I}`);let k=await w.text().catch(H=>an(H).message),U=gu(k),q=U?void 0:k;throw Z(this).debug(`[${l}] response error (${I})`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,message:q,durationMs:Date.now()-p})),this.makeStatusError(w.status,U,q,w.headers)}return Z(this).info(S),Z(this).debug(`[${l}] response start`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:b-p})),{response:w,options:n,controller:x,requestLogID:l,retryOfRequestLogID:o,startTime:p}}getAPIList(e,r,o){return this.requestAPIList(r,o&&"then"in o?o.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...o})}requestAPIList(e,r){let o=this.makeRequest(r,null,void 0);return new mn(this,o,e)}async fetchWithAuth(e,r,o,n,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${Ag}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,o,n)}async fetchWithTimeout(e,r,o,n){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(n);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,o),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,p={signal:n.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,o,n){let s,a=n?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=n?.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 ze(s),this.makeRequest(e,r-1,o)}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 o={...e},{method:n,path:s,query:a,defaultBaseURL:i}=o,u=this.buildURL(s,a,i);"timeout"in o&&hu("timeout",o.timeout),o.timeout=o.timeout??this.timeout;let{bodyHeaders:l,body:d,isStreamingBody:p}=this.buildBody({options:o});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:r});return{req:{method:n,headers:f,...o.signal&&{signal:o.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...o.fetchOptions??{}},url:u,timeout:o.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:o,retryCount:n}){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(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Au(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,o,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:o}=e;if(!r)return r===void 0&&"body"in e?{..._(this,En,"f").call(this,{body:r,headers:T([o])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=T([o]),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"&&n.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:us(r),isStreamingBody:!0}:typeof r=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,En,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ti=O,En=new WeakMap,vi=new WeakSet,Sc=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=Ti;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=C;O.APIError=V;O.APIConnectionError=ct;O.APIConnectionTimeoutError=Ne;O.APIUserAbortError=W;O.NotFoundError=Sr;O.ConflictError=Cr;O.RateLimitError=Er;O.BadRequestError=Ir;O.AuthenticationError=vr;O.InternalServerError=Mr;O.PermissionDeniedError=Tr;O.UnprocessableEntityError=kr;O.InvalidWebhookSignatureError=$e;O.toFile=hn;O.Completions=Ht;O.Chat=ht;O.Embeddings=Zt;O.Files=Yt;O.Images=rr;O.Audio=De;O.Moderations=nr;O.Models=or;O.FineTuning=ke;O.Graders=vt;O.VectorStores=Qe;O.Webhooks=lr;O.Beta=Ce;O.Batches=Bt;O.Uploads=Tt;O.Admin=yt;O.Responses=Ue;O.Realtime=Je;O.Conversations=xt;O.Evals=It;O.Containers=At;O.Skills=Ze;O.Videos=ir;function xg(t){if(Ig(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 Ig(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let o=e;if(o.code==="UND_ERR_INVALID_ARG"&&typeof o.message=="string"&&o.message.includes("invalid onRequestStart method"))return!0;e=o.cause}return!1}function vg(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 xe(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Ne.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError",Et(e,!0)):t.constructor.name===W.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",Et(e,!1)):vg(t)?e=Il.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Et(nn(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=Et(nn(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=Et(nn(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=Et(nn(t,"MODEL_NOT_FOUND"),!1):e=t,e}var Ee=t=>t();function Ye(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Tg(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 zs(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Sg="LC_AUTOGENERATED";function ur(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'."),Sg)}function Xe(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(!Gn.isInstance(t))throw new Error("Invalid generic chat message");return Tg(t);default:throw new Error(`Unknown message type: ${e}`)}}function Cc(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function et(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:o,azureOpenAIBasePath:n,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((o||a)&&n&&e)return`${n}/${e}`;if((o||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(o||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 Ci(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function kc(t){let e=Ee(()=>{if(Ci(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ci(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,o])=>typeof o=="string").map(([o,n])=>[o,n]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function Ec(){let t=Al();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function tt(t,e=!1,r="1.0.0"){let o=kc(t),n=Ec(),s=`langchainjs${e?"-azure":""}-openai`;return{...o,"User-Agent":o["User-Agent"]?`${s}/${r} (${n})${o["User-Agent"]}`:`${s}/${r} (${n})`}}function Mc(t,e){let r;return Ar(t)?r=va(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Cg(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Pc(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(Oc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
66
+ `)}function Oc(t,e){let r=[];for(let[o,n]of Object.entries(t.properties??{}))n.description&&e<2&&r.push(`// ${n.description}`),t.required?.includes(o)?r.push(`${o}: ${Ls(n,e)},`):r.push(`${o}?: ${Ls(n,e)},`);return r.map(o=>" ".repeat(e)+o).join(`
67
+ `)}function Ls(t,e){if(Cg(t))return t.anyOf.map(r=>Ls(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["{",Oc(t,e+2),"}"].join(`
68
+ `);case"array":return t.items?`${Ls(t.items,e)}[]`:"any[]";default:return""}}function js(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function jo(t){return"type"in t&&t.type!=="function"}function Rc(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 Nc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function cr(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Ds(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function $c(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 zc(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 Lc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function jc(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 Dc(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 Fc(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 qc=Symbol("Let zodToJsonSchema decide on which parser to use"),Uc={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"},Bc=t=>typeof t=="string"?{...Uc,basePath:["#"],definitions:{},name:t}:{...Uc,basePath:["#"],definitions:{},...t};var Mn=t=>"_def"in t?t._def:t;function Kc(t){if(!t)return!0;for(let e in t)return!1;return!0}var Gc=t=>{let e=Bc(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(([o,n])=>[Mn(n),{def:Mn(n),path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function ki(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function j(t,e,r,o,n){t[e]=r,ki(t,e,o,n)}function Vc(){return{}}function Wc(t,e){let r={type:"array"};return t.type?._def?.typeName!==$.ZodAny&&(r.items=R(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&j(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&j(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(j(r,"minItems",t.exactLength.value,t.exactLength.message,e),j(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Hc(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":e.target==="jsonSchema7"?o.inclusive?j(r,"minimum",o.value,o.message,e):j(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?j(r,"maximum",o.value,o.message,e):j(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",o.value,o.message,e));break;case"multipleOf":j(r,"multipleOf",o.value,o.message,e);break}return r}function Jc(){return{type:"boolean"}}function Zc(t,e,r){return R(t.type._def,e,r)}var Qc=(t,e,r)=>R(t.innerType._def,e,r);function Ei(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,s)=>Ei(t,e,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return kg(t,e)}}var kg=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":j(r,"minimum",o.value,o.message,e);break;case"max":j(r,"maximum",o.value,o.message,e);break}return r};function Yc(t,e,r){return{...R(t.innerType._def,e,r),default:t.defaultValue()}}function Xc(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function ed(t){return{type:"string",enum:[...t.values]}}var Eg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function td(t,e){let r=[R(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),R(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),o=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(s=>{if(Eg(s))n.push(...s.allOf),s.unevaluatedProperties===void 0&&(o=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else o=void 0;n.push(a)}}),n.length?{allOf:n,...o}:void 0}function rd(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 Mi,dr={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:()=>(Mi===void 0&&(Mi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mi),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 Fs(t,e){let r={type:"string"};function o(n){return e.patternStrategy==="escape"?Mg(n):n}if(t.checks)for(let n of t.checks)switch(n.kind){case"min":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Me(r,"email",n.message,e);break;case"format:idn-email":Me(r,"idn-email",n.message,e);break;case"pattern:zod":Pe(r,dr.email,n.message,e);break}break;case"url":Me(r,"uri",n.message,e);break;case"uuid":Me(r,"uuid",n.message,e);break;case"regex":Pe(r,n.regex,n.message,e);break;case"cuid":Pe(r,dr.cuid,n.message,e);break;case"cuid2":Pe(r,dr.cuid2,n.message,e);break;case"startsWith":Pe(r,RegExp(`^${o(n.value)}`),n.message,e);break;case"endsWith":Pe(r,RegExp(`${o(n.value)}$`),n.message,e);break;case"datetime":Me(r,"date-time",n.message,e);break;case"date":Me(r,"date",n.message,e);break;case"time":Me(r,"time",n.message,e);break;case"duration":Me(r,"duration",n.message,e);break;case"length":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Pe(r,RegExp(o(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&Me(r,"ipv4",n.message,e),n.version!=="v4"&&Me(r,"ipv6",n.message,e);break}case"emoji":Pe(r,dr.emoji,n.message,e);break;case"ulid":{Pe(r,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Me(r,"binary",n.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Pe(r,dr.base64,n.message,e);break}}break}case"nanoid":Pe(r,dr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Mg=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Me=(t,e,r,o)=>{t.format||t.anyOf?.some(n=>n.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&o.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&&o.errorMessages&&{errorMessage:{format:r}}})):j(t,"format",e,r,o)},Pe=(t,e,r,o)=>{t.pattern||t.allOf?.some(n=>n.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:od(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):j(t,"pattern",od(e,o),r,o)},od=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let o={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=o.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<n.length;l++){if(a){s+=n[l],a=!1;continue}if(o.i){if(i){if(n[l].match(/[a-z]/)){u?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),u=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],u=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(o.m){if(n[l]==="^"){s+=`(^|(?<=[\r
69
+ ]))`;continue}else if(n[l]==="$"){s+=`($|(?=[\r
70
+ ]))`;continue}}if(o.s&&n[l]==="."){s+=i?`${n[l]}\r
71
+ `:`[${n[l]}\r
72
+ ]`;continue}s+=n[l],n[l]==="\\"?a=!0:i&&n[l]==="]"?i=!1:!i&&n[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 Us(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,n)=>({...o,[n]:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===$.ZodString&&t.keyType._def.checks?.length){let o=Object.entries(Fs(t.keyType._def,e)).reduce((n,[s,a])=>s==="type"?n:{...n,[s]:a},{});return{...r,propertyNames:o}}else if(t.keyType?._def.typeName===$.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function nd(t,e){if(e.mapStrategy==="record")return Us(t,e);let r=R(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},o=R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function sd(t){let e=t.values,o=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(o.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function ad(){return{not:{}}}function id(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Pn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ud(t,e){if(e.target==="openApi3")return ld(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in Pn&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,s)=>{let a=Pn[s._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){let n=o.filter((s,a,i)=>i.indexOf(s)===a);return{type:n.length>1?n:n[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(s=>!o.includes(s))],[])};return ld(t,e)}var ld=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>R(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function cd(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:Pn[t.innerType._def.typeName],nullable:!0}:{type:[Pn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function dd(t,e){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",ki(r,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?j(r,"minimum",o.value,o.message,e):j(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?j(r,"maximum",o.value,o.message,e):j(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",o.value,o.message,e));break;case"multipleOf":j(r,"multipleOf",o.value,o.message,e);break}return r}function Pg(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function pd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((o,[n,s])=>{if(s===void 0||s._def===void 0)return o;let a=[...e.currentPath,"properties",n],i=R(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return o;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:{...o.properties,[n]:i},required:s.isOptional()&&!e.openaiStrictMode?o.required:[...o.required,n]}},{properties:{},required:[]}),additionalProperties:Pg(t,e)};return r.required.length||delete r.required,r}var md=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return R(t.innerType._def,{...e,currentPath:e.currentPath},r);let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return o?{anyOf:[{not:{}},o]}:{}};var fd=(t,e,r)=>{if(e.pipeStrategy==="input")return R(t.in._def,e,r);if(e.pipeStrategy==="output")return R(t.out._def,e,r);let o=R(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=R(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,n].filter(s=>s!==void 0)}};function hd(t,e,r){return R(t.type._def,e,r)}function gd(t,e){let o={type:"array",uniqueItems:!0,items:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&j(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&j(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function yd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:R(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function _d(){return{not:{}}}function wd(){return{}}var bd=(t,e,r)=>R(t.innerType._def,e,r);function R(t,e,r=!1){let o=e.seen.get(t);if(e.override){let s=e.override?.(t,e,o,r);if(s!==qc)return s}if(o&&!r){let s=Og(o,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let s=$g(t,t.typeName,e,r);return s&&zg(t,e,s),n.jsonSchema=s,s}finally{r&&o&&e.seen.set(t,o)}}var Og=(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((o,n)=>n===0?o:Rg(o)).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:Ng(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((o,n)=>e.currentPath[n]===o)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ad="_x_",Rg=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Ad))return t;let e=Ad;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Ng=(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("/")},$g=(t,e,r,o)=>{switch(e){case $.ZodString:return Fs(t,r);case $.ZodNumber:return dd(t,r);case $.ZodObject:return pd(t,r);case $.ZodBigInt:return Hc(t,r);case $.ZodBoolean:return Jc();case $.ZodDate:return Ei(t,r);case $.ZodUndefined:return _d();case $.ZodNull:return id(r);case $.ZodArray:return Wc(t,r);case $.ZodUnion:case $.ZodDiscriminatedUnion:return ud(t,r);case $.ZodIntersection:return td(t,r);case $.ZodTuple:return yd(t,r);case $.ZodRecord:return Us(t,r);case $.ZodLiteral:return rd(t,r);case $.ZodEnum:return ed(t);case $.ZodNativeEnum:return sd(t);case $.ZodNullable:return cd(t,r,o);case $.ZodOptional:return md(t,r,o);case $.ZodMap:return nd(t,r);case $.ZodSet:return gd(t,r);case $.ZodLazy:return R(t.getter()._def,r,o);case $.ZodPromise:return hd(t,r,o);case $.ZodNaN:case $.ZodNever:return ad();case $.ZodEffects:return Xc(t,r,o);case $.ZodAny:return Vc();case $.ZodUnknown:return wd();case $.ZodDefault:return Yc(t,r,o);case $.ZodBranded:return Zc(t,r,o);case $.ZodReadonly:return bd(t,r,o);case $.ZodCatch:return Qc(t,r,o);case $.ZodPipeline:return fd(t,r,o);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(n=>{})(e)}},zg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Pi=(t,e)=>{let r=Gc(e),o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=R(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(n.title=s);let a=(()=>{if(Kc(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let p=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(p.length===0)break;for(let[f,x]of p)u[f]=R(Mn(x),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=o===void 0?a?{...n,[r.definitionPath]:a}:n:r.nameStrategy==="duplicate-ref"?{...n,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[o]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...a,[o]:n}};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 xd(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return rt(e,[],e)}function Oi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Oi(e))return!0;for(let e of t.anyOf??[])if(Oi(e))return!0;return!1}function rt(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!pr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let o=t.$defs;if(pr(o))for(let[f,x]of Object.entries(o))rt(x,[...e,"$defs",f],r);let n=t.definitions;if(pr(n))for(let[f,x]of Object.entries(n))rt(x,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(pr(i)){for(let[f,x]of Object.entries(i))if(!Oi(x)&&!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,x])=>[f,rt(x,[...e,"properties",f],r)]))}let u=t.items;pr(u)&&(t.items=rt(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,x)=>rt(f,[...e,"anyOf",String(x)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=rt(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,x)=>rt(f,[...e,"allOf",String(x)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&jg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=Lg(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!pr(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,rt(t,e,r)}return t}function Lg(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),o=t;for(let n of r){if(!pr(o))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(o)}`);let s=o[n];if(s===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);o=s}return o}function pr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jg(t,e){let r=0;for(let o in t)if(r++,r>e)return!0;return!1}function Dg(t,e){return Pi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Fg(t){return xd(Ml(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let o=e._zod.def;if(o.type==="union"&&"discriminator"in o&&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 Ug(t){return"_zod"in t}function Id(t,e,r){return Gu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Ug(t)?Fg(t):Dg(t,{name:e})}},o=>t.parse(JSON.parse(o)))}var vd=["jsonSchema","functionCalling","jsonMode"];function Td(t,e){if(typeof e<"u"&&!vd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${vd.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 qg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Sd(t,e,r){if(Pl(t))return Id(t,e,r);if(Hn(t))return qg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Pt(t,{cycles:"ref",reused:"ref",override(o){o.jsonSchema.title=e}})}},o=>kl(t,JSON.parse(o)));throw new Error("Unsupported schema response format")}function Cd(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(o=>typeof o?.image_url?.url=="string").map(o=>({type:"image",url:o.image_url.url}));return[{type:"text",text:t},...r]}return t}var kd={"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}};var qs="**REDACTED**";function Do(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var mr=class extends Yn{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}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=qs),"authorization"in o&&(o.authorization=qs),o})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=qs),"authorization"in o&&(o.authorization=qs),o})}:t}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0,r=Ta({baseURL:t?.configuration?.baseURL??(ge("OPENAI_API_BASE")||ge("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??r.apiKey??ge("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ge("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration,baseURL:r.baseURL},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.8")}_getReasoningParams(t){if(!Ye(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&&Mt(t.json_schema.schema)?Sd(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=et({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=tt(r.defaultHeaders),this.client=new O(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return cr(t)?Fc(t.metadata.customTool):Zn(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Mc(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(o=>{if(jo(o)||cr(o))return o;if(Rc(o))return o.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(o,{strict:r});return Ar(o)&&o.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...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,o=0;this.model==="gpt-3.5-turbo-0301"?(r=4,o=-1):(r=3,o=1);let n=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Xe(s))]),u=s.name!==void 0?o+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(p){console.error("Error parsing function arguments",p,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:n}}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 o=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Pc(e);o+=await this.getNumTokens(n),o+=9}return e&&t.find(n=>n._getType()==="system")&&(o-=4),r==="none"?o+=1:typeof r=="object"&&(o+=await this.getNumTokens(r.name)+4),o}async moderateContent(t,e){let r=this._getClientOptions(e?.options),o={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(o,r)}catch(n){throw xe(n)}})}get profile(){return kd[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,o,{schema:n,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=Td(this.model,e?.method);if(i==="jsonMode"){o=xa(n);let u=Pt(n);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=Pt(n),l={name:s??"extract",description:ba(u),schema:Mt(n)?n: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}}}),Mt(n)||Wn(n)){let d=xa(n);o=it.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:d.invoke(p.content))}else o=new Nl}else{let u=s??"extract",l=Pt(n),d;Mt(n)||Wn(n)?d={name:u,description:l.description,parameters:l}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,u=n.name):(u=n.title??u,d={name:u,description:n.description??"",parameters:n}),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}:{}}),o=$l(n,u)}return zl(r,o,a)}};var On={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=ya({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||"",o;try{o=ga(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(o.type!=="audio"||o.subtype!=="wav"&&o.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:o.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=ga(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=ya({dataUrl:t.url}),r=ur(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=ur(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`)}},Bs=({message:t,rawResponse:e,includeRawResponse:r})=>{let o=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of o??[])try{s.push(Qn(l,{returnId:!0}))}catch(d){a.push(wr(l,d.message))}let i={function_call:t.function_call,tool_calls:o};r!==void 0&&(i.__raw_response=e),n!==void 0&&(i.reasoning_content=n);let u={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new F({content:Cd(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 Gn(t.content||"",t.role??"unknown")}},Ks=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:o})=>{let n=t.role??o,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(n==="user")return new wa({content:s,response_metadata:i});if(n==="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 at({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return n==="system"?new Vn({content:s,response_metadata:i}):n==="developer"?new Vn({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new Tl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):n==="tool"?new _a({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new vl({content:s,role:n,response_metadata:i})},Ri=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=Sl(()=>{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=ur(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}}}},Ni=({message:t,model:e})=>{let r=Xe(t);if(r==="system"&&Ye(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return F.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Aa):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&B.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*o(n){for(let s of n){s.type==="text"&&(yield{type:"text",text:s.text});let a=Ri(s);a&&(yield a)}}return{role:"user",content:Array.from(o(t.contentBlocks))}},fr=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Ni({message:r});let o=Xe(r);o==="system"&&Ye(e)&&(o="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(a=>Bn(a)?Kn(a,On):typeof a=="object"&&a!==null&&"type"in a&&(a.type==="tool_use"||a.type==="tool_call"||a.type==="reasoning"||a.type==="reasoning_content"||a.type==="thinking")?[]:a),s={role:o,content:n};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),F.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Aa):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),B.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var Gs=class extends mr{constructor(t,e){super(Do(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 o={};t?.stream_options!==void 0?o={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(o={stream_options:{include_usage:!0}});let n={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:js(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...o,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&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(n.reasoning_effort=s.effort),Ye(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let o={},n=this.invocationParams(e),s=fr({messages:t,model:this.model});if(n.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let x of a){x.message.response_metadata={...x.generationInfo,...x.message.response_metadata};let w=x.generationInfo?.completion??0;i[w]===void 0?i[w]=x:i[w]=i[w].concat(x)}let u=Object.entries(i).sort(([x],[w])=>parseInt(x,10)-parseInt(w,10)).map(([x,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return o.input_tokens=p,o.output_tokens=f,o.total_tokens=p+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}else{let a=await this.completionWithRetry({...n,stream:!1,messages:s},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:p}=a?.usage??{};i&&(o.output_tokens=(o.output_tokens??0)+i),u&&(o.input_tokens=(o.input_tokens??0)+u),l&&(o.total_tokens=(o.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(o.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(o.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let x of a?.choices??[]){let w={text:x.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(x.message??{role:"assistant"},a)};w.generationInfo={...x.finish_reason?{finish_reason:x.finish_reason}:{},...x.logprobs?{logprobs:x.logprobs}:{}},st(w.message)&&(w.message.usage_metadata=o),w.message=new F(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let o=fr({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:o,stream:!0},s=await this.completionWithRetry(n,e),a=this.streamUsage??e.streamUsage;yield*Xn(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 o=fr({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:o,stream:!0},s,a=await this.completionWithRetry(n,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 p=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let x={...f};l.finish_reason!=null&&(x.finish_reason=l.finish_reason,x.system_fingerprint=u.system_fingerprint,x.model_name=u.model,x.service_tier=u.service_tier),this.logprobs&&(x.logprobs=l.logprobs);let w=new rn({message:p,text:p.content,generationInfo:x});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 rn({message:new at({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{maxRetries:r,...o}=e??{},n=this._getClientOptions(o),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(a){throw xe(a)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Ks({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Bs({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Vs="__openai_function_call_ids__",Ws="__openai_custom_tool_call_ids__";function $d(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 Kg(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 Fo=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}},Rn=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],o=[],n=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:n,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($d),...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(Qn(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),o.push(wr(u,d))}a[Vs]??={},i.id&&(a[Vs][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=$c(i);u?(r.push(u),a[Ws]??={},i.id&&i.call_id&&(a[Ws][i.call_id]=i.id)):o.push(wr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=zc(i);u?r.push(u):o.push(wr(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 F({id:t.id,content:e,tool_calls:r,invalid_tool_calls:o,usage_metadata:Fo(t.usage),additional_kwargs:a,response_metadata:s})},$i=t=>{let e=(t.summary.length>1?t.summary.reduce((r,o)=>{let n=r[r.length-1];return n.index===o.index?n.text+=o.text:r.push(o),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([o])=>o!=="index")));return{...t,summary:e}},Hs=t=>{let e=[],r={},o,n=[],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:[$d(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")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Vs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.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[Ws]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.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=Rn(t.response);if(o=Fo(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")n.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,p)=>({...d,index:p})):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 rn({text:e.map(u=>u.text).join(""),message:new at({id:i,content:e,tool_call_chunks:n,usage_metadata:o,additional_kwargs:a,response_metadata:s}),generationInfo:r})},zi=t=>{let e=F.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let o=Ee(()=>{try{let h=Xe(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),n=h=>o==="assistant"?{type:"output_text",text:h,annotations:[]}:{type:"input_text",text:h},s,a=new Set,i=new Set,u=new Map,l=new Map;function*d(){if(!s)return;let h=s.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield s),s=void 0}let p=(h,I)=>{s||(s={type:"message",role:o,content:[],...I?{phase:I}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[n(s.content),...h]:[...h]:s.content.push(...h)},f=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},x=h=>{let I=Ee(()=>{let k=h.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(h.fileId)return{type:"input_image",detail:I,file_id:h.fileId};if(h.url)return{type:"input_image",detail:I,image_url:h.url};if(h.data){let k=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:I,image_url:`data:${h.mimeType??"image/png"};base64,${k}`}}},w=h=>{if(h.fileId){let I=zs(h);return{type:"input_file",file_id:h.fileId,...I?{filename:I}:{}}}if(h.url){let I=zs(h);return{...I?{filename:I}:{},type:"input_file",file_url:h.url}}if(h.data){let I=ur(h),k=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,${k}`,filename:I}}},b=h=>{let I=Ee(()=>{if(Array.isArray(h.summary)){let U=h.summary?.map(q=>q?.text).filter(q=>typeof q=="string")??[];if(U.length>0)return U}return h.reasoning?[h.reasoning]:[]}),k=I.length>0?I.map(U=>({type:"summary_text",text:U})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:k}},y=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:f(h.args)}),S=h=>{let I=f(h.output),k=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:I,...k?{status:k}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let I=Ee(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});p([n(h.text)],I)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*d(),yield b(h);else if(h.type==="tool_call"){yield*d();let I=h.id??"";I&&(a.add(I),u.delete(I)),yield y(h)}else if(h.type==="tool_call_chunk"){if(h.id){let I=u.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),u.set(h.id,I)}}else if(h.type==="server_tool_call"){yield*d();let I=h.id??"";I&&(i.add(I),l.delete(I)),yield y(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let I=l.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),l.set(h.id,I)}}else if(h.type==="server_tool_call_result")yield*d(),yield S(h);else if(h.type!=="audio")if(h.type==="file"){let I=w(h);I&&p([I])}else if(h.type==="image"){let I=x(h);I&&p([I])}else if(h.type==="video"){let I=w(h);I&&p([I])}else h.type==="text-plain"?h.text&&p([n(h.text)]):h.type==="non_standard"&&e&&(yield*d(),yield h.value)}yield*d();for(let[h,I]of u){if(!h||a.has(h))continue;let k=I.args.join("");!I.name&&!k||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:k})}for(let[h,I]of l){if(!h||i.has(h))continue;let k=I.args.join("");!I.name&&!k||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:k})}}return Array.from(r())},Uo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(o=>{let n=o.response_metadata;if(n?.output_version==="v1")return zi(o);let s=o.additional_kwargs,a=Xe(o);if(a==="system"&&Ye(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=o;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 p=i.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(b=>"type"in b))return n?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=$i(u);i.push(b)}let{content:d}=o;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",...o.id&&!e&&o.id.startsWith("msg_")?{id:o.id}:{},content:Ee(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let S=y;return{type:"output_text",text:S.text,annotations:(S.annotations??[]).map(Kg)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Ee(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let p=s?.[Vs],f=s?.[Ws];F.isInstance(o)&&o.tool_calls?.length?i.push(...o.tool_calls.map(b=>jc(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}:Lc(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:p?.[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:p?.[b.id]}})));let x=n?.output?.length?n?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(x!=null){let b=x?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof o.content=="string")return{type:"message",role:a,content:o.content};let i=[],u=o.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}),Bn(l)){if(l.type==="file"){let d=zs(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:ur(l)}}return Kn(l,On)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ee(()=>{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:Ee(()=>{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*Li(t,e={}){let r=e.streamUsage??!0,o=e.provider??"openai",n=new Map,s=new Map,a=0,i=!1,u,l,d,p,f=new Set,x=(y,S)=>{let h=s.get(y);if(h!==void 0)return{index:h,isNew:!1};let I=a++;return s.set(y,I),n.set(I,{...S}),{index:I,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let S=n.get(y);S&&(f.add(y),yield{event:"content-block-finish",index:y,content:Ll(S)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:o,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:S,isNew:h}=x(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});h&&(yield{event:"content-block-start",index:S,content:{type:"text",text:""}});let I=n.get(S);I.text=(I.text??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:S,isNew:h}=x(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});h&&(yield{event:"content-block-start",index:S,content:{type:"reasoning",reasoning:""}});let I=n.get(S);I.reasoning=(I.reasoning??"")+y.delta,yield{event:"content-block-delta",index:S,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 S=`tool:${y.output_index}`,h=y.item.type==="custom_tool_call",I=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:k,isNew:U}=x(S,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:I,index:y.output_index,...h?{isCustomTool:!0}:{}});if(U&&(yield{event:"content-block-start",index:k,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:I,index:y.output_index}}),I){let q=n.get(k);yield{event:"content-block-delta",index:k,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:S,isNew:h}=x(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});h&&(yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let I=n.get(S);I.args=(I.args??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...I.id!=null?{id:I.id}:{},...I.name!=null?{name:I.name}:{},args:I.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let S=`tool:${y.output_index}`,h=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:I,isNew:k}=x(S,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:h,index:y.output_index});if(k)yield{event:"content-block-start",index:I,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:h,index:y.output_index}};else{let U=n.get(I);U.args=h,U.id=y.item.call_id,U.name=y.item.name}yield*b(I);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=Gg(y.response.status,y.type),p={model_provider:o,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=Fo(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:o,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of n)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function Gg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Js=class extends mr{constructor(t,e){super(Do(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:Nc(t?.tool_choice)?t?.tool_choice:(()=>{let n=js(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,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},o=this._getReasoningParams(t);return o!==void 0&&(r.reasoning=o),r}async _generate(t,e,r){e.signal?.throwIfAborted();let o=this.invocationParams(e);if(o.stream){let n=this._streamResponseChunks(t,e,r),s;for await(let a of n)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 n=await this.completionWithRetry({input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...o,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:n.output_text,message:Rn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let o=await this.completionWithRetry({...this.invocationParams(e),input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Li(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(o,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let o=await this.completionWithRetry({...this.invocationParams(e),input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of o){if(e.signal?.aborted)return;let s=Hs(n);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(n){throw xe(n)}}async completionWithRetry(t,e){let{maxRetries:r,...o}=e??{},n=this._getClientOptions(o);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw xe(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let o of t)if(jo(o))o.type==="image_generation"&&e?.stream&&(o.partial_images=1),r.push(o);else if(cr(o)){let n=o.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Zn(o)){let n={};for(let[s,a]of Object.entries(o))s!=="type"&&s!=="function"&&(n[s]=a);r.push({type:"function",name:o.function.name,parameters:o.function.parameters,description:o.function.description,strict:e?.strict??null,...n})}else Ds(o)&&r.push(Dc(o));return r}};var Zs=class zd extends mr{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 o=Do(e,r);super(o),this.fields=o,this.useResponsesApi=o?.useResponsesApi??!1,this.responses=o?.responses??new Js(o),this.completions=o?.completions??new Gs(o)}_useResponsesApi(e){let r=e?.tools?.some(jo),o=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(Ds)||e?.tools?.some(cr);return this.useResponsesApi||r||o||n||Cc(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,o){return this._useResponsesApi(r)?this.responses._generate(e,r,o):this.completions._generate(e,r,o)}async*_streamChatModelEvents(e,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),o);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),o)}async*_streamResponseChunks(e,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),o);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),o)}withConfig(e){let r=new zd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Qs=class extends Ol{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??ge("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ge("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Ia(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let a={model:this.model,input:s};return this.dimensions&&(a.dimensions=this.dimensions),this.encodingFormat&&(a.encoding_format=this.encodingFormat),this.embeddingWithRetry(a)}),o=await Promise.all(r),n=[];for(let s=0;s<o.length;s+=1){let a=e[s],{data:i}=o[s];for(let u=0;u<a.length;u+=1)n.push(i[u].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=et({baseURL:this.clientConfig.baseURL}),o={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=tt(o.defaultHeaders),this.client=new O(o)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw xe(r)}})}};var Jg=v.object({type:v.literal("screenshot")}),Zg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Qg=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Yg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),Xg=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),ey=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),ty=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),ry=v.object({type:v.literal("type"),text:v.string()}),oy=v.object({type:v.literal("wait"),duration:v.number().optional()}),ny=v.union([Jg,Zg,Qg,Yg,Xg,ey,ty,ry,oy]),aG=v.object({action:ny});var sy=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()}),cG=v.union([sy]);var fG=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 ay=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),iy=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),ly=v.object({type:v.literal("delete_file"),path:v.string()}),_G=v.union([ay,iy,ly]);var Dd={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Di={default:"text-embedding-ada-002"},ji=new Map,Ys=null,my=()=>{let t=Ld.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},Fd=async t=>{let e=my();ji.size===0&&(Ys||(Ys=(async()=>{try{(await jd(`${e}/models`)).data.models.forEach(o=>ji.set(o.name,o))}catch(o){throw Ys=null,o}})()),await Ys);let r=ji.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},fy=async(t="default")=>await Fd(Dd[t]),Ud=async(t="default")=>await Fd(Di[t]),hy=M.Root({agentExecutionContext:M({default:ka,reducer:Sa}),currentIntent:M({default:()=>"none",reducer:lt}),routing:M({default:()=>({mode:"auto"}),reducer:lt}),lastExecutedAgent:M({default:()=>"",reducer:lt}),requiresFollowUp:M({default:()=>!0,reducer:lt}),stepCount:M({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:M({default:()=>"",reducer:Ca})});var gy=t=>typeof t=="string"&&t.length>0?t:void 0,yy=()=>hl(),_y=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,wy=t=>{let e=t?.configurable;return{conversationId:gy(e?.thread_id),abortSignal:t?.signal,requestId:yy(),requestSource:_y(py.applicationName)}},by=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},qd=async({config:t})=>{let e=Ld.getDefault(),r=(await dy.getCredential(`${e.url}/sharing`))?.token;return async(o,n)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=wy(t),l=new Headers(n?.headers);for(let p of[...l.keys()]){let f=p.toLowerCase();(f==="authorization"||f==="api-key"||f.startsWith("x-stainless-"))&&l.delete(p)}r&&r.length>0&&l.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(u&&u.length>0&&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&&n?.signal?AbortSignal.any([a,n.signal]):n?.signal??a;return(await jd(o instanceof Request?o.url:o.toString(),{body:by(n?.body),headers:Object.fromEntries(l),responseType:"native",signal:d})).data}},Fi=async(t={})=>{let{modelTier:e="default",config:r}=t,o=Dd[e],n=await fy(e);return new Zs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await qd({config:r})}})},Bd=async(t={})=>{let{tier:e="default",config:r}=t,o=Di[e],n=await Ud(e);return new Qs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await qd({config:r})},batchSize:2048,maxConcurrency:10})},Ay=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(Ay);var Kd="0.1",qo=1536,Gd="openai",Vd=Di.default,Wd=`Name: {name}
73
+ Title: {title}
74
+ Description: {description}`,Hd=`Name: {name}
75
+ Alias: {alias}
76
+ Description: {description}`,Jd=v.object({schemaVersion:v.literal(Kd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Gd),model:v.literal(Vd),dimensions:v.literal(qo),templates:v.object({layer:v.string().default(Wd),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(qo,{message:`Layer vector must be exactly ${qo} 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(qo,{message:`Field vector must be exactly ${qo} dimensions`})}))})).default([])});var xy=(t,e)=>{let r=jl.fromTemplate(t);return br.fromMessages([r,...e])};var Nn=async t=>{let{promptText:e,modelTier:r="default",messages:o,inputVariables:n,schema:s,config:a}=t,i=xy(e,o??[]),u=(await Fi({modelTier:r,config:a})).withStructuredOutput(s);return await i.pipe(u).invoke(n??{},a)};var Iy=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),BV=c.object({fields:c.array(Iy)});var KV=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var Zd=async t=>{try{return await(await Bd()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var Yd=t=>Array.isArray(t)&&t.every(tn),Ty=t=>typeof t=="object"&&t!=null&&"messages"in t&&Yd(t.messages),Sy=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ot=class extends Dl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:o,handleToolErrors:n}=e??{};super({name:r,tags:o,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=n??this.handleToolErrors}async runTool(t,e,r){let o=this.tools.find(n=>n.name===t.name);try{if(o===void 0)throw new Error(`Tool "${t.name}" not found.`);let n={...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 o.invoke(n,s);return tn(a)&&a.getType()==="tool"||kt(a)?a:new B({status:"success",name:o.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||qn(n))throw n;return new B({status:"error",content:`Error: ${n.message}
77
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Sy(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(Yd(t))s=t;else if(Ty(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(st(l)){i=l;break}}if(i==null||!st(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(kt))return Array.isArray(t)?r:{messages:r};let o=[],n=null;for(let s of r)kt(s)?s.graph===Be.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>bl(a))?n?n.goto.push(...s.goto):n=new Be({graph:Be.PARENT,goto:s.goto}):o.push(s):o.push(Array.isArray(t)?[s]:{messages:[s]});return n&&o.push(n),o}};var BW=M.Root({llmInputMessages:M({reducer:(t,e)=>on([],e),default:()=>[]})});function D(t,e){let r=t?.configurable?.context;if(!r||typeof r!="object")throw new Error("Agent context missing");let o=e.filter(n=>!(n in r));if(o.length)throw new Error(`Agent context missing: ${o.join(", ")}`);return r}var ky=t=>{let e=t.map?.allLayers.filter(o=>o.type==="feature"),r=0;return e?.forEach(o=>{let n=o;n.featureEffect&&(n.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},Ey=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return ky(r)},My=E(Ey,{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({})});var Py=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.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."},Oy=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return await Py(r)},Ry=E(Oy,{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({})});var Xd=750;function Bo(t){return"point"in t&&t.point!==void 0}function hr(t){return"layerId"in t&&t.layerId!==void 0}var St=async(t,e)=>{if(Bo(t)){let{point:r}=t;return{geometry:new Ny({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(hr(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 o=r.title??r.id,n=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:n,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Xd+1});if(!s.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${n}`};if(s.features.length>Xd)return{error:`Geometry filter for layer "${o}" 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]:ep.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"}},$y=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Ie=c.enum($y);var jy=async(t,e,r,o,n,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",o&&(i.geometry=o,i.spatialRelationship="intersects",n&&(i.distance=n),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}${o?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},Dy=async(t,e,r,o,n,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(n){let p=await St(n,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new zy({filter:new Ly({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:n?.distance,units:n?.units}),includedEffect:r,excludedEffect:o}),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 jy(e,t.layerId,u,i,n?.distance,n?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${n&&"layerId"in n?` using geometry from layer "${n.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},Fy=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:n="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=D(s,["mapView"]);return await Dy(t,a,o,n,e,r)},Uy=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:Ie.optional().describe("The units for the distance buffer.")}),qy=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:Ie.optional().describe("The units for the distance buffer.")}),By=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([Uy,qy]).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.")}),Ky=E(Fy,{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:By});var Wy=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),rp=t=>{if(!t)return!1;let e=t.toLowerCase();return Wy.has(e)},Ui=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},Hy=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Jy=t=>{if(typeof t=="string"&&t)return t;let e=Ui(t);return e?e.toISOString().slice(0,10):null};var Zy=(t,e,r)=>{let o=e?.toLowerCase();if(o&&!rp(o))return t;if(o==="date-only"){let s=Jy(t);return s?Gy(s,Xs("short-date")):t}if(o==="time-only"){if(typeof t=="string"&&t)return Vy(t,Xs("long-time"));let s=Ui(t);return s?tp(s,{...Xs("long-time"),timeZone:"UTC"}):t}let n=Ui(t);return n?tp(n,{...Xs("short-date-short-time"),timeZone:Hy(r)}):t},op=(t,e,r)=>{if(t&&typeof t!="function"){let o="getField"in r&&r.getField?.(t),n=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(n?.type==="coded-value"){let s=n.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},Qy=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Yy=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},Xy=(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}},e_=(t,e,r)=>{let o=Yy(t);if(!o)return t;let n={};e.dateStyle?n.dateStyle=e.dateStyle:(e.year&&(n.year=e.year),e.month&&(n.month=e.month)),e.timeStyle&&(n.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?n.hour12=!0:e.timeStyle&&e.hour12==="never"&&(n.hour12=!1),n.timeZone=Qy(r);try{return new Intl.DateTimeFormat(void 0,n).format(o)}catch{return t}},np=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,sp=(t,e,r,o,n)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?Xy(r,s):s?.type==="date-time"?!o||rp(o)?e_(r,s,n):r:Zy(r,o,n)},ap=(t,e,r,o)=>{let n=t.fieldsIndex?.get(e),s=op(e,r,t)??r;return sp(t,e,s,n?.type,o)},ip=(t,e)=>np(t,e),ea=(t,e,r)=>{let o=t.objectIdField,n=e.features.map(a=>a.attributes[o]),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===o){u[l.name]=d;return}let p=op(l.name,d,t)??d,f=np(t,l.name);u[f]=sp(t,l.name,p,l.type,r)}),u});return{objectIds:n,attributes:s}};var t_=(t,e,r)=>{let o=t.createQuery();return o.outFields=[e],o.where=r||"1=1",o.num=1,o},r_=async(t,e,r,o)=>{let n=o.map?.allLayers.find(d=>d.id===t),s=t_(n,e,r.where),a=(await n.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=ap(n,e,i,o.timeZone),l=ip(n,e);return{tool:"getAttribute",layerName:n.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function o_({layerId:t,fieldName:e,query:r},o){let{mapView:n}=D(o,["mapView"]),s=await r_(t,e,r,n);return JSON.stringify(s,null,2)}var n_=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.")})}),lp=E(o_,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:n_});var Ko=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let o=new Set((t.availableFields??[]).map(n=>n.toLowerCase()));return o.has("*")?!0:e.every(n=>o.has(n.toLowerCase()))};function gr(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Ct=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};var l_=async t=>{let{targetLayer:e,fieldName:r,statisticType:o,mapView:n,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=n.map?.allLayers.find(S=>S.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await n.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,f;if(a){let S=await St(a,n);if("error"in S)throw new Error(S.error);if(!S.geometry)throw hr(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(hr(a)){let h=n.map?.allLayers.find(I=>I.id===a.layerId);p={geometryLayerName:h?.title??h?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else Bo(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new i_({geometry:S.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let x=Ko(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let S={layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:gr(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[o]}};w=await s_(S);let h=["string","small-integer","integer"],I=l.domain?.type==="coded-value"?l.domain:null;(h.includes(l.type)||I)&&(b=(await a_({layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:gr(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((k,U)=>U.count-k.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(k=>({...k,value:I?I.getName(k.value)??k.value:k.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${o} = ${typeof w?.[o]=="number"?w[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:w?.[o]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:p}}};async function u_({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:o},n){let s=Ct(n,"layersAndFieldsRegistry"),{mapView:a}=D(n,["mapView"]),i=await l_({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:o});return JSON.stringify(i,null,2)}var c_=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:Ie.optional().describe("The units for the distance buffer.")}),d_=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:Ie.optional().describe("The units for the distance buffer.")}),p_=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([c_,d_]).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.")}),up=E(u_,{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.
78
+
79
+ USE THIS TOOL FOR:
80
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
81
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
82
+ - Questions requiring a mathematical aggregation across many features
83
+
84
+ DO NOT USE FOR:
85
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
86
+ - "Show / list / find features" \u2014 use queryFeatures instead
87
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
88
+
89
+ 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:p_});var h_=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),g_=async(t,e,r,o,n)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(o){let f=await St(o,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 o?o.where:"unknown criteria"}`}};u=f.geometry}else n&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new m_({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new f_({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=gr(s.definitionExpression,t.where||"1=1"),b.outFields=p.length?p:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),o?.distance&&(b.distance=o.distance),o?.units&&(b.units=o.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...h_(e.orderByFields)])],S=Ko(a,y,n??!1);try{f=S?await a.queryFeatures(b):await s.queryFeatures(b)}catch(h){console.warn("Client-side query failed, falling back to server:",h),f=await s.queryFeatures(b)}}let x=f.features.map(b=>b.attributes[d]),{attributes:w}=ea(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:x,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)}}}},y_=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:o},n)=>{let{mapView:s}=D(n,["mapView"]),a=await g_(t,e,s,r,o);return JSON.stringify(a,null,2)},__=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:Ie.optional().describe("The units for the distance buffer.")}),w_=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:Ie.optional().describe("The units for the distance buffer.")}),b_=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([__,w_]).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).")}),cp=E(y_,{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:b_});var qi=25,A_=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),x_=async(t,e,r,o)=>{let n=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(n),a=n.title??t.layerId,i;if(r){let y=await St(r,e);if("error"in y){let S={error:y.error};if(hr(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else Bo(r)&&(S.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:S}}if(!y.geometry){let S={};if(hr(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.error=`No features found matching: ${r.where}`,S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else Bo(r)&&(S.error="Failed to create point geometry",S.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:S}}i=y.geometry}else o&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...A_(t.orderByFields)])],l=Ko(s,u,o??!1),d=n.objectIdField,p=n.createQuery();p.where=gr(n.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],p.orderByFields=t.orderByFields,i&&(p.geometry=i,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let f,x;try{f=l?await s.queryFeatureCount(p):await n.queryFeatureCount(p),f>0&&f<=qi&&(x=l?await s.queryFeatures(p):await n.queryFeatures(p))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await n.queryFeatureCount(p),f>0&&f<=qi&&(x=await n.queryFeatures(p))}let{objectIds:w,attributes:b}=x?ea(n,x,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>qi&&{note:`${f} features found.`}}}};async function I_({targetLayer:t,geometryFilter:e,useCurrentExtent:r},o){let{mapView:n}=D(o,["mapView"]),s=await x_(t,n,e,r);return JSON.stringify(s,null,2)}var v_=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:Ie.optional().describe("The units for the distance buffer.")}),T_=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:Ie.optional().describe("The units for the distance buffer.")}),S_=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([v_,T_]).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).")}),dp=E(I_,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
90
+
91
+ USE THIS TOOL FOR:
92
+ - "Show / display / list features where..." \u2014 finding and listing features
93
+ - "How many X are Y?" \u2014 counting features that match a condition
94
+ - "Which features..." / "Find features..." \u2014 identifying specific features
95
+ - Spatial queries \u2014 finding features near/within/intersecting other features
96
+ - Any question where the user wants to SEE or COUNT matching features
97
+
98
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:S_});var $n=(t,e)=>e??t,Z_=M.Root({...rs(),intent:M({reducer:$n}),vectorSearchLayerResults:M({reducer:$n,default:()=>[]}),vectorSearchFieldResults:M({reducer:$n}),navigationInternalState:M({reducer:$n,default:()=>({toolCallMessage:void 0})})}),gp=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 nt(t){let e=Object.entries(gp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
99
+ Available prompts:
100
+ ${Object.keys(gp).join(`
101
+ `)}`);return await e[1]()}async function Q_(t){let{fields:e,layer:r,view:o,styleName:n,colorSchemeTags:s}=t,a;return s?a=k_({basemapTheme:await fp(o),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=E_({basemapTheme:await fp(o),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:o,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:n.includes("Size"),pieChartScheme:a}}async function Y_(t){return await C_(t)}async function X_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n};try{let l=await Q_(u),d=await Y_(l);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var ew=["mapView"];function Oe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=ew.filter(o=>!(o in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function tw({layerId:t,fields:e,colorSchemes:r,includeSize:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await X_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:o})}var rw=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)")}),ow=E(tw,{name:"chart",description:`Label: Charts
102
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
103
+ Keywords: pie, chart, all categories, breakdown, proportion
104
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
105
+ Fields: This style requires 2-8 number fields.
106
+
107
+ Label: Charts and Size
108
+ 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.
109
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
110
+ 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.
111
+ Fields: This style requires 2-8 number fields.`,schema:rw});function nw(t){let{fields:e,layer:r,view:o,theme:n,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Zi({geometryType:r.geometryType,includedTags:s,theme:n||"high-to-low"})[0]),{layer:r,view:o,startTime:a,endTime:new Date,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function sw(t){return await M_(t)}async function aw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=nw(u),d=await sw(l);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function iw({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await aw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var lw=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")}),uw=E(iw,{name:"color-age",description:`Label: Age (color)
112
+ 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.
113
+ Keywords: since, age, how old, how long
114
+ Example: Show the age of each feature based on its reported date.
115
+ Fields: This style requires at least one field with a date type.`,schema:lw});function cw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,{theme:s}=t,a=e[1],i=e[0],u;return n&&(u=Zi({geometryType:r.geometryType,includedTags:n,theme:s||"high-to-low"})[0]),{layer:r,view:o,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function dw(t){return await P_(t)}async function pw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=cw(u),d=await dw(l);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function mw({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await pw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var fw=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")}),hw=E(mw,{name:"color",description:`Label: Counts and Amounts (color)
116
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
117
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
118
+ Example: Color each feature based on the population density.
119
+ 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:fw});function gw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n,theme:s}=t,a,i,u=e[0];return n&&(i=Zi({geometryType:r.geometryType,includedTags:n,theme:s||"high-to-low"})[0]),{layer:r,view:o,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function yw(t){return await O_(t)}async function _w({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=gw(u),d=await yw(l);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function ww({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await _w({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var bw=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")}),Aw=E(ww,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
120
+ Description: Vary symbol size and color based on the values of two numeric attributes.
121
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
122
+ 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.
123
+ 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:bw});function xw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s;return n&&(s=N_({includedTags:n,numColors:Math.min(e.length,8)})[0]),{layer:r,view:o,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 Iw(t){return await R_(t)}async function vw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n}){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:o,layer:a,view:s,colorSchemeTags:n};try{let u=xw(i),l=await Iw(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function Tw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Oe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await vw({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var Sw=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")}),Cw=E(Tw,{name:"dot-density",description:`Dot Density
124
+ Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
125
+ **Use cases:**
126
+ - Population distribution visualization
127
+ - Comparing multiple categories within areas
128
+ - Showing spatial distribution patterns
129
+ **Examples:**
130
+ - Show the density of the population based on various race/ethnic groups
131
+ - Visualize distribution of different crops across regions
132
+ - Display demographic patterns within census tracts
133
+ **Fields:** Requires 2-8 number fields.
134
+ **Keywords:** density, how much, how many, total, number, amount`,schema:Sw});function kw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s,a=e[0];return n&&(s=z_({includedTags:n,basemap:o.map?.basemap||"topo"})[0]),{layer:r,view:o,field:a,heatmapScheme:s}}async function Ew(t){return await $_(t)}async function Mw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n}){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:o,layer:a,view:s,colorSchemeTags:n};try{let u=kw(i),l=await Ew(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function Pw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Oe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await Mw({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var Ow=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")}),Rw=E(Pw,{name:"heatmap",description:`Label: Heat Map
135
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
136
+ Keywords: density, heatmap, hot spots, pattern, cluster
137
+ Example: Create a heatmap
138
+ Fields: This typically requires zero or one field of type number.`,schema:Ow});function Nw(t){let{fields:e,layer:r,view:o,styleName:n,colorSchemeTags:s}=t,a;return s&&(a=j_({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:o,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:n.includes("Size"),predominanceScheme:a}}async function $w(t){return await L_(t)}async function zw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n};try{let l=Nw(u),d=await $w(l);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function Lw({layerId:t,fields:e,colorSchemes:r,includeSize:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await zw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:o})}var jw=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)")}),Dw=E(Lw,{name:"predominance",description:`Label: Predominant category
139
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
140
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
141
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
142
+ Fields: This style relies on 2-10 number fields.
143
+
144
+ Label: Predominant category and Size
145
+ 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.
146
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
147
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
148
+ Fields: This style relies on 2-10 number fields.`,schema:jw});function Fw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s,a={field:e[0]},i={field:e[1]};return n&&(s=F_({geometryType:r.geometryType,includedTags:n})[0]),{layer:r,view:o,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function Uw(t){return await D_(t)}async function qw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n}){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:o,layer:a,view:s,colorSchemeTags:n};try{let u=Fw(i),l=await Uw(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function Bw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Oe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await qw({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var Kw=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")}),Gw=E(Bw,{name:"relationship",description:`Label: Relationship
149
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
150
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
151
+ Example: Show the relationship between tree height and carbon storage
152
+ Fields: This style requires two number fields.`,schema:Kw});function Vw(t){let{fields:e,layer:r,view:o,theme:n}=t,s=e[0];return{layer:r,view:o,startTime:s,endTime:new Date,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Ww(t){return await U_(t)}async function Hw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=Vw(u),d=await Ww(l);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Jw({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await Hw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var Zw=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")}),Qw=E(Jw,{name:"size-age",description:`Label: Age (size)
153
+ 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.
154
+ Keywords: since, age, how old, how long
155
+ Example: Change the size of features so older features are larger than new features.
156
+ Fields: This style requires at least one field with a date type.`,schema:Zw});function Yw(t){let{fields:e,layer:r,view:o}=t,{theme:n}=t,s=e[1],a=e[0];return{layer:r,view:o,field:a,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Xw(t){return await q_(t)}async function eb({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=Yw(u),d=await Xw(l);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function tb({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await eb({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var rb=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")}),ob=E(tb,{name:"size",description:`Label: Counts and Amounts (size)
157
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
158
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
159
+ Example: Vary the size of each point based on the total population.
160
+ 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.
161
+
162
+ Label: Continuous Timeline (size)
163
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
164
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
165
+ Example: Vary the size of each feature based on the date a ticket was completed.
166
+ Fields: This style requires a single field with a date type.`,schema:rb});function nb(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s=e[0],a=e[1],i=e[2],u;return n&&(u=K_({geometryType:r.geometryType,includedTags:n})[0]),{layer:r,view:o,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function sb(t){return await B_(t)}async function ab({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,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:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=nb(u),d=await sb(l);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function ib({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await ab({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var lb=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")}),ub=E(ib,{name:"type",description:`Label: Types (unique symbols)
167
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
168
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
169
+ Example: Color each feature based on the region it belongs to
170
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:lb}),cb=M.Root({...Ot(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),selectedLayerId:M()}),db=M.Root({...Ot(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),queryResponse:M(),dataExplorationMessages:M({reducer:on,default:()=>[]})}),wp=[lp,up,cp,dp];var JH=new ot(wp,{handleToolErrors:!1});var pb=M.Root({...Ot(),helpInternalState:M({reducer:$n,default:()=>({toolCallMessage:void 0})})}),mb=M.Root({...Ot(),intent:M({reducer:(t,e)=>e}),arcgisKnowledgeMessages:M({reducer:on,default:()=>[]}),arcgisKnowledgeToolResult:M({reducer:(t,e)=>e,default:()=>null})});function bp(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 Ho(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function na(t){!t||Ho(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Ln(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)&&bp(r),{view:r}}async function Jo(t){let e=t?.configurable?.context;if(fb(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await hp(o)}}else{bp(e.view);let o=(e.view.map?.allLayers.find(n=>n.type==="knowledge-graph")).url;if(!o)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await hp(o)}}}}function fb(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 Bi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=oa.fromDataModel(e)}},oa=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 o of e.entityTypes)r.entityTypes.push(zn.fromEntityType(o));for(let o of e.relationshipTypes)r.relationshipTypes.push(Ki.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:hb(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(n=>n.name).join(", "),o=e.relationshipTypes.map(n=>n.name).join(", ");return`Entity Types: ${r}.
171
+ Relationship Types: ${o}.`}},zn=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=gb(e.role);for(let o of e.properties){let n={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:yb(o.role),geometryDef:o.fieldType==="esriFieldTypeGeometry"?{geometryType:o.geometryType??"esriGeometryAny",hasM:o.hasM?o.hasM:void 0,hasZ:o.hasZ?o.hasZ:void 0}:void 0};r.properties.push(n)}return r}},Ki=class extends zn{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=zn.fromEntityType(e);r.observedEndPoints=[];for(let o of e.endPoints)r.observedEndPoints.push({originEntityType:o.originEntityType,destinationEntityType:o.destinationEntityType});return r}},hb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},gb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function yb(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 sa(t){return t?.signal}async function _b(t,e){let r=await nt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
172
+
173
+ Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
174
+
175
+ Attempt Number: ${e.attemptCount}
176
+ Execution Error: ${e.executionError}
177
+ Failed Query:
178
+ ${e.failedGraphQuery}`:`${t} ${r}`}async function wb(t,e,r,o){let{graphQuery:n,explanation:s}=await Qi(t,e,r,o);return{graphQuery:n,explanation:s}}async function Qi(t,e,r,o,n){let s={message:await _b(t,n),context:new Bi(e)},a=sa(o);await J({text:"Attempting to generate a cypher query from your prompt..."},o);let i=await mp(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:pp.findCredential(Wo.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,p="",f="",x=1;for(;!u;){await new Promise(b=>setTimeout(b,1e3)),await J({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,x)}`},o),x=x%3+1;let w=await mp(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:pp.findCredential(Wo.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});p=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:p,explanation:f}}function bb(t,e){Go(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Go(t,e){if(!(!t||typeof t!="object")){if(xb(t))for(let r of t.path)Go(r,e);else if(Ab(t))e(t);else if(Array.isArray(t))for(let r of t)Go(r,e);else if(Ib(t))for(let r of Object.values(t.properties??{}))Go(r,e)}}function Ab(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function xb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Ib(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function vb(t,e){let r=[],o=[],n=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,o]];for(let[s,a]of n)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:o}}function Tb(t,e){let r={entityIds:new Array,relationshipIds:new Array},o=[],n=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!n)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:o};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=n.namedTypeDefinitions.get(l.name);if(!d){a=!1,o.push(l.name);continue}if(!d.useAllData){a=!1,o.push(l.name);for(let[p]of d.members||[])u.push(p)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:o}}var Vo=3;function Ap(t,e=100){let r={};for(let o of Object.entries(t.properties??{})){let[n,s]=o;typeof s=="string"&&s.length>e?r[n]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[n]=s}return t.properties=r,t}function Zo(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 Sb=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:o,requestOptions:n,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,d=n?.signal,p=()=>{l.abort(d?.reason)};d&&(d.aborted?l.abort(d.reason):d.addEventListener("abort",p,{once:!0}));try{let f=await V_(t,e,n);i=f.resultHeader;let x=f.resultRowsStream.getReader(),w=0,b=Date.now(),y=!1;for(;;){let{done:S,value:h}=await x.read();if(S)break;if(!y&&a&&Date.now()-b>a)return l.abort(),{type:"timeout"};for(let I of h){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=o(u,I)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Zo(f),error:f}}finally{d?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function xp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:o,targetStructure:n,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let d;for(let p=1;p<=Vo;p++){let f;try{f=await Qi(t,r.dataModel,o,l,d)}catch(y){return{type:"generation-error",errorMessage:Zo(y),error:y}}await J({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let x=await Cb(f.graphQuery,e),w=await Sb({kg:r,queryParams:new _p({openCypherQuery:f.graphQuery,bindParameters:x}),targetStructure:n,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(p>=Vo)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:p},await J({text:`Attempt ${p} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Vo} attempts.`)}var Cb=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:o}=await J_(t);if(o)return e;let n={};for(let s of r)s in e&&(n[s]=e[s]);return n},kb=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:o,searchResultLimit:n,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=n??1/0;try{for(let l of i){let d=u-a.length;if(d<=0)break;let p=(await W_(t,new H_({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:o??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:x,value:w}=await p.read();if(x){f=!0;break}for(let b of w)for(let y of b)a.push(y)}}}catch(l){let d=Zo(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},Ip="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function vp({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:o=!1}){let n=[t];if(o&&n.push(Ip),!Ho(e)&&e.map){let d=await nt("arcgis_knowledge_current_lc_context"),p=vb(e.map,r);return n.push(d),{enhancedPrompt:n.join(`
179
+
180
+ `),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=Tb(s,r);if(a)return{enhancedPrompt:n.join(`
181
+
182
+ `),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await nt("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return n.push(l),{enhancedPrompt:n.join(`
183
+
184
+ `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function Eb(t,e,r,o,n,s){let{view:a}=n,i=await xp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:o,targetStructure:new Map,targetStructureReducer:(f,x)=>{for(let w of x)bb(w,f);return f},requestOptions:{signal:sa(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,p=Array.from(d.values());return await J({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),!Ho(a)&&a?.map?(await a.map.addRecords(p),await na(a),{generatedQuery:u,explanation:l,addedIdTypePairs:p}):(await a?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(p),{generatedQuery:u,explanation:l,addedIdTypePairs:p})}var ta="addRecords",Mb=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.")}),Pb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e),o=Ln(e),{view:n}=o,s=Wo.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await vp({prompt:t,view:n,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:ta,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:p}=await Eb(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,o,e);return{toolName:ta,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
185
+
186
+ Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:p}}}catch(l){let d=Zo(l);return{toolName:ta,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},Ob=E(Pb,{name:ta,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.
187
+
188
+ example prompts:
189
+ - "add all suppliers and the parts they produce to the link chart"
190
+ - "show me the competitors of company x and add them to the link chart"
191
+ - "add the relationships between company x and company y to the link chart"
192
+ - "expand all the companies"
193
+ - "expand company x through all the buildings it owns"
194
+ - "connect company x and company y"
195
+ - "connect all buildings on the link chart"
196
+ `,schema:Mb});async function Rb(t,e){return await e.map?.applyLayout(t),await na(e),{appliedLayout:t}}var Gi="applyLayout",Nb=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")}),$b=async({layout:t},e)=>{let{view:r}=Ln(e);if(Ho(r))return{toolName:Gi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:o}=await Rb(t,r);return{toolName:Gi,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}},zb=E($b,{name:Gi,description:"Apply a diagram layout to the link chart",schema:Nb});async function Lb(t,e){return e.map?.changeNonspatialDataDisplay(t),await na(e),{appliedNonspatialDataDisplayMode:t}}var Vi="changeNonspatialVisibility",jb=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Db=async({setting:t},e)=>{let{view:r}=Ln(e);if(Ho(r))return{toolName:Vi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:o}=await Lb(t,r);return{toolName:Vi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}},Fb=E(Db,{name:Vi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:jb});async function Ub(t,e,r,o,n){let s,a="";for(let i=1;i<=Vo;i++){let{graphQuery:u,explanation:l}=await Qi(t,e.dataModel,r,n,s);try{await J({text:`Attempting to create link chart from derived query: ${u}`},n);let d=await G_.fromCypherQuery(e,new _p({openCypherQuery:u}));await J({text:"Link chart created successfully, loading..."},n),await d.load();let p=o.map;return o.map=d,await o.when(),await yp.whenOnce(()=>!o.updating),d.entityCount===0&&d.relationshipCount===0?(o.map===d&&(o.map=p),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
197
+ ${u}
198
+
199
+ Explanation: ${l}`}):(await na(o),{type:"success",graphQuery:u,explanation:l})}catch(d){let p=Zo(d);if(i>=Vo){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await J({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},n)}}return{type:"error",errorMessage:`Failed to create link chart after ${Vo} attempts. Last error: ${a}`}}var ra="createLinkChart",qb=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.")}),Bb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e),{view:o}=Ln(e);if(Ho(o))return{toolName:ra,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let n=Wo.getDefault().helperServices,s=await Ub(`${t}
200
+
201
+ ${Ip}`,r,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,o,e);if(s.type==="error")return{toolName:ra,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:ra,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
202
+ ${a}
203
+
204
+ Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},Kb=E(Bb,{name:ra,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:qb}),Wi="queryGraphData",Gb=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.")}),Vb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e),o=Wo.getDefault().helperServices,n=t,s=null,a=null;try{({view:a}=Ln(e))}catch{}a&&({enhancedPrompt:n,bindParameters:s}=await vp({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await xp({prompt:n,bindParameters:s,kg:r,graphQueryServiceUrl:`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,y)=>(b.push(y),b),requestOptions:{signal:sa(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:Wi,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:p}=i,f=p.headerKeys;for(let b of d)for(let y of b)Go(y,S=>Ap(S));let x=50,w=d.slice(0,x).map(b=>JSON.stringify(b));return{toolName:Wi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
205
+
206
+ \`\`\`cypher
207
+ ${u}
208
+ \`\`\`
209
+
210
+ Query Results:
211
+ ${w.length} result(s) found.
212
+
213
+ Column Headers: ${f.join(", ")}
214
+
215
+ ${w.length>x?`Showing top ${x} results:
216
+
217
+ `:`Results:
218
+
219
+ `}${w.join(`
220
+ `)}
221
+ `,details:{generatedQuery:u,explanation:l,resultHeader:p,queryResults:d}}},Wb=E(Vb,{name:Wi,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:Gb}),Hi="generateCypher",Hb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Jb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e),o=Wo.getDefault().helperServices;try{let{graphQuery:n,explanation:s}=await wb(t,r.dataModel,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Hi,status:"success",summary:`Generated Graph Query:
222
+ ${n}
223
+
224
+ Explanation: ${s}`,details:{generatedQuery:n,explanation:s}}}catch(n){let s=Zo(n);return{toolName:Hi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:n}}},Zb=E(Jb,{name:Hi,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:Hb}),Qb=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(p=>d.add(p)),r.set(u,d)}let o=e.entityTypes.filter(i=>r.has(i.name)),n=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
225
+ ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
226
+ `)}`,a=`Relationship Types:
227
+ ${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
228
+ `)}`;return`${s}
229
+
230
+ ${a}`};async function Yb(t,e,r){let o=await nt("arcgis_knowledge_lucene_generation_prompt"),n={inquiry:t,dataModelForSearch:Qb(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 Nn({promptText:o,inputVariables:n,schema:u,config:r})}var Ji="searchGraphData",Xb=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.")}),eA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e);await J({text:"Generating search query for the user inquiry"},e);let o=await Yb(t,r,e);await J({text:"Executing graph search with generated search query"},e);let n=await kb({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:sa(e),timeout:e?.timeout}});if(n.type!=="success")return{toolName:Ji,status:"error",errorMessage:n.errorMessage,error:"error"in n?n.error:null};for(let i of n.results)Go(i,u=>Ap(u));let s=10,a=n.results.slice(0,s);return{toolName:Ji,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
231
+ Query: ${o.query}
232
+ Type Category Filter: ${o.typeCategoryFilter}
233
+ Named Type Filters: ${o.typeFilters?o.typeFilters.join(", "):"None"}
234
+ Result Limit: ${o.resultLimit??"No limit"}
235
+
236
+ Search Results: ${n.results.length} result(s) found.
237
+
238
+ ${n.results.length>s?`Showing top ${s} results:
239
+
240
+ `:""}${a.map(i=>JSON.stringify(i)).join(`
241
+ `)}`,details:{generatedSearchQuery:o,searchResults:n.results}}},tA=E(eA,{name:Ji,description:`
242
+ 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.
243
+ Example prompts:
244
+ - "Find 'Bradley'"
245
+ - "find the person john smith"
246
+ - "find all people named smith"
247
+ - "Find all references to 'delayed parts shipment'"
248
+ - "Find all reports authored by someone with the title of 'Researcher'"
249
+ - "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".
250
+ - "Search for all john smiths and show their global ids`,schema:Xb});async function aA(t,e){let r=oA.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let n=o.url,s=`${Yi.assetsPath?.endsWith("/")?Yi.assetsPath:`${Yi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await nA(n,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new sA({url:s,width:24,height:24}),u=new rA({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}}}}async function iA({address:t},e){let{mapView:r}=D(e,["mapView"]);return await aA(t,r)}var lA=c.object({address:c.string().describe("The full address or place name to locate.")}),uA=E(iA,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:lA});async function cA(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(s=>s.name===t);if(!o)throw new Error(`Bookmark with name "${t}" not found.`);let n=o.viewpoint;if(!n)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(n),{text:`Navigated to bookmark: ${t}`}}async function dA({bookmarkName:t},e){let{mapView:r}=D(e,["mapView"]);return await Promise.resolve(cA(t,r))}var pA=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),mA=E(dA,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:pA});async function fA(t,e,r){let o=r.map?.allLayers.find(a=>a.id===t);if(!o)return{text:`Error: Layer with id ${t} not found`};let n=e?.trim()?e:"1=1",s=o.createQuery();s.where=n;try{let{extent:a,count:i}=await o.queryExtent(s);if(i===0)return{text:`No features found in ${o.title} matching: ${n}`,where:n};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${o.title}`,where:n};let u={layerId:t,layerTitle:o.title??t,where:n,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${o.title} matching: ${n}`,where:n,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:n}}}async function hA({layerId:t,where:e},r){let{mapView:o}=D(r,["mapView"]);return await fA(t,e,o)}var gA=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. Start with a fresh filter for the current request unless the task explicitly refers to prior results. Use only field name values from the selected layer, not aliases. Use field metadata only to interpret intent: prefer LIKE '%value%' for string fields, and use =, <, >, BETWEEN, IN, IS NULL, AND/OR/NOT as appropriate for number/date fields. For coded-value domain fields, use the domain code already provided in layerInfo.domain.codedValues, never the display label. Respect range-domain bounds when they are provided. Do NOT include subqueries, nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),yA=E(hA,{name:"goToFeatures",description:"Go to the features that match the given filter for the given layerId. Use coded-value domain codes from layer field metadata when building the WHERE clause.",schema:gA});async function wA(t){let e=new _A({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 bA(t,e){let{mapView:r}=D(e,["mapView"]);return await wA(r)}var AA=v.object({}),xA=E(bA,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:AA});async function IA(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 vA(t,e){let{mapView:r}=D(e,["mapView"]);return await IA(r)}var TA=c.object({}),SA=E(vA,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:TA});async function CA(t,e){await e.when();let r=e.map?.allLayers.find(n=>n.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?o=e.map.diagramNodesExtent:o=r.fullExtent,o?(await e.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function kA({layerId:t},e){let{mapView:r}=D(e,["mapView"]);return await CA(t,r)}var EA=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),MA=E(kA,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:EA});async function PA(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function OA({scale:t},e){let{mapView:r}=D(e,["mapView"]);return await PA(t,r)}var RA=c.object({scale:c.number().describe("The map scale of the view to go to.")}),NA=E(OA,{name:"goToScale",description:"Go to the specified view scale.",schema:RA});async function zA(t,e,r){let o={target:new $A({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await e.goTo(o),{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 LA({center:t,zoom:e,scale:r},o){let{mapView:n}=D(o,["mapView"]);return await zA(t,n,{zoom:e,scale:r})}var jA=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.")}),DA=E(LA,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:jA});async function FA(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function UA({zoom:t},e){let{mapView:r}=D(e,["mapView"]);return await FA(t,r)}var qA=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),BA=E(UA,{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:qA});var SJ=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
251
+ 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.
252
+
253
+ Supported actions:
254
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
255
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
256
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
257
+ - **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
258
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
259
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
260
+ - **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").
261
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
262
+
263
+ _Example: “Zoom to Texas”_
264
+ _Example: “Go to the water mains layer”_
265
+ _Example: “Zoom to to the extent of my link chart”_
266
+ _Example: “Center the map on San Francisco at scale 50000”_
267
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
268
+ _Example: “Go to the Downtown bookmark”_
269
+ _Example: “Where is Mount Rainier?”_`;var KJ=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.
270
+ _Example: “Color points by sales amount”_
271
+ _Example: “Show population density with a color gradient”_
272
+ _Example: “Create a relationship map between height and depth”_
273
+ _Example: “Vary circle sizes according to population”_`;var y3=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).
274
+ 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.
275
+ _Example: “Only show stations where Brand is Shell”_
276
+ _Example: “Make Shell stations stand out on the map”_
277
+ _Example: “Gray out all stations that aren’t Shell”_
278
+ 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.
279
+ _Example: “How many features are there?”_
280
+ _Example: “What’s the average population?”_
281
+ _Example: “Which values are in the status field?”_
282
+
283
+ 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 KA=(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 o=Array.from(r.fieldRegistry.values()),n=o.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
284
+ `);return`**${r.layerItem.title}** has ${o.length} field(s):
285
+
286
+ ${n}`},GA=({layerTitle:t},e)=>{let r=Ct(e,"layersAndFieldsRegistry");return KA(r,t)},VA=E(GA,{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.")})});var U3=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 sZ=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 Re=Nn;var oe=J,Sp=Zd;var Qo=()=>rs(),ia=async(t,e)=>await fe(t,e),la=async({modelTier:t="default",config:e}={})=>await Fi({modelTier:t,config:e});var Vp=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function _r(t){if(!Vp(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var ZA=`
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
+ `,QA=t=>t.map(e=>`"${e}"`).join(", "),YA=c.object({successMessage:c.string().default("")}),kp="portal-group-creation",Ep="approveAddMembers",XA=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 o=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!o.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let n=`The following member(s) will be added to the newly created group:
353
+
354
+ ${o.map(p=>`- **@${p}**`).join(`
355
+ `)}
356
+
357
+ Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==kp||s.id!==Ep){let p={agentId:kp,id:Ep,kind:"booleanChoice",message:n,metadata:{action:"addMembers",groupId:r,members:[...o]}};throw new Un(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await oe({text:`Adding members ${QA(o)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;_r(a);let{result:i,error:u}=await ql(a.portal,r,o);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 p=(await Re({promptText:ZA,schema:YA,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},ex=`
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
+ `,tx=`
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
+ `,Mp="portal-group-creation",Pp="approveCreateGroup",rx=c.object({successMessage:c.string().default("")}),ox=c.object({failureMessage:c.string().default("")}),nx=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 o=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:n}=e?.configurable;if(n?.agentId!==Mp||n.id!==Pp){let l={agentId:Mp,id:Pp,kind:"booleanChoice",message:o,metadata:{action:"createGroup",title:r,access:"private"}};throw new Un(l)}if(n.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await oe({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;_r(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 Re({promptText:tx,schema:ox,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 Re({promptText:ex,schema:rx,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{}},qe=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let o=r.content;if(typeof o=="string")return o;if(Array.isArray(o))return o.map(n=>typeof n=="string"?n:"text"in n&&typeof n.text=="string"?n.text:"").join(" ").trim()}return""},sx=`
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
+ `,ax=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),ix=async(t,e)=>{await oe({text:"Thinking about groups...",agentName:"group-creation"},e);let r=qe(t.agentExecutionContext.messages).trim(),o=await Re({promptText:sx,schema:ax,modelTier:"default",inputVariables:{userMessage:r}}),n=o.title.trim(),s=o.memberIdentifiers.filter(Boolean),a=o.clarifyMessage.trim(),i=o.intent==="create"&&!!n,u=o.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:n}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},lx=["customSignInSection","loginsSection","changeLoginProviderSection","multiFactorAuthSection","multifactorEnforcementSection","multifactorDesignatedAdminsSection"],ux=["customSignInCard","loginCard","multifactorAuthCard"],cx=["newItem","createLayer","developerCredentials"],dx={customSignInSection:"customSignInCard",loginsSection:"loginCard",changeLoginProviderSection:"loginCard",multiFactorAuthSection:"multifactorAuthCard",multifactorEnforcementSection:"multifactorAuthCard",multifactorDesignatedAdminsSection:"multifactorAuthCard"},px=["favorites","group","living-atlas","org"],mx=["featured","my","organization"],fx=["licenses","members","overview","reports","settings","status"],hx=c.object({destinationType:c.literal("portal-content"),hash:c.enum(px).optional(),queryParams:c.object({newItem:c.enum(cx).optional()}).optional()}),gx=c.object({destinationType:c.literal("portal-groups"),hash:c.enum(mx).optional()}),yx=c.object({destinationType:c.literal("portal-org"),hash:c.enum(fx).optional(),queryParams:c.object({tab:c.literal("security").optional(),section:c.enum(ux).optional(),subsection:c.enum(lx).optional(),period:c.string().optional(),startTime:c.string().optional(),endTime:c.string().optional()}).optional()}),_x=c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),wx=c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1)}),bx=c.object({destinationType:c.union([c.literal("portal-gallery"),c.literal("portal-map-viewer"),c.literal("portal-notebooks"),c.literal("portal-scene-viewer")])}),Ax=c.union([hx,gx,yx,_x,wx,bx]),Wp="portal-navigation",ma=async(t,e)=>{let r=e?.configurable?.context;!Vp(r)||!r.navigationTargetMap?.[t.destinationType]||await ia({type:Wp,data:{...t}},e)},xx=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await oe({text:"Preparing navigation...",agentName:"group-creation"},e),await ma({destinationType:"portal-group",groupId:r},e),{}):{}},Op=(t,e)=>e??t,Hp=M.Root({...Qo(),intentParams:M({reducer:Op,default:()=>({intent:"clarify"})}),createdGroupId:M({reducer:Op,default:()=>""})}),Ix=()=>new ce(Hp).addNode("detectGroupCreationIntent",ix).addNode("createPortalGroup",nx).addNode("addMembersToPortalGroup",XA).addNode("suggestCreatedGroupNavigation",xx).addEdge(ue,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return K}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",K),vx=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
+ `,Tx={id:"portal-group-creation",name:"Portal Group Creation",description:vx,createGraph:Ix,workspace:Hp},Jp="portalDocAssistantMemory",Sx=()=>({conversationId:""}),Cx=t=>{let e=t?.[Jp]?.value;if(!e||typeof e!="object")return Sx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},kx=t=>({[Jp]:{value:t}}),Ex={pipeline:{follow_up:{allow:!1}}};function Mx(t){return{kind:"DocAIAssistantRequest",filters:{...Ex,persona:{persona:t}}}}async function Px({portal:t,question:e,persona:r,previousConversationId:o,signal:n,skillId:s}){s??="doc_ai_assistant";let a=Mx(r),i=await Ox({portal:t,skillId:s,message:e,options:{context:a,previousConversationId:o,signal:n}});return{reply:Rx(i,s),conversationId:i[0]?.conversationId??""}}async function Ox({portal:t,skillId:e,message:r,options:o}){let n=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:HA.findCredential(t.url)?.token??""},a=await Cp(n,{method:"post",body:JSON.stringify({message:r,context:o.context,conversationId:o.previousConversationId}),headers:s,signal:o.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,p=async(f,x)=>{if(!x)return;await _l(500);let w=await Cp(n,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:d,ackSequenceNumber:f}),headers:s,signal:o.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 p(b.sequenceNumber,b.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function Rx(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 o=t[r];if(o.context?.kind==="DocAIAssistantContext"){let n=o.context.results?.[0]?.reply;if(n)return n}}return"";default:return en(e)}}var Nx=async(t,e)=>{await oe({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=qe(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let o=e?.configurable?.context;_r(o);let n=Cx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Px({portal:o.portal,question:r,previousConversationId:n.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:kx({conversationId:a||n.conversationId})}},Zp=E(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;_r(o);try{return(await Fl(o.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(n){return console.error("Error searching for portal group by title:",n),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.")})}),Qp=E(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;_r(o);let{result:n,error:s}=await Bl(o.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),n?.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 Dn(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let o=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return o?.[1]?o[1].trim():null}function $x(t){let e=Fn(t).flatMap(r=>{let o=r,n=t[r],s=[o,{description:n.description,hints:n.hints}],a=n.sections?Fn(n.sections).map(i=>{let u=n.sections?.[i];return[`${o}-${i}`,u]}):[];return[s,...a]});return Object.fromEntries(e)}function zx(t){return Object.entries(t).map(([e,{description:r,hints:o}])=>` - ${e}: ${r} (hints: ${o.join(", ")})`).join(`
413
+ `)}var Lx={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"]},"portal-content-favorites":{description:"The Favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"]},"portal-content-group":{description:"The Groups view under Content in the portal.",hints:["Content groups","Group content","My groups content"]},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content living atlas"]},"portal-content-organization":{description:"The Organization view under Content in the portal.",hints:["Organization content","Content organization","My organization content"]},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"]},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"]},"portal-groups":{description:"The groups listing page of the portal.",hints:["Groups","Browse groups"]},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"]},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"]},"portal-groups-organization":{description:"The Organization groups view under Groups in the portal.",hints:["Organization groups","Groups organization","My organization groups"]},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"]},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"]},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"]},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"]},"portal-org-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],sections:{"custom-sign-in":{description:"The Organization > Settings > Security > Custom Sign In section of the portal.",hints:["Custom Sign In","Organization > Settings > Security > Custom Sign In"]},logins:{description:"The Organization > Settings > Security > Logins section of the portal.",hints:["Logins","Organization > Settings > Security > Logins"]},"change-login-provider":{description:"The Organization > Settings > Security > Change Login Provider section of the portal.",hints:["Change Login Provider","Organization > Settings > Security > Change Login Provider"]},"multifactor-auth":{description:"The Organization > Settings > Security > Multifactor Authentication section of the portal.",hints:["MFA","Multifactor Authentication","Organization > Settings > Security > MFA"]},"multifactor-enforcement":{description:"The Organization > Settings > Security > Enforce MFA section of the portal.",hints:["Enforce MFA","MFA enforcement","Organization > Settings > Security > Enforce MFA"]},"multifactor-designated-admins":{description:"The Organization > Settings > Security > Designated Admins section of the portal.",hints:["Designated admins","MFA designated admins","Organization > Settings > Security > Designated Admins"]}}},"portal-content-new-item":{description:"The Content page with the New Item flow opened.",hints:["New item","Create new item","Content > My Content > New Item"],sections:{"feature-layer":{description:"The Content page with New Item flow set to Feature Layer as the starting step.",hints:["Feature Layer","New Feature Layer","Content > My Content > New Item > Feature Layer"]},"developer-credentials":{description:"The Content page with New Item flow set to Developer Credentials as the starting step.",hints:["Developer Credentials","New developer credentials","Content > My Content > New Item > Developer Credentials"]}}}},Yp=$x(Lx),jx=Fn(Yp),Dx=zx(Yp),Fx=`
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 destinationType:
419
+ ${Dx}
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
+ `,Rp=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...jx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),Ux=async(t,e)=>{await oe({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let o=qe(t.agentExecutionContext.messages).trim(),n=await br.fromTemplate(Fx).format({question:o,response:r}),s=(await la({modelTier:"fast"})).withStructuredOutput(Rp),a=Rp.parse(await s.invoke(n));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Dn(o,"#");u&&(a.itemId=await Qp.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Dn(o,"$")??Dn(o,"#");u&&(a.groupId=await Zp.invoke({groupTitle:u},e)??"")}let i=qx(a);return i?(await ma(i,e),{}):{}};function qx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":case"portal-gallery":case"portal-groups":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":return{destinationType:t};case"portal-org-security":return{destinationType:"portal-org",hash:"settings",queryParams:{tab:"security"}};case"portal-content-new-item":case"portal-content-new-item-feature-layer":case"portal-content-new-item-developer-credentials":return{queryParams:{newItem:Bx[t]},destinationType:"portal-content"};case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":return{destinationType:"portal-content",hash:Kx[t]};case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":return{destinationType:"portal-groups",hash:Gx[t]};case"portal-org-security-custom-sign-in":case"portal-org-security-logins":case"portal-org-security-change-login-provider":case"portal-org-security-multifactor-auth":case"portal-org-security-multifactor-enforcement":case"portal-org-security-multifactor-designated-admins":let o=Vx[t];return{destinationType:"portal-org",hash:"settings",queryParams:{tab:"security",section:dx[o],subsection:o}};case"portal-item":return e?{destinationType:t,itemId:e}:null;case"portal-group":return r?{destinationType:t,groupId:r}:null;case"none":return null;default:return en(t)}}var Bx={"portal-content-new-item":"newItem","portal-content-new-item-feature-layer":"createLayer","portal-content-new-item-developer-credentials":"developerCredentials"},Kx={"portal-content-favorites":"favorites","portal-content-group":"group","portal-content-living-atlas":"living-atlas","portal-content-organization":"org"},Gx={"portal-groups-featured":"featured","portal-groups-my":"my","portal-groups-organization":"organization"},Vx={"portal-org-security-custom-sign-in":"customSignInSection","portal-org-security-logins":"loginsSection","portal-org-security-change-login-provider":"changeLoginProviderSection","portal-org-security-multifactor-auth":"multiFactorAuthSection","portal-org-security-multifactor-enforcement":"multifactorEnforcementSection","portal-org-security-multifactor-designated-admins":"multifactorDesignatedAdminsSection"},Xp=M.Root({...Qo()}),Wx=()=>new ce(Xp).addNode("answerDocQuestion",Nx).addNode("extractNavigationIntent",Ux).addEdge(ue,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",K),Hx=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
+ `,Jx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:Hx,createGraph:Wx,workspace:Xp},Zx=()=>({latestGroupId:null,memory:{}}),fa=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:Zx()},em=`
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
+ `,Qx=`
453
+ You answer follow-up questions about ArcGIS group analytics.
454
+
455
+ ${em}
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
+ `,Yx=async(t,e)=>{await oe({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=fa(t),o=t.groupSummaryGroupId??r.latestGroupId,n=o?r.memory[o]:void 0,s=t.groupSummaryQuestion||qe(t.agentExecutionContext.messages);return n?{status:"success",outputMessage:(await Re({promptText:Qx,schema:Xx,modelTier:"default",inputVariables:{summary:n.summary,question:s,fullContext:JSON.stringify(n.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>."}},Xx=c.object({answer:c.string(),isRelevant:c.boolean()}),eI=`
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
+ `,tI=async(t,e)=>{await oe({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=qe(t.agentExecutionContext.messages),o=!!fa(t).latestGroupId,n=await br.fromTemplate(eI).format({userMessage:r,hasAnalyticsContext:String(o)}),s=(await la({modelTier:"fast"})).withStructuredOutput(Np),a=Np.parse(await s.invoke(n)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let x=Dn(r,"$");x&&(i=await Zp.invoke({groupTitle:x},e)??"")}let{intent:u,question:l}=a,d=u==="summarize"&&!i,p=u==="followUp"&&!(l??"").trim(),f=u==="clarify"||d||p;return{groupSummaryIntent:f?"clarify":u,groupSummaryGroupId:i||null,groupSummaryQuestion:l||"",status:"success",outputMessage:f?"Please clarify with a group id or title":""}},Np=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),rI=async(t,e)=>{let r=fa(t),o=t.groupSummaryGroupId??r.latestGroupId;return await oe({text:"Preparing navigation...",agentName:"group-analytics"},e),await ma(o?{destinationType:"portal-group",groupId:o}:{destinationType:"portal-groups"},e),{status:"success"}};function tm({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var oI=720*60*60*1e3;function nI(t){let e=Gl(t);return{id:t.id??"",title:t.title??"",description:t.description??"",snippet:t.snippet??"",access:t.access??null,owner:t.owner??"",tags:t.tags??[],created:t.created?.getTime(),modified:t.modified?.getTime(),isInvitationOnly:t.isInvitationOnly,sourceSignals:{capabilities:Vl(t),membershipAccess:Wl(t),isOpenData:Hl(t),isDistributedCollaborationGroup:Jl(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function sI(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 aI(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 iI(t,e){return t.filter(r=>r.modified?tm({timestamp:r.modified,now:e,windowMs:oI}):!1)}function lI(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,o)=>o[1]-r[1]||r[0].localeCompare(o[0])).slice(0,6).map(([r,o])=>({type:r,count:o}))}async function uI(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=aI(e.results),o=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:iI(r,o),topItemTypes:lI(r)}}async function cI(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 o=nI(r),n=await sI(r),s=await uI(r);return{result:{group:o,members:n,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var dI=`
507
+ You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
508
+
509
+ ${em}
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
+ `,pI=2160*60*60*1e3,mI=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 oe({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let o=e?.configurable?.context;_r(o);let{result:n,error:s}=await cI(o.portal,r);if(s||!n)return await oe({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}=n,u=Date.now(),l=a.modified,d=l?tm({timestamp:l,now:u,windowMs:pI}):!1,p=i.recentlyModifiedItems.length,f=p>0,x=d||f,w=await Re({promptText:dI,schema:fI,modelTier:"default",inputVariables:{context:JSON.stringify(n),deterministicSignals:JSON.stringify({isGroupActive:x,isGroupRecentlyModified:d,hasRecentlyAddedOrUpdatedContent:f,recentItemCount:p})}}),{followUpQuestions:b,summary:y}=w,S=fa(t),h={latestGroupId:r,memory:{...S.memory,[r]:{summary:y,followUpQuestions:b,fullContext:n}}};return b.length&&await ia({type:"suggested-prompts",data:{prompts:b}},e),{status:"success",outputMessage:y,sharedStatePatch:{portalGroupSummaryMemory:{value:h}}}},fI=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),tl=(t,e)=>e??t,rm=M.Root({...Qo(),groupSummaryIntent:M({reducer:tl,default:()=>"clarify"}),groupSummaryGroupId:M({reducer:tl,default:()=>null}),groupSummaryQuestion:M({reducer:tl,default:()=>""})}),hI=()=>new ce(rm).addNode("detectGroupSummaryIntent",tI).addNode("summarizePortalGroup",mI).addNode("answerGroupSummaryFollowUp",Yx).addNode("suggestGroupSummaryNavigation",rI).addEdge(ue,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":K).addEdge("summarizePortalGroup",K).addEdge("answerGroupSummaryFollowUp",K).addEdge("suggestGroupSummaryNavigation",K),gI=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
+ `,yI={id:"portal-group-analytics",name:"Portal Group Analytics",description:gI,createGraph:hI,workspace:rm},_I=()=>({latestItemId:null,memory:{}}),ll=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:_I()},$p=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),wI=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),bI=c.object({answer:c.string(),isRelevant:c.boolean()}),AI=`
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
+ `,xI=async(t,e)=>{await oe({text:"Answering follow-up...",agentName:"analytics"},e);let r=ll(t),o=t.analyticsItemId??r.latestItemId,n=o?r.memory[o]:void 0,s=t.analyticsQuestion||qe(t.agentExecutionContext.messages);return n?{status:"success",outputMessage:(await Re({promptText:AI,schema:bI,modelTier:"default",inputVariables:{summary:n.summary,question:s,fullContext:JSON.stringify(n.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>."}},II=`
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
+ `,vI=async(t,e)=>{await oe({text:"Analyzing intent...",agentName:"analytics"},e);let r=qe(t.agentExecutionContext.messages),o=!!ll(t).latestItemId,n=await br.fromTemplate(II).format({userMessage:r,hasSummaryContext:String(o)}),s=(await la({modelTier:"fast"})).withStructuredOutput($p),a=$p.parse(await s.invoke(n)),i=a.itemId;if(a.intent==="summarize"&&!i){let p=Dn(r,"#");p&&(i=await Qp.invoke({itemTitle:p},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>".':""}},TI=`
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
+ `,SI=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 oe({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let o=e?.configurable?.context;_r(o);let{portal:n,user:s}=o,{result:a,error:i}=await Kl(s,n,r);if(i||!a)return await oe({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 Re({promptText:TI,schema:wI,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:p}=l,f=ll(t),x={latestItemId:r,memory:{...f.memory,[r]:{summary:p,followUpQuestions:d,fullContext:u}}};return d.length&&await ia({type:"suggested-prompts",data:{prompts:d}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:x}}}},rl=(t,e)=>e??t,om=M.Root({...Qo(),analyticsIntent:M({reducer:rl,default:()=>"clarify"}),analyticsItemId:M({reducer:rl,default:()=>null}),analyticsQuestion:M({reducer:rl,default:()=>""})}),CI=()=>new ce(om).addNode("detectAnalyticsIntent",vI).addNode("summarizePortalItem",SI).addNode("answerAnalyticsFollowUp",xI).addEdge(ue,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":K).addEdge("summarizePortalItem",K).addEdge("answerAnalyticsFollowUp",K),kI=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
+ `,EI={id:"portal-item-analytics",name:"Portal Item Analytics",description:kI,createGraph:CI,workspace:om},MI={schemaVersion:"1.0",capabilities:[{id:"my-content",title:"My content",description:"Browse, discover, search, and filter ArcGIS content\u2014including maps, apps, datasets, and other items\u2014that you own or can access.",hints:["view my content","show my content","my content"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}},{id:"create-feature-layer",title:"Create feature layer",description:"Generate an editable feature layer by copying fields from templates or existing layers.",hints:["add a feature layer","make a feature layer","generate a feature layer"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}},{id:"create-folder",title:"Create folder",description:"Create a new folder in your ArcGIS content to organize your items.",hints:["create a folder","make a folder","set up a folder","new folder"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}}]},PI={schemaVersion:"1.0",capabilities:[{id:"my groups",title:"My groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that you own, belong to, or can access.",hints:["view my groups","show my groups","my groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups"}}},{id:"create-group",title:"Create group",description:"Create a new ArcGIS Portal group owned by the signed-in user.",hints:["create a group","make a group","set up a group","new group"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups"}}},{id:"featured-groups",title:"Featured groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that organization administrators choose to highlight in ArcGIS.",hints:["view featured groups","show featured groups","highlighted groups","top groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups",hash:"featured"}}},{id:"organization-groups",title:"Organization groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that are specific to your organization in ArcGIS.",hints:["view organization groups","show organization groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups",hash:"organization"}}}]},OI={schemaVersion:"1.0",capabilities:[{id:"org-config-mfa",title:"Multifactor Authentication (MFA)",description:"Configure organization-level multifactor authentication (MFA) settings. Administrators can enable MFA for ArcGIS logins, allow recovery codes for members, view MFA adoption status, enforce MFA requirements for all members, manage the MFA exemption list, and designate administrators who can troubleshoot MFA issues.",hints:["config MFA","set up MFA"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"organization",queryParams:{tab:"security"},hash:"settings"}}}]},RI={"contentRouteRegistry.ts":MI,"groupsRouteRegistry.ts":PI,"orgSettingsRouteRegistry.ts":OI};function zp(t){let e=[],r=new Set;for(let[o,n]of Object.entries(t))for(let s of n.capabilities){if(r.has(s.id))throw new Error(`${o}: duplicate capability id "${s.id}" across registries`);r.add(s.id),e.push(s)}return e}var ua;function yr(t){return t?ua=zp({customCapabilities:t}):ua||(ua=zp(RI)),ua}var NI=/^(?:take me to|navigate to|go to|show me|open)\s+(?:the\s+)?/u;function pa(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim().replace(NI,"").trim()}var $I=c.object({capabilityIds:c.array(c.string()).default([]),confidence:c.number().min(0).max(1).default(0),reason:c.string().default("")}),Lp=.8,zI=String.raw`You select Portal navigation capabilities for a user's request.
620
+
621
+ Select only capability IDs from the supplied candidates. Return an empty array when none fit.
622
+ A named surface is required: do not select a capability on another Portal surface.
623
+ Retrieval scores are hints only, not ground truth.
624
+
625
+ User request:
626
+ {userRequest}
627
+
628
+ Candidates:
629
+ {candidates}`,LI=async(t,e)=>{if(t.outputMessage||t.targets.length===0)return{};let r=qe(t.agentExecutionContext.messages).trim(),o=jI(r,t);if(o.length===1)return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"exact-match",request:r,selectedCapabilityIds:o}),{chosenCapabilityIds:o};await oe({text:"Choosing a navigation destination...",agentName:"navigation"},e);let n=JSON.stringify(t.targets.map(({capability:s,keywordScore:a,semanticScore:i})=>({id:s.id,title:s.title,description:s.description,route:s.resolutions.navigate,keywordScore:a,semanticScore:i})));try{let s=await Re({promptText:zI,schema:$I,modelTier:"fast",inputVariables:{candidates:n,userRequest:r}}),a=new Set(t.targets.map(({capability:u})=>u.id)),i=s.capabilityIds.filter(u=>a.has(u));return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{confidence:s.confidence,method:"structured-model",reason:s.reason,request:r,selectedCapabilityIds:i}),s.confidence<Lp?{chosenCapabilityIds:[],status:"failed",summary:`Navigation selection confidence ${s.confidence} is below the required ${Lp}; defer to the Portal Doc Assistant.`}:{chosenCapabilityIds:i}}catch{return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"structured-model-unavailable",request:r,selectedCapabilityIds:[]}),{chosenCapabilityIds:[]}}};function jI(t,e){let r=pa(t);return e.targets.filter(({capability:o})=>[o.title,...o.hints].some(n=>pa(n)===r)).map(({capability:o})=>o.id)}var nm=new Set(["1d","7d","14d","30d","3m","6m"]),DI=c.object({period:c.string(),startTime:c.string(),endTime:c.string()}),FI=String.raw`Extract temporal filters for an ArcGIS storage-credits query.
630
+
631
+ Return JSON only with these optional string fields:
632
+ - period
633
+ - startTime
634
+ - endTime
635
+
636
+ Rules:
637
+ - period must use <integer><unit> with unit in d,w,m (examples: 7d, 2w, 3m).
638
+ - If the request is a relative range and period can be determined, always include period.
639
+ - For "last quarter" or "previous quarter", use calendar-quarter boundaries and include period as 3m with both startTime and endTime.
640
+ - For "last quarter" or "previous quarter", endTime must be the UTC end of the previous quarter, not "now".
641
+ - If period matches one of these supported periods and the range ends today, period alone is sufficient:
642
+ 1d, 7d, 14d, 30d, 3m, 6m.
643
+ - If the request implies a range not supported as period (for example 2m or 10d), include startTime and endTime.
644
+ - For custom date ranges (for example "last december"), provide startTime and endTime.
645
+ - startTime and endTime must be epoch milliseconds as strings.
646
+ - If the end of range is "now", set endTime to {nowEpochMs}.
647
+ - If temporal intent is unclear, return empty strings for all fields.
648
+
649
+ Now UTC:
650
+ - ISO: {nowIso}
651
+ - Epoch ms: {nowEpochMs}
652
+
653
+ User request:
654
+ {userRequest}`;async function UI(t,e=new Date){let r=t.trim();if(!r)return{};try{let o=await Re({promptText:FI,schema:DI,modelTier:"fast",inputVariables:{nowEpochMs:String(e.getTime()),nowIso:e.toISOString(),userRequest:r}});return qI(o,e)}catch(o){return console.error(o),{}}}function qI(t,e=new Date){let r=jp(t.startTime),o=jp(t.endTime),n=BI(t.period);if(n){if(r!==void 0&&o!==void 0&&r<o)return{period:n,startTime:String(r),endTime:String(o)};let s=nm.has(n);if(!s||o!==void 0&&!GI(o,e.getTime())){let a=o??e.getTime(),i=KI(n,new Date(a));if(i!==void 0)return{period:n,startTime:String(i),endTime:String(a)}}return s?{period:n,...r!==void 0?{startTime:String(r)}:{},...o!==void 0?{endTime:String(o)}:{}}:{period:n}}return r!==void 0&&o!==void 0&&r<o?{startTime:String(r),endTime:String(o)}:r!==void 0?{startTime:String(r),endTime:String(e.getTime())}:{}}function BI(t){let e=t?.trim().match(/^(\d+)\s*([dwm])$/iu);if(!e)return;let r=Number.parseInt(e[1],10);if(!Number.isFinite(r)||r<=0)return;let o=e[2].toLowerCase();if(o==="w"){let n=r*7;if(nm.has(`${n}d`))return`${n}d`}return`${r}${o}`}function KI(t,e){let r=t.match(/^(\d+)([dwm])$/u);if(!r)return;let o=Number.parseInt(r[1],10);if(!Number.isFinite(o)||o<=0)return;let n=r[2];if(n==="d")return e.getTime()-o*24*60*60*1e3;if(n==="w")return e.getTime()-o*7*24*60*60*1e3;let s=new Date(e.getTime());return s.setUTCMonth(s.getUTCMonth()-o),s.getTime()}function jp(t){if(!t)return;let e=Number.parseInt(t,10);if(!(!Number.isFinite(e)||e<=0))return e}function GI(t,e){let r=new Date(t),o=new Date(e);return r.getUTCFullYear()===o.getUTCFullYear()&&r.getUTCMonth()===o.getUTCMonth()&&r.getUTCDate()===o.getUTCDate()}async function VI(t,e,r){let o=yr().find(s=>s.id===t);if(!o)return;let n=await HI(WI(o),r);return n&&ZI(n,e)?{capability:o,target:n}:void 0}function WI(t){let{hash:e,queryParams:r,routeKey:o}=t.resolutions.navigate;switch(o){case"content":switch(t.id){case"my-content":return{destinationType:"portal-content"};case"create-feature-layer":return{destinationType:"portal-content"};case"create-folder":return{destinationType:"portal-content"};default:return{destinationType:"portal-content"}}case"groups":if(e==="featured")return{destinationType:"portal-groups",hash:"featured"};if(e==="organization")return{destinationType:"portal-groups",hash:"organization"};switch(t.id){case"my groups":return{destinationType:"portal-groups",hash:"my"};case"create-group":return{destinationType:"portal-groups"};default:return{destinationType:"portal-groups"}}case"organization":return{destinationType:"portal-org",hash:e,queryParams:r,buttonLabel:t.buttonLabel};default:return}}async function HI(t,e){if(!t||!e||!JI(t))return t;let r=await UI(e);if(!r.period&&!r.startTime&&!r.endTime)return t;let o={...t.queryParams??{},...r.period?{period:r.period}:{},...r.startTime?{startTime:r.startTime}:{},...r.endTime?{endTime:r.endTime}:{}};return{...t,queryParams:o}}function JI(t){return t.destinationType==="portal-org"&&t.hash==="status"}function ZI(t,e){return!e||!!e[t.destinationType]}var QI=async(t,e)=>{if(t.outputMessage||t.status==="failed")return{};let r=t.targets.find(({capability:s})=>t.chosenCapabilityIds.includes(s.id))??t.targets[0];if(!r)return{outputMessage:"I couldn't find a matching Portal page. Try asking to open your content, groups, or organization settings.",sharedStatePatch:{navLastAnsweredRequest:{value:Dp(t)}},status:"success",summary:"Navigation could not find a matching capability; route another agent if appropriate."};let o=Dp(t),n=await VI(r.capability.id,void 0,o);return n?(await oe({text:"Preparing navigation...",agentName:"navigation"},e),await ma(n.target,e),{outputMessage:t.chosenCapabilityIds.length?r.capability.description:`The closest place to start is ${r.capability.title}. Click the button below to open it.`,status:"success",summary:`Navigation suggested ${r.capability.id}${t.retrievalDegraded?" using keyword-only retrieval":""}.`,sharedStatePatch:{navLastAnsweredRequest:{value:o}}}):(console.warn(`Navigation capability ${r.capability.id} was not found in the resolver.`),{outputMessage:"I found a possible destination, but couldn't resolve a valid Portal navigation target. Try asking to open your content, groups, or organization settings.",status:"success",summary:`Navigation resolver could not map ${r.capability.id}.`,sharedStatePatch:{navLastAnsweredRequest:{value:o}}})};function Dp(t){return qe(t.agentExecutionContext.messages)||t.agentExecutionContext.userRequest}async function sm(t){return t.length===0?[]:(await JA.getDefault().load(),await Sp(t))}var YI=Object.freeze(Object.defineProperty({__proto__:null,generateEmbeddings:sm},Symbol.toStringTag,{value:"Module"}));function XI(t){let e=[],r=`${t.title}. ${t.description}`;r.trim().length>0&&e.push({field:"summary",text:r});let o=t.hints;if(Array.isArray(o))for(let n of o)typeof n=="string"&&n.trim().length>0&&e.push({field:"hint",text:n});return e}var ca,ul,da=0;async function ev(t={}){let e=da;return ca??=rv(t.embed??ov).then(r=>(e===da&&(ul=r),r)).catch(r=>{throw e===da&&(ca=void 0),r}),await ca}function tv(){return ul}function Fp(){da+=1,ul=void 0,ca=void 0}async function rv(t){let e=nv(),r=await t(e.map(o=>o.text));if(r.length!==e.length)throw new Error(`Expected ${e.length} vectors, got ${r.length}`);return e.map((o,n)=>({...o,vector:r[n]}))}async function ov(t){let{generateEmbeddings:e}=await Promise.resolve().then(()=>YI);return await e(t)}function nv(){return yr().flatMap(t=>XI(t).map(({field:e,text:r})=>({capabilityId:t.id,field:e,text:r})))}var Up=1.2,qp=.75,sv=60,av=.65,ol={description:1,hint:2,title:3},al;function iv(){al=void 0}async function lv(t,e={}){let r=pv(am(t)),o=[],n=!1,s;if(t.trim()){let a=e.loadEmbeddings,i=tv();if(!a&&!i)n=!0,s="Capability embeddings are still loading.";else try{if(a){let[u,l]=await Promise.all([(e.embedQuery??Kp)(t),a()]);o=Bp(u,l)}else if(i){let u=await(e.embedQuery??Kp)(t);o=Bp(u,i)}}catch{n=!0,s="Semantic search is unavailable."}}return{degraded:n,...s?{degradedReason:s}:{},matches:fv(r,o,e.topN??5)}}function uv(){return al??=cv(yr()),al}function cv(t){let e=new Map,r=t.map(o=>{let n=new Map;nl(n,o.title,ol.title),nl(n,o.description,ol.description);for(let s of o.hints)nl(n,s,ol.hint);for(let s of n.keys())e.set(s,(e.get(s)??0)+1);return{capability:o,length:dv(n),termFrequencies:n}});return{averageDocumentLength:r.length?r.reduce((o,n)=>o+n.length,0)/r.length:0,documentFrequency:e,documents:r}}function nl(t,e,r){for(let o of am(e))t.set(o,(t.get(o)??0)+r)}function dv(t){return[...t.values()].reduce((e,r)=>e+r,0)}function am(t){return t.toLowerCase().split(/[^a-z0-9]+/u).filter(Boolean)}function pv(t){let e=uv(),r=new Set(t),o=e.documents.length;return e.documents.map(({capability:n,length:s,termFrequencies:a})=>{let i=0;for(let u of r){let l=a.get(u),d=e.documentFrequency.get(u);if(!l||!d)continue;let p=Math.log(1+(o-d+.5)/(d+.5)),f=Up*(1-qp+qp*(s/e.averageDocumentLength));i+=p*(l*(Up+1)/(l+f))}return{capability:n,score:i}}).filter(({score:n})=>n>0).sort(im)}function Bp(t,e){let r=new Map;for(let n of e){let s=mv(t,n.vector);if(s===void 0)continue;let a=r.get(n.capabilityId);(a===void 0||s>a)&&r.set(n.capabilityId,s)}let o=new Map(yr().map(n=>[n.id,n]));return[...r.entries()].flatMap(([n,s])=>{let a=o.get(n);return a&&s>=av?[{capability:a,score:s}]:[]}).sort(im)}function mv(t,e){if(t.length===0||t.length!==e.length)return;let r=0,o=0,n=0;for(let a=0;a<t.length;a+=1)r+=t[a]*e[a],o+=t[a]**2,n+=e[a]**2;let s=Math.sqrt(o)*Math.sqrt(n);return s===0?void 0:r/s}async function Kp(t){let[e]=await sm([t]);if(!e)throw new Error("Expected one query embedding.");return e}function fv(t,e,r){let o=new Map;return Gp(o,t,"keyword"),Gp(o,e,"semantic"),[...o.values()].sort((n,s)=>s.score!==n.score?s.score-n.score:(s.semanticScore??0)!==(n.semanticScore??0)?(s.semanticScore??0)-(n.semanticScore??0):(s.keywordScore??0)!==(n.keywordScore??0)?(s.keywordScore??0)-(n.keywordScore??0):n.capability.id.localeCompare(s.capability.id)).slice(0,Math.max(0,r))}function Gp(t,e,r){for(let[o,{capability:n,score:s}]of e.entries()){let a=o+1,i=t.get(n.id)??{capability:n,score:0};i.score+=1/(sv+a),r==="keyword"?(i.keywordRank=a,i.keywordScore=s):(i.semanticRank=a,i.semanticScore=s),t.set(n.id,i)}}function im(t,e){return e.score-t.score||t.capability.id.localeCompare(e.capability.id)}var hv=async(t,e)=>{await oe({text:"Finding a place to navigate...",agentName:"navigation"},e);let r=qe(t.agentExecutionContext.messages).trim();try{let o=await lv(r,{topN:5});return console.table(o.matches.map(({capability:n,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u,score:l})=>({capability:n.title,fusedScore:l,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u}))),o.degradedReason&&console.info("[arcgis-portal-ai-assistant] navigation semantic search:",o.degradedReason),{chosenCapabilityIds:[],retrievalDegraded:o.degradedReason??"",targets:gv(r,o.matches)}}catch{return{chosenCapabilityIds:[],outputMessage:"I couldn't look up a Portal page right now. Please try again.",status:"failed",targets:[]}}};function gv(t,e){let r=pa(t),o=e.filter(({capability:s})=>[s.title,...s.hints].some(a=>pa(a)===r));if(o.length!==1)return e;let[n]=o;return[n,...e.filter(s=>s!==n)]}var sl=(t,e)=>e??t,lm=M.Root({...Qo(),chosenCapabilityIds:M({reducer:sl,default:()=>[]}),retrievalDegraded:M({reducer:sl,default:()=>""}),targets:M({reducer:sl,default:()=>[]})}),yv=()=>new ce(lm).addNode("retrieveNavigationTargets",hv).addNode("chooseNavigationTargets",LI).addNode("respondWithNavigation",QI).addEdge(ue,"retrieveNavigationTargets").addEdge("retrieveNavigationTargets","chooseNavigationTargets").addEdge("chooseNavigationTargets","respondWithNavigation").addEdge("respondWithNavigation",K);function _v(){let t=yr().map(({hints:e,title:r})=>e[0]??r).join(", ");return String.raw`- **portal-navigation** - Portal page navigation assistant:
655
+ - routes requests to open, show, or navigate to a Portal page, including creation-flow pages
656
+ - falls back to the closest Portal page where a workflow starts when another agent cannot perform the action
657
+ - handles short navigation follow-ups after asking the user to open a page
658
+ - capability examples: ${t}
659
+ - do not use for general "how do I" questions unless the user explicitly asks to reach a page
660
+ `}var wv={id:"navigation",name:"Portal Navigation",get description(){return _v()},createGraph:yv,workspace:lm},bv=pl`: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 Av(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":return e[r]?.(t.hash,t.queryParams);case"portal-groups":return e[r]?.(t.hash);case"portal-org":return e[r]?.(t.hash,t.queryParams);case"portal-gallery":return e[r];case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId);default:return en(r)}}function xv(t){let e=Ax.safeParse(t);return e.success?e.data:void 0}function Iv(t,e){let r=e.navigation;switch(t.destinationType){case"portal-content":switch(t.hash){case"favorites":return r.openContentFavorites;case"group":return r.openContentGroup;case"living-atlas":return r.openContentLivingAtlas;case"org":return r.openContentOrganization;default:return r.openContent}case"portal-gallery":return r.openGallery;case"portal-groups":switch(t.hash){case"featured":return r.openGroupsFeatured;case"my":return r.openGroupsMy;case"organization":return r.openGroupsOrganization;default:return r.openGroups}case"portal-map-viewer":return r.openMapViewer;case"portal-notebooks":return r.openNotebooks;case"portal-scene-viewer":return r.openSceneViewer;case"portal-org":return r.openOrgSettings;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return en(t)}}var il=class extends gl{constructor(){super(),this.t9n=wl({blocking:!0}),this.assistantEl=Yo(),this.formEl=Yo(),this.voiceInputEl=Yo(),this.inputEl=Yo(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,o=r.data?.block;if(!o)return;let n=this.getNavigationAction(o);n&&this.upsertNavigationSlotElement(r.slotName,n)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=fl(),yr()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,disabledAgents:0,defaultClosed:5,navigationCapabilities:0}}static{this.styles=bv}async load(){await this.refreshCapabilityEmbeddings()}willUpdate(e){!this.hasUpdated||!e.has("navigationCapabilities")||this.refreshCapabilityEmbeddings()}async clearEmbeddingsCache(){Fp()}isAgentEnabled(e){return!this.disabledAgents?.[e]}async refreshCapabilityEmbeddings(){try{yr(this.navigationCapabilities),iv(),Fp(),await ev()}catch(e){console.warn("[arcgis-portal-ai-assistant] embeddings warm-up failed:",e)}}getNavigationAction(e){if(e?.type!==Wp)return;let r=e.data,o=xv(r);if(!o)return;let n=Av(r,this.navigationTargetMap);if(n)return{href:n,targetDetail:r,label:r?.buttonLabel||Iv(o,this.t9n)}}upsertNavigationSlotElement(e,r){let o=this.assistantEl.value;if(!o)return;let n=`navigation:${e}`,s=this.navigationSlotElements.get(n);s||(s=document.createElement("div"),s.slot=e,this.navigationSlotElements.set(n,s),o.append(s)),ml(ve`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${a=>{a.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?ve`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,s)}render(){let{t9n:e,inputText:r,portal:o,user:n,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return ve`<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()})}} ${Xo(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="")}} ${Xo(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${o} .user=${n} 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??""}} ${Xo(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}} ${Xo(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&ve`<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>${this.isAgentEnabled("itemAnalytics")&&ve`<arcgis-assistant-agent .agent=${EI} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupCreation")&&ve`<arcgis-assistant-agent .agent=${Tx} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("docAssistant")&&ve`<arcgis-assistant-agent .agent=${Jx} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupAnalytics")&&ve`<arcgis-assistant-agent .agent=${yI} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("navigation")&&ve`<arcgis-assistant-agent .agent=${wv} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.interrupt&&ve`<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>`}};yl("arcgis-portal-ai-assistant",il);return il},"identity/IdentityManager","portal/Portal","portal/Portal","request","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","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/Point","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","layers/support/FeatureFilter","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","config","Graphic","portal/Portal","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","request","portal/Portal",a,b,c)