@esri/solutions-components 5.1.0-next.129 → 5.1.0-next.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/cdn/CSS4AELA.js +2 -0
  2. package/dist/cdn/EVGXFAJU.js +2 -0
  3. package/dist/cdn/J5K2SIY6.js +4 -0
  4. package/dist/cdn/{HZOBBQYW.js → JSQHZGE3.js} +91 -91
  5. package/dist/cdn/RMCQZMLA.js +2 -0
  6. package/dist/cdn/U4A4FLFF.js +2 -0
  7. package/dist/cdn/{N2UNOXJ6.js → W5L4RUZC.js} +1 -1
  8. package/dist/cdn/{DYCGZ67C.js → WK7CB4GW.js} +1 -1
  9. package/dist/cdn/{6IMLSV3Z.js → YZVDT3ZT.js} +1 -1
  10. package/dist/cdn/Z4BCFJUQ.js +88 -0
  11. package/dist/cdn/ZTO4S3BZ.js +2 -0
  12. package/dist/cdn/assets/arcgis-solutions-assistant/t9n/messages.en.json +1 -1
  13. package/dist/cdn/assets/arcgis-solutions-assistant/t9n/messages.json +1 -1
  14. package/dist/cdn/assets/create-feature/t9n/messages.en.json +1 -1
  15. package/dist/cdn/assets/create-feature/t9n/messages.json +1 -1
  16. package/dist/cdn/assets/crowdsource-reporter/t9n/messages.en.json +1 -1
  17. package/dist/cdn/assets/crowdsource-reporter/t9n/messages.json +1 -1
  18. package/dist/cdn/index.js +1 -1
  19. package/dist/chunks/updateDesign.js +1 -1
  20. package/dist/components/arcgis-solutions-assistant/customElement.d.ts +6 -0
  21. package/dist/components/arcgis-solutions-assistant/customElement.js +340 -340
  22. package/dist/components/create-feature/customElement.d.ts +35 -3
  23. package/dist/components/create-feature/customElement.js +176 -76
  24. package/dist/components/create-feature/index.js +2 -1
  25. package/dist/components/create-related-feature/customElement.d.ts +4 -4
  26. package/dist/components/create-related-feature/customElement.js +60 -80
  27. package/dist/components/create-related-feature/index.js +1 -0
  28. package/dist/components/crowdsource-reporter/customElement.d.ts +16 -2
  29. package/dist/components/crowdsource-reporter/customElement.js +75 -49
  30. package/dist/components/feature-list/customElement.d.ts +1 -1
  31. package/dist/components/feature-list/customElement.js +2 -2
  32. package/dist/components/layer-list/customElement.d.ts +1 -1
  33. package/dist/components/solution-builder-assistant/customElement.js +97 -98
  34. package/dist/docs/api.json +1 -1
  35. package/dist/docs/docs.json +1 -1
  36. package/dist/docs/vscode.html-custom-data.json +1 -1
  37. package/dist/docs/web-types.json +1 -1
  38. package/dist/loader.js +2 -2
  39. package/dist/solutions-components_commit.txt +7 -7
  40. package/dist/types/lumina.d.ts +2 -2
  41. package/dist/types/preact.d.ts +2 -2
  42. package/dist/types/react.d.ts +2 -2
  43. package/dist/types/stencil.d.ts +2 -2
  44. package/dist/utils/interfaces.d.ts +17 -0
  45. package/package.json +1 -1
  46. package/dist/cdn/53MDMQSB.js +0 -88
  47. package/dist/cdn/H4YPSJ5G.js +0 -2
  48. package/dist/cdn/KLCBAO3U.js +0 -4
  49. package/dist/cdn/NSKVOAA7.js +0 -2
  50. package/dist/cdn/ODB4CELR.js +0 -2
  51. package/dist/cdn/QYWT7Y5Q.js +0 -2
  52. package/dist/cdn/UYOTCDME.js +0 -2
@@ -0,0 +1,88 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import{c as Qt,d as Tn,e as Fo,f as Ka,g as Bo}from"./54AE7WD2.js";import{a as Uo}from"./WPGT2HLS.js";import c from"./XC3IZAIH.js";import a from"./EXC566PM.js";import{b as ba,c as Ia}from"./2B4SGB3I.js";import{b as Po}from"./I2NTSKBD.js";import"./3UKDJZ2D.js";import{a as Aa}from"./MGEDATQ7.js";import"./RMEDO4JC.js";import"./ISFTCFSJ.js";import{$ as Na,C as Ca,D as me,E as Pa,F as as,G as So,H as Eo,I as ls,Ia as z,J as W,K as Mo,L as D,M as Ro,N as qe,O as us,P as Oa,Q as ka,R as $o,S as cs,T as Sa,U as Ea,V as xn,W as ps,X as Ma,Y as Ra,Z as $a,_ as ds,a as Gt,aa as mt,b as Se,ba as No,ca as ms,da as M,ea as y,fa as ft,ga as fs,ha as La,ia as hs,ja as Da,ka as ja,la as gs,lb as ys,ma as Lo,mb as ws,na as Yt,nb as Xt,oa as Do,p as ko,pa as za,qa as Ua,sa as _s,ta as Fa,ua as Ba,va as vn,wa as b,xa as jo,ya as zo}from"./JSQHZGE3.js";import"./TEHBW75B.js";import"./IHG7KTNC.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./N22MFQSQ.js";import"./N7BXCDA3.js";import"./ZX3UHK6P.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./LP2JYX4X.js";import"./GF4QELNV.js";import{l as xa,v as Oo}from"./AYSQIO6L.js";import"./YQHYMLC7.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as wa}from"./2I5LGZNX.js";import{E as ga,F as _a,G as ya,K as Co,h as pa,i as dt,k as da,l as vo,q as To,v as ma,w as fa,x as ha}from"./FFF5HUPM.js";import{c as ca}from"./QPIMTXPL.js";export default $arcgis.t(([$c,Ac,Zi,Sf,Vj,Yj,rh,nh,{q:va},{r:Ta}])=>{var Cn=class extends ha{constructor(e){if(super(e),this.it=vo,e.type!==ma.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===vo||e==null)return this._t=void 0,this.it=e;if(e===da)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;let r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};Cn.directiveName="unsafeHTML",Cn.resultType=1;var Wa=fa(Cn);async function qa(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
+
4
+ If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
+
6
+ Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
7
+ |`,`
8
+ \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
9
+ `].join(" "));let n=await Ea(r),s=n?.getParentRunId();n!==void 0&&s!==void 0&&await n.handleCustomEvent?.(t,e,s)}var T=b;var rp={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},Pg=Object.keys(rp);var Ko=Symbol.for("langgraph-zod");Ko in globalThis||(globalThis[Ko]=new WeakSet);function Za(t){let e=globalThis[Ko];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return ws(r,{jsonSchemaExtra:n})},reducer(n,s){return ws(r,{default:ms(r),reducer:{schema:s,fn:n}})}}}}),e.add(t))}try{Za(y.ZodType.prototype),Za(b.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 Va=class extends Ra{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=ms(t);n!=null&&(r.default=n)}return super.add(t,...e)}},op=new Va(ys);var Cp=y.function().args(y.custom(),y.custom(),y.custom()).returns(y.union([y.string(),y.promise(y.string())])),Pp=["approve","edit","reject"],Op=y.enum(Pp),kp=y.object({allowedDecisions:y.array(Op),description:y.union([y.string(),Cp]).optional(),argsSchema:y.record(y.any()).optional()}),Cw=y.object({interruptOn:y.record(y.union([y.boolean(),kp])).optional(),descriptionPrefix:y.string().default("Tool execution requires approval")});var Mp=`<role>
10
+ Context Extraction Assistant
11
+ </role>
12
+
13
+ <primary_objective>
14
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
15
+ </primary_objective>
16
+
17
+ <objective_information>
18
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
19
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
20
+ </objective_information>
21
+
22
+ <instructions>
23
+ The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
24
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
25
+ </instructions>
26
+
27
+ The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
28
+
29
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
30
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
31
+
32
+ <messages>
33
+ Messages to summarize:
34
+ {messages}
35
+ </messages>`;var Rp=y.function().args(y.array(y.custom())).returns(y.union([y.number(),y.promise(y.number())])),Vo=y.object({fraction:y.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:y.number().positive("Tokens must be greater than 0").optional(),messages:y.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"}),rl=y.object({fraction:y.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:y.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:y.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"}),Ww=y.object({model:y.custom(),trigger:y.union([Vo,y.array(Vo)]).optional(),keep:rl.optional(),tokenCounter:Rp.optional(),summaryPrompt:y.string().default(Mp),trimTokensToSummarize:y.number().optional(),summaryPrefix:y.string().optional(),maxTokensBeforeSummary:y.number().optional(),messagesToKeep:y.number().optional()});var tA=y.object({model:y.string().or(y.instanceof(Da)).optional(),systemPrompt:y.string().optional(),maxTools:y.number().optional(),alwaysInclude:y.array(y.string()).optional()});var lA=y.object({applyToInput:y.boolean().optional(),applyToOutput:y.boolean().optional(),applyToToolResults:y.boolean().optional()});var mA=y.object({rules:y.record(y.string(),y.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var $p=["continue","error","end"],Np="continue";var Lp=y.enum($p).default(Np);y.object({toolName:y.string().optional(),threadLimit:y.number().optional(),runLimit:y.number().optional(),exitBehavior:Lp});var vA=y.object({threadToolCallCount:y.record(y.string(),y.number()).default({}),runToolCallCount:y.record(y.string(),y.number()).default({})});var Dp=y.enum(["pending","in_progress","completed"]).describe("Status of the todo"),jp=y.object({content:y.string().describe("Content of the todo item"),status:Dp}),MA=y.object({todos:y.array(jp).default([])});var DA=y.object({threadLimit:y.number().optional(),runLimit:y.number().optional(),exitBehavior:y.enum(["error","end"]).optional()}),jA=y.object({threadModelCallCount:y.number().default(0),runModelCallCount:y.number().default(0)});var As=y.object({maxRetries:y.number().min(0).default(2),retryOn:y.union([y.function().args(y.instanceof(Error)).returns(y.boolean()),y.array(y.custom())]).default(()=>()=>!0),backoffFactor:y.number().min(0).default(2),initialDelayMs:y.number().min(0).default(1e3),maxDelayMs:y.number().min(0).default(6e4),jitter:y.boolean().default(!0)});var XA=y.object({onFailure:y.union([y.literal("error"),y.literal("continue"),y.function().args(y.instanceof(Error)).returns(y.string())]).default("continue")}).merge(As);var ib=y.object({tools:y.array(y.union([y.custom(),y.custom(),y.string()])).optional(),onFailure:y.union([y.literal("error"),y.literal("continue"),y.literal("raise"),y.literal("return_message"),y.function().args(y.instanceof(Error)).returns(y.string())]).default("continue")}).merge(As);var yb=y.object({enableCaching:y.boolean().optional(),ttl:y.enum(["5m","1h"]).optional(),minMessagesToCache:y.number().optional(),unsupportedModelBehavior:y.enum(["ignore","warn","raise"]).optional()});function On(t,e){return t.lc_error_code=e,t.message=`${t.message}
36
+
37
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
38
+ `,t}function C(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function f(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Go=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Go=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function kn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Sn=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 v=class extends Error{},F=class t extends v{constructor(e,r,n,s){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,r,n,s){if(!e||!s)return new Je({message:n,cause:Sn(r)});let o=r?.error;return e===400?new rr(e,o,n,s):e===401?new nr(e,o,n,s):e===403?new sr(e,o,n,s):e===404?new or(e,o,n,s):e===409?new ir(e,o,n,s):e===422?new ar(e,o,n,s):e===429?new lr(e,o,n,s):e>=500?new ur(e,o,n,s):new t(e,o,n,s)}},B=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Je=class extends F{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},be=class extends Je{constructor({message:e}={}){super({message:e??"Request timed out."})}},rr=class extends F{},nr=class extends F{},sr=class extends F{},or=class extends F{},ir=class extends F{},ar=class extends F{},lr=class extends F{},ur=class extends F{},cr=class extends v{constructor(){super("Could not parse response content as the length limit was reached")}},pr=class extends v{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ie=class extends Error{constructor(e){super(e)}},ht=class extends F{constructor(e,r,n){let s="OAuth2 authentication error",o;if(r&&typeof r=="object"){let i=r;o=i.error;let a=i.error_description;a&&typeof a=="string"?s=a:o&&(s=o)}super(e,r,s,n),this.error_code=o}},En=class extends v{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Zp=/^[a-z][a-z0-9+.-]*:/i,nl=t=>Zp.test(t),oe=t=>(oe=Array.isArray,oe(t)),Yo=oe;function bs(t){return typeof t!="object"?{}:t??{}}function Xo(t){if(!t)return!0;for(let e in t)return!1;return!0}function sl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Mn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var ol=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new v(`${t} must be an integer`);if(e<0)throw new v(`${t} must be a positive integer`);return e};var il=t=>{try{return JSON.parse(t)}catch{return}};var xe=t=>new Promise(e=>setTimeout(e,t));var Ze="6.39.0";var cl=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Vp(){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 Gp=()=>{let t=Vp();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"X-Stainless-OS":ll(Deno.build.os),"X-Stainless-Arch":al(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":Ze,"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":Ze,"X-Stainless-OS":ll(globalThis.process.platform??"unknown"),"X-Stainless-Arch":al(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Yp();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"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":Ze,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Yp(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var al=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",ll=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"),ul,pl=()=>ul??(ul=Gp());function Is(){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 Qo(...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 xs(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Qo({start(){},async pull(r){let{done:n,value:s}=await e.next();n?r.close():r.enqueue(s)},async cancel(){await e.return?.()}})}function ei(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 ti(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 ml=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var ri="RFC3986",ni=t=>String(t),si={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ni},fl="RFC1738";var vs=(t,e)=>(vs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),vs(t,e)),ve=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var oi=1024,hl=(t,e,r,n,s)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=oi){let u=o.length>=oi?o.slice(a,a+oi):o,l=[];for(let p=0;p<u.length;++p){let m=u.charCodeAt(p);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||s===fl&&(m===40||m===41)){l[l.length]=u.charAt(p);continue}if(m<128){l[l.length]=ve[m];continue}if(m<2048){l[l.length]=ve[192|m>>6]+ve[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=ve[224|m>>12]+ve[128|m>>6&63]+ve[128|m&63];continue}p+=1,m=65536+((m&1023)<<10|u.charCodeAt(p)&1023),l[l.length]=ve[240|m>>18]+ve[128|m>>12&63]+ve[128|m>>6&63]+ve[128|m&63]}i+=l.join("")}return i};function gl(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ii(t,e){if(oe(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var yl={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},wl=function(t,e){Array.prototype.push.apply(t,oe(e)?e:[e])},_l,V={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:hl,encodeValuesOnly:!1,format:ri,formatter:ni,indices:!1,serializeDate(t){return(_l??(_l=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Qp(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var ai={};function Al(t,e,r,n,s,o,i,a,u,l,p,m,_,h,A,I,E,g){let w=t,k=g,L=0,R=!1;for(;(k=k.get(ai))!==void 0&&!R;){let H=k.get(t);if(L+=1,typeof H<"u"){if(H===L)throw new RangeError("Cyclic object value");R=!0}typeof k.get(ai)>"u"&&(L=0)}if(typeof l=="function"?w=l(e,w):w instanceof Date?w=_?.(w):r==="comma"&&oe(w)&&(w=ii(w,function(H){return H instanceof Date?_?.(H):H})),w===null){if(o)return u&&!I?u(e,V.encoder,E,"key",h):e;w=""}if(Qp(w)||gl(w)){if(u){let H=I?e:u(e,V.encoder,E,"key",h);return[A?.(H)+"="+A?.(u(w,V.encoder,E,"value",h))]}return[A?.(e)+"="+A?.(String(w))]}let j=[];if(typeof w>"u")return j;let Q;if(r==="comma"&&oe(w))I&&u&&(w=ii(w,u)),Q=[{value:w.length>0?w.join(",")||null:void 0}];else if(oe(l))Q=l;else{let H=Object.keys(w);Q=p?H.sort(p):H}let U=a?String(e).replace(/\./g,"%2E"):String(e),Y=n&&oe(w)&&w.length===1?U+"[]":U;if(s&&oe(w)&&w.length===0)return Y+"[]";for(let H=0;H<Q.length;++H){let Z=Q[H],la=typeof Z=="object"&&typeof Z.value<"u"?Z.value:w[Z];if(i&&la===null)continue;let xo=m&&a?Z.replace(/\./g,"%2E"):Z,Qc=oe(w)?typeof r=="function"?r(Y,xo):Y:Y+(m?"."+xo:"["+xo+"]");g.set(t,L);let ua=new WeakMap;ua.set(ai,g),wl(j,Al(la,Qc,r,n,s,o,i,a,r==="comma"&&I&&oe(w)?null:u,l,p,m,_,h,A,I,E,ua))}return j}function ed(t=V){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||V.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=ri;if(typeof t.format<"u"){if(!vs(si,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=si[r],s=V.filter;(typeof t.filter=="function"||oe(t.filter))&&(s=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in yl?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=V.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:V.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:V.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:V.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:V.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?V.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:V.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:V.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:V.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:V.encodeValuesOnly,filter:s,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:V.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:V.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:V.strictNullHandling}}function bl(t,e={}){let r=t,n=ed(e),s,o;typeof n.filter=="function"?(o=n.filter,r=o("",r)):oe(n.filter)&&(o=n.filter,s=o);let i=[];if(typeof r!="object"||r===null)return"";let a=yl[n.arrayFormat],u=a==="comma"&&n.commaRoundTrip;s||(s=Object.keys(r)),n.sort&&s.sort(n.sort);let l=new WeakMap;for(let _=0;_<s.length;++_){let h=s[_];n.skipNulls&&r[h]===null||wl(i,Al(r[h],h,a,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let p=i.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),p.length>0?m+p:""}function Il(t){return bl(t,{arrayFormat:"brackets"})}function Tl(t){let e=0;for(let s of t)e+=s.length;let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var xl;function dr(t){let e;return(xl??(e=new globalThis.TextEncoder,xl=e.encode.bind(e)))(t)}var vl;function li(t){let e;return(vl??(e=new globalThis.TextDecoder,vl=e.decode.bind(e)))(t)}var ue,ce,gt=class{constructor(){ue.set(this,void 0),ce.set(this,void 0),C(this,ue,new Uint8Array,"f"),C(this,ce,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?dr(e):e;C(this,ue,Tl([f(this,ue,"f"),r]),"f");let n=[],s;for(;(s=rd(f(this,ue,"f"),f(this,ce,"f")))!=null;){if(s.carriage&&f(this,ce,"f")==null){C(this,ce,s.index,"f");continue}if(f(this,ce,"f")!=null&&(s.index!==f(this,ce,"f")+1||s.carriage)){n.push(li(f(this,ue,"f").subarray(0,f(this,ce,"f")-1))),C(this,ue,f(this,ue,"f").subarray(f(this,ce,"f")),"f"),C(this,ce,null,"f");continue}let o=f(this,ce,"f")!==null?s.preceding-1:s.preceding,i=li(f(this,ue,"f").subarray(0,o));n.push(i),C(this,ue,f(this,ue,"f").subarray(s.index),"f"),C(this,ce,null,"f")}return n}flush(){return f(this,ue,"f").length?this.decode(`
39
+ `):[]}};ue=new WeakMap,ce=new WeakMap;gt.NEWLINE_CHARS=new Set([`
40
+ `,"\r"]);gt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function rd(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Cl(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var Cs={off:0,error:200,warn:300,info:400,debug:500},ui=(t,e,r)=>{if(t){if(sl(Cs,t))return t;q(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Cs))}`)}};function Rn(){}function Ts(t,e,r){return!e||Cs[t]>Cs[r]?Rn:e[t].bind(e)}var nd={error:Rn,warn:Rn,info:Rn,debug:Rn},Pl=new WeakMap;function q(t){let e=t.logger,r=t.logLevel??"off";if(!e)return nd;let n=Pl.get(e);if(n&&n[0]===r)return n[1];let s={error:Ts("error",e,r),warn:Ts("warn",e,r),info:Ts("info",e,r),debug:Ts("debug",e,r)};return Pl.set(e,[r,s]),s}var Ee=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var $n,Te=class t{constructor(e,r,n){this.iterator=e,$n.set(this,void 0),this.controller=r,C(this,$n,n,"f")}static fromSSEResponse(e,r,n,s){let o=!1,i=n?q(n):console;async function*a(){if(o)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let u=!1;try{for await(let l of sd(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let p;try{p=JSON.parse(l.data)}catch(m){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),m}if(p&&p.error)throw new F(void 0,p.error,void 0,e.headers);yield s?{event:l.event,data:p}:p}else{let p;try{p=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new F(void 0,p.error,p.message,void 0);yield{event:l.event,data:p}}}u=!0}catch(l){if(kn(l))return;throw l}finally{u||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let s=!1;async function*o(){let a=new gt,u=ei(e);for await(let l of u)for(let p of a.decode(l))yield p;for(let l of a.flush())yield l}async function*i(){if(s)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let u of o())a||u&&(yield JSON.parse(u));a=!0}catch(u){if(kn(u))return;throw u}finally{a||r.abort()}}return new t(i,r,n)}[($n=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>s(e),this.controller,f(this,$n,"f")),new t(()=>s(r),this.controller,f(this,$n,"f"))]}toReadableStream(){let e=this,r;return Qo({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await r.next();if(o)return n.close();let i=dr(JSON.stringify(s)+`
41
+ `);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){await r.return?.()}})}};async function*sd(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new v("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 v("Attempted to iterate over a response with no body");let r=new ci,n=new gt,s=ei(t.body);for await(let o of od(s))for(let i of n.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of n.flush()){let i=r.decode(o);i&&(yield i)}}async function*od(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?dr(r):r,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=Cl(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var ci=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 o={event:this.event,data:this.data.join(`
42
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,s]=id(e,":");return s.startsWith(" ")&&(s=s.substring(1)),r==="event"?this.event=s:r==="data"&&this.data.push(s),null}};function id(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Ps(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return q(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):Te.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 _=await r.json();return pi(_,r)}return await r.text()})();return q(t).debug(`[${n}] response parsed`,Ee({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function pi(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 Nn,_t=class t extends Promise{constructor(e,r,n=Ps){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Nn.set(this,void 0),C(this,Nn,e,"f")}_thenUnwrap(e){return new t(f(this,Nn,"f"),this.responsePromise,async(r,n)=>pi(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(f(this,Nn,"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)}};Nn=new WeakMap;var Os,mr=class{constructor(e,r,n,s){Os.set(this,void 0),C(this,Os,e,"f"),this.options=s,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await f(this,Os,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Os=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Ln=class extends _t{constructor(e,r,n){super(e,r,async(s,o)=>new n(s,o.response,await Ps(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},ie=class extends mr{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends mr{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...bs(this.options.query),after:r}}:null}},$=class extends mr{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...bs(this.options.query),after:e}}:null}},J=class extends mr{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...bs(this.options.query),after:e}}:null}};var ld={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},ud="urn:ietf:params:oauth:grant-type:token-exchange",ks=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Is()}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:ud,subject_token:e,subject_token_type:ld[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let a=await n.text(),u;try{u=JSON.parse(a)}catch{}throw n.status===400||n.status===401||n.status===403?new ht(n.status,u,n.headers):F.generate(n.status,u,`Token exchange failed with status ${n.status}`,n.headers)}let s=await n.json(),o=s.expires_in||3600,i=Date.now()+o*1e3;return this.cachedToken={token:s.access_token,expiresAt:i},s.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var fi=()=>{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 fr(t,e,r){return fi(),new File(t,e??"unknown_file",r)}function Dn(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 Ss=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Ve=async(t,e)=>di(t.body)?{...t,body:await kl(t.body,e)}:t,ae=async(t,e)=>({...t,body:await kl(t.body,e)}),Ol=new WeakMap;function cd(t){let e=typeof t=="function"?t:t.fetch,r=Ol.get(e);if(r)return r;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Ol.set(e,n),n}var kl=async(t,e)=>{if(!await cd(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,s])=>mi(r,n,s))),r},Sl=t=>t instanceof Blob&&"name"in t,pd=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Ss(t)||Sl(t)),di=t=>{if(pd(t))return!0;if(Array.isArray(t))return t.some(di);if(t&&typeof t=="object"){for(let e in t)if(di(t[e]))return!0}return!1},mi=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,fr([await r.blob()],Dn(r)));else if(Ss(r))t.append(e,fr([await new Response(xs(r)).blob()],Dn(r)));else if(Sl(r))t.append(e,r,Dn(r));else if(Array.isArray(r))await Promise.all(r.map(n=>mi(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>mi(t,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var El=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",dd=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&El(t),md=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function jn(t,e,r){if(fi(),t=await t,dd(t))return t instanceof File?t:fr([await t.arrayBuffer()],t.name);if(md(t)){let s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),fr(await hi(s),e,r)}let n=await hi(t);if(e||(e=Dn(t)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return fr(n,e,r)}async function hi(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(El(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Ss(t))for await(let r of t)e.push(...await hi(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${fd(t)}`)}return e}function fd(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var d=class{constructor(e){this._client=e}};function Rl(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ml=Object.freeze(Object.create(null)),gd=(t=Rl)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((p,m,_)=>{/[?#]/.test(m)&&(s=!0);let h=n[_],A=(s?encodeURIComponent:t)(""+h);return _!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Ml)??Ml)?.toString)&&(A=h+"",o.push({start:p.length+m.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),p+m+(_===n.length?"":A)},""),a=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(a))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((p,m)=>p.start-m.start),o.length>0){let p=0,m=o.reduce((_,h)=>{let A=" ".repeat(h.start-p),I="^".repeat(h.length);return p=h.start+h.length,_+A+I},"");throw new v(`Path parameters result in path with invalid segments:
43
+ ${o.map(_=>_.error).join(`
44
+ `)}
45
+ ${i}
46
+ ${m}`)}return i},c=gd(Rl);var yt=class extends d{list(e,r={},n){return this._client.getAPIList(c`/chat/completions/${e}/messages`,S,{query:r,...n,__security:{bearerAuth:!0}})}};function zn(t){return t!==void 0&&"function"in t&&t.function!==void 0}function $l(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Un(t){return t?.$brand==="auto-parseable-response-format"}function wt(t){return t?.$brand==="auto-parseable-tool"}function Nl(t,e){return!e||!gi(e)?{...t,choices:t.choices.map(r=>(Dl(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Fn(t,e)}function Fn(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new cr;if(n.finish_reason==="content_filter")throw new pr;return Dl(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>Ad(e,s))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?wd(e,n.message.content):null}}});return{...t,choices:r}}function wd(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 Ad(t,e){let r=t.tools?.find(n=>zn(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:wt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Ll(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>zn(n)&&n.function?.name===e.function.name);return zn(r)&&(wt(r)||r?.function.strict||!1)}function gi(t){return Un(t.response_format)?!0:t.tools?.some(e=>wt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Dl(t){for(let e of t||[])if(e.type!=="function")throw new v(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function jl(t){for(let e of t??[]){if(e.type!=="function")throw new v(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new v(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var hr=t=>t?.role==="assistant",_i=t=>t?.role==="tool";var yi,Es,Ms,Bn,Kn,Rs,Wn,Me,qn,$s,Ns,gr,zl,Ge=class{constructor(){yi.add(this),this.controller=new AbortController,Es.set(this,void 0),Ms.set(this,()=>{}),Bn.set(this,()=>{}),Kn.set(this,void 0),Rs.set(this,()=>{}),Wn.set(this,()=>{}),Me.set(this,{}),qn.set(this,!1),$s.set(this,!1),Ns.set(this,!1),gr.set(this,!1),C(this,Es,new Promise((e,r)=>{C(this,Ms,e,"f"),C(this,Bn,r,"f")}),"f"),C(this,Kn,new Promise((e,r)=>{C(this,Rs,e,"f"),C(this,Wn,r,"f")}),"f"),f(this,Es,"f").catch(()=>{}),f(this,Kn,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},f(this,yi,"m",zl).bind(this))},0)}_connected(){this.ended||(f(this,Ms,"f").call(this),this._emit("connect"))}get ended(){return f(this,qn,"f")}get errored(){return f(this,$s,"f")}get aborted(){return f(this,Ns,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,Me,"f")[e]||(f(this,Me,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=f(this,Me,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(f(this,Me,"f")[e]||(f(this,Me,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{C(this,gr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){C(this,gr,!0,"f"),await f(this,Kn,"f")}_emit(e,...r){if(f(this,qn,"f"))return;e==="end"&&(C(this,qn,!0,"f"),f(this,Rs,"f").call(this));let n=f(this,Me,"f")[e];if(n&&(f(this,Me,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!f(this,gr,"f")&&!n?.length&&Promise.reject(s),f(this,Bn,"f").call(this,s),f(this,Wn,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!f(this,gr,"f")&&!n?.length&&Promise.reject(s),f(this,Bn,"f").call(this,s),f(this,Wn,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Es=new WeakMap,Ms=new WeakMap,Bn=new WeakMap,Kn=new WeakMap,Rs=new WeakMap,Wn=new WeakMap,Me=new WeakMap,qn=new WeakMap,$s=new WeakMap,Ns=new WeakMap,gr=new WeakMap,yi=new WeakSet,zl=function(e){if(C(this,$s,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new B),e instanceof B)return C(this,Ns,!0,"f"),this._emit("abort",e);if(e instanceof v)return this._emit("error",e);if(e instanceof Error){let r=new v(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new v(String(e)))};function Ul(t){return typeof t.parse=="function"}var le,wi,Ls,Ai,bi,Ii,Fl,Bl,bd=10,_r=class extends Ge{constructor(){super(...arguments),le.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),_i(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(hr(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new v("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),f(this,le,"m",wi).call(this)}async finalMessage(){return await this.done(),f(this,le,"m",Ls).call(this)}async finalFunctionToolCall(){return await this.done(),f(this,le,"m",Ai).call(this)}async finalFunctionToolCallResult(){return await this.done(),f(this,le,"m",bi).call(this)}async totalUsage(){return await this.done(),f(this,le,"m",Ii).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=f(this,le,"m",Ls).call(this);r&&this._emit("finalMessage",r);let n=f(this,le,"m",wi).call(this);n&&this._emit("finalContent",n);let s=f(this,le,"m",Ai).call(this);s&&this._emit("finalFunctionToolCall",s);let o=f(this,le,"m",bi).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",f(this,le,"m",Ii).call(this))}async _createChatCompletion(e,r,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),f(this,le,"m",Fl).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Fn(o,r))}async _runChatCompletion(e,r,n){for(let s of r.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let s="tool",{tool_choice:o="auto",stream:i,...a}=r,u=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:l=bd}=n||{},p=r.tools.map(h=>{if(wt(h)){if(!h.$callback)throw new v("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),m={};for(let h of p)h.type==="function"&&(m[h.function.name||h.function.function.name]=h.function);let _="tools"in r?p.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of r.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){let I=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:_,messages:[...this.messages]},n)).choices[0]?.message;if(!I)throw new v("missing message in ChatCompletion response");if(!I.tool_calls?.length)return;for(let E of I.tool_calls){if(E.type!=="function")continue;let g=E.id,{name:w,arguments:k}=E.function,L=m[w];if(L){if(u&&u!==w){let U=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:g,content:U});continue}}else{let U=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(m).map(Y=>JSON.stringify(Y)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:g,content:U});continue}let R;try{R=Ul(L)?await L.parse(k):k}catch(U){let Y=U instanceof Error?U.message:String(U);this._addMessage({role:s,tool_call_id:g,content:Y});continue}let j=await L.function(R,this),Q=f(this,le,"m",Bl).call(this,j);if(this._addMessage({role:s,tool_call_id:g,content:Q}),u)return}}}};le=new WeakSet,wi=function(){return f(this,le,"m",Ls).call(this).content??null},Ls=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(hr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new v("stream ended without producing a ChatCompletionMessage with role=assistant")},Ai=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(hr(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},bi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(_i(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===r.tool_call_id)))return r.content}},Ii=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},Fl=function(e){if(e.n!=null&&e.n>1)throw new v("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Bl=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Hn=class t extends _r{static runTools(e,r,n){let s=new t,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,r,o)),s}_addMessage(e,r=!0){super._addMessage(e,r),hr(e)&&e.content&&this._emit("content",e.content)}};var X={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},xi=class extends Error{},vi=class extends Error{};function Id(t,e=X.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return xd(t.trim(),e)}var xd=(t,e)=>{let r=t.length,n=0,s=_=>{throw new xi(`${_} at position ${n}`)},o=_=>{throw new vi(`${_} at position ${n}`)},i=()=>(m(),n>=r&&s("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||X.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||X.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||X.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||X.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||X.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||X.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):p()),a=()=>{let _=n,h=!1;for(n++;n<r&&(t[n]!=='"'||h&&t[n-1]==="\\");)h=t[n]==="\\"?!h:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(_,++n-Number(h)))}catch(A){o(String(A))}else if(X.STR&e)try{return JSON.parse(t.substring(_,n-Number(h))+'"')}catch{return JSON.parse(t.substring(_,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,m();let _={};try{for(;t[n]!=="}";){if(m(),n>=r&&X.OBJ&e)return _;let h=a();m(),n++;try{let A=i();Object.defineProperty(_,h,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(X.OBJ&e)return _;throw A}m(),t[n]===","&&n++}}catch{if(X.OBJ&e)return _;s("Expected '}' at end of object")}return n++,_},l=()=>{n++;let _=[];try{for(;t[n]!=="]";)_.push(i()),m(),t[n]===","&&n++}catch{if(X.ARR&e)return _;s("Expected ']' at end of array")}return n++,_},p=()=>{if(n===0){t==="-"&&X.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(X.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(h))}}let _=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(X.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(_,n))}catch{t.substring(_,n)==="-"&&X.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(_,t.lastIndexOf("e")))}catch(A){o(String(A))}}},m=()=>{for(;n<r&&`
47
+ \r `.includes(t[n]);)n++};return i()},Ti=t=>Id(t,X.ALL^X.NUM);var G,Re,yr,Ye,Ci,Ds,Pi,Oi,ki,js,Si,Kl,At=class t extends _r{constructor(e){super(),G.add(this),Re.set(this,void 0),yr.set(this,void 0),Ye.set(this,void 0),C(this,Re,e,"f"),C(this,yr,[],"f")}get currentChatCompletionSnapshot(){return f(this,Ye,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let s=new t(r);return s._run(()=>s._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,r,n){super._createChatCompletion;let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),f(this,G,"m",Ci).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let i of o)f(this,G,"m",Pi).call(this,i);if(o.controller.signal?.aborted)throw new B;return this._addChatCompletion(f(this,G,"m",js).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),f(this,G,"m",Ci).call(this),this._connected();let s=Te.fromReadableStream(e,this.controller),o;for await(let i of s)o&&o!==i.id&&this._addChatCompletion(f(this,G,"m",js).call(this)),f(this,G,"m",Pi).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new B;return this._addChatCompletion(f(this,G,"m",js).call(this))}[(Re=new WeakMap,yr=new WeakMap,Ye=new WeakMap,G=new WeakSet,Ci=function(){this.ended||C(this,Ye,void 0,"f")},Ds=function(r){let n=f(this,yr,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},f(this,yr,"f")[r.index]=n,n)},Pi=function(r){if(this.ended)return;let n=f(this,G,"m",Kl).call(this,r);this._emit("chunk",r,n);for(let s of r.choices){let o=n.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=f(this,G,"m",Ds).call(this,o);o.finish_reason&&(f(this,G,"m",ki).call(this,o),i.current_tool_call_index!=null&&f(this,G,"m",Oi).call(this,o,i.current_tool_call_index));for(let a of s.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(f(this,G,"m",ki).call(this,o),i.current_tool_call_index!=null&&f(this,G,"m",Oi).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[a.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:a.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(u?.type,void 0))}}},Oi=function(r,n){if(f(this,G,"m",Ds).call(this,r).done_tool_calls.has(n))return;let o=r.message.tool_calls?.[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=f(this,Re,"f")?.tools?.find(a=>zn(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:wt(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},ki=function(r){let n=f(this,G,"m",Ds).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let s=f(this,G,"m",Si).call(this);this._emit("content.done",{content:r.message.content,parsed:s?s.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},js=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let r=f(this,Ye,"f");if(!r)throw new v("request ended without sending any chunks");return C(this,Ye,void 0,"f"),C(this,yr,[],"f"),vd(r,f(this,Re,"f"))},Si=function(){let r=f(this,Re,"f")?.response_format;return Un(r)?r:null},Kl=function(r){var n,s,o,i;let a=f(this,Ye,"f"),{choices:u,...l}=r;a?Object.assign(a,l):a=C(this,Ye,{...l,choices:[]},"f");for(let{delta:p,finish_reason:m,index:_,logprobs:h=null,...A}of r.choices){let I=a.choices[_];if(I||(I=a.choices[_]={finish_reason:m,index:_,message:{},logprobs:h,...A}),h)if(!I.logprobs)I.logprobs=Object.assign({},h);else{let{content:j,refusal:Q,...U}=h;Object.assign(I.logprobs,U),j&&((n=I.logprobs).content??(n.content=[]),I.logprobs.content.push(...j)),Q&&((s=I.logprobs).refusal??(s.refusal=[]),I.logprobs.refusal.push(...Q))}if(m&&(I.finish_reason=m,f(this,Re,"f")&&gi(f(this,Re,"f")))){if(m==="length")throw new cr;if(m==="content_filter")throw new pr}if(Object.assign(I,A),!p)continue;let{content:E,refusal:g,function_call:w,role:k,tool_calls:L,...R}=p;if(Object.assign(I.message,R),g&&(I.message.refusal=(I.message.refusal||"")+g),k&&(I.message.role=k),w&&(I.message.function_call?(w.name&&(I.message.function_call.name=w.name),w.arguments&&((o=I.message.function_call).arguments??(o.arguments=""),I.message.function_call.arguments+=w.arguments)):I.message.function_call=w),E&&(I.message.content=(I.message.content||"")+E,!I.message.refusal&&f(this,G,"m",Si).call(this)&&(I.message.parsed=Ti(I.message.content))),L){I.message.tool_calls||(I.message.tool_calls=[]);for(let{index:j,id:Q,type:U,function:Y,...H}of L){let Z=(i=I.message.tool_calls)[j]??(i[j]={});Object.assign(Z,H),Q&&(Z.id=Q),U&&(Z.type=U),Y&&(Z.function??(Z.function={name:Y.name??"",arguments:""})),Y?.name&&(Z.function.name=Y.name),Y?.arguments&&(Z.function.arguments+=Y.arguments,Ll(f(this,Re,"f"),Z)&&(Z.function.parsed_arguments=Ti(Z.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function vd(t,e){let{id:r,choices:n,created:s,model:o,system_fingerprint:i,...a}=t,u={...a,id:r,choices:n.map(({message:l,finish_reason:p,index:m,logprobs:_,...h})=>{if(!p)throw new v(`missing finish_reason for choice ${m}`);let{content:A=null,function_call:I,tool_calls:E,...g}=l,w=l.role;if(!w)throw new v(`missing role for choice ${m}`);if(I){let{arguments:k,name:L}=I;if(k==null)throw new v(`missing function_call.arguments for choice ${m}`);if(!L)throw new v(`missing function_call.name for choice ${m}`);return{...h,message:{content:A,function_call:{arguments:k,name:L},role:w,refusal:l.refusal??null},finish_reason:p,index:m,logprobs:_}}return E?{...h,index:m,finish_reason:p,logprobs:_,message:{...g,role:w,content:A,refusal:l.refusal??null,tool_calls:E.map((k,L)=>{let{function:R,type:j,id:Q,...U}=k,{arguments:Y,name:H,...Z}=R||{};if(Q==null)throw new v(`missing choices[${m}].tool_calls[${L}].id
48
+ ${zs(t)}`);if(j==null)throw new v(`missing choices[${m}].tool_calls[${L}].type
49
+ ${zs(t)}`);if(H==null)throw new v(`missing choices[${m}].tool_calls[${L}].function.name
50
+ ${zs(t)}`);if(Y==null)throw new v(`missing choices[${m}].tool_calls[${L}].function.arguments
51
+ ${zs(t)}`);return{...U,id:Q,type:j,function:{...Z,name:H,arguments:Y}}})}}:{...h,message:{...g,content:A,role:w,refusal:l.refusal??null},finish_reason:p,index:m,logprobs:_}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Nl(u,e)}function zs(t){return JSON.stringify(t)}var Jn=class t extends At{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let s=new t(r),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,r,o)),s}};var $e=class extends d{constructor(){super(...arguments),this.messages=new yt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",S,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return jl(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Fn(n,e))}runTools(e,r){return e.stream?Jn.runTools(this._client,e,r):Hn.runTools(this._client,e,r)}stream(e,r){return At.createChatCompletion(this._client,e,r)}};$e.Messages=yt;var Xe=class extends d{constructor(){super(...arguments),this.completions=new $e(this._client)}};Xe.Completions=$e;var wr=class extends d{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(c`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",S,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ar=class extends d{list(e={},r){return this._client.getAPIList("/organization/audit_logs",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var br=class extends d{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(c`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",ie,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",ie,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Ir=class extends d{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 xr=class extends d{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(c`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var vr=class extends d{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(c`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",J,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Tr=class extends d{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Cr=class extends d{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 Pr=class extends d{create(e,r,n){return this._client.post(c`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:s}=r;return this._client.get(c`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/groups/${e}/roles`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:s}=r;return this._client.delete(c`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Or=class extends d{create(e,r,n){return this._client.post(c`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:s}=r;return this._client.get(c`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/groups/${e}/users`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:s}=r;return this._client.delete(c`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Qe=class extends d{constructor(){super(...arguments),this.users=new Or(this._client),this.roles=new Pr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(c`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",J,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Qe.Users=Or;Qe.Roles=Pr;var kr=class extends d{retrieve(e,r,n){let{project_id:s}=r;return this._client.get(c`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/api_keys`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s}=r;return this._client.delete(c`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Sr=class extends d{list(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/certificates`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(c`/organization/projects/${e}/certificates/activate`,ie,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(c`/organization/projects/${e}/certificates/deactivate`,ie,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Er=class extends d{retrieve(e,r){return this._client.get(c`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Mr=class extends d{retrieve(e,r){return this._client.get(c`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Rr=class extends d{retrieve(e,r){return this._client.get(c`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var $r=class extends d{listRateLimits(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/rate_limits`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/organization/projects/${s}/rate_limits/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}};var Nr=class extends d{create(e,r,n){return this._client.post(c`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:s}=r;return this._client.get(c`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/projects/${s}/roles/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/projects/${e}/roles`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s}=r;return this._client.delete(c`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Lr=class extends d{create(e,r,n){return this._client.post(c`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:s}=r;return this._client.get(c`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/organization/projects/${s}/service_accounts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/service_accounts`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s}=r;return this._client.delete(c`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Dr=class extends d{create(e,r,n){return this._client.post(c`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/organization/projects/${s}/spend_alerts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/spend_alerts`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s}=r;return this._client.delete(c`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var jr=class extends d{create(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/projects/${s}/groups/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:s,group_id:o}=r;return this._client.get(c`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:s,...o}=r;return this._client.getAPIList(c`/projects/${s}/groups/${e}/roles`,J,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s,group_id:o}=r;return this._client.delete(c`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var bt=class extends d{constructor(){super(...arguments),this.roles=new jr(this._client)}create(e,r,n){return this._client.post(c`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:s,...o}=r;return this._client.get(c`/organization/projects/${s}/groups/${e}`,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/groups`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s}=r;return this._client.delete(c`/organization/projects/${s}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};bt.Roles=jr;var zr=class extends d{create(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/projects/${s}/users/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:s,user_id:o}=r;return this._client.get(c`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:s,...o}=r;return this._client.getAPIList(c`/projects/${s}/users/${e}/roles`,J,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s,user_id:o}=r;return this._client.delete(c`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var It=class extends d{constructor(){super(...arguments),this.roles=new zr(this._client)}create(e,r,n){return this._client.post(c`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:s}=r;return this._client.get(c`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:s,...o}=r;return this._client.post(c`/organization/projects/${s}/users/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/projects/${e}/users`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:s}=r;return this._client.delete(c`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};It.Roles=zr;var ee=class extends d{constructor(){super(...arguments),this.users=new It(this._client),this.serviceAccounts=new Lr(this._client),this.apiKeys=new kr(this._client),this.rateLimits=new $r(this._client),this.modelPermissions=new Rr(this._client),this.hostedToolPermissions=new Mr(this._client),this.groups=new bt(this._client),this.roles=new Nr(this._client),this.dataRetention=new Er(this._client),this.spendAlerts=new Dr(this._client),this.certificates=new Sr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(c`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(c`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ee.Users=It;ee.ServiceAccounts=Lr;ee.APIKeys=kr;ee.RateLimits=$r;ee.ModelPermissions=Rr;ee.HostedToolPermissions=Mr;ee.Groups=bt;ee.Roles=Nr;ee.DataRetention=Er;ee.SpendAlerts=Dr;ee.Certificates=Sr;var Ur=class extends d{create(e,r,n){return this._client.post(c`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:s}=r;return this._client.get(c`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/organization/users/${e}/roles`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:s}=r;return this._client.delete(c`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var xt=class extends d{constructor(){super(...arguments),this.roles=new Ur(this._client)}retrieve(e,r){return this._client.get(c`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(c`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(c`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};xt.Roles=Ur;var te=class extends d{constructor(){super(...arguments),this.auditLogs=new Ar(this._client),this.adminAPIKeys=new wr(this._client),this.usage=new Cr(this._client),this.invites=new xr(this._client),this.users=new xt(this._client),this.groups=new Qe(this._client),this.roles=new vr(this._client),this.dataRetention=new Ir(this._client),this.spendAlerts=new Tr(this._client),this.certificates=new br(this._client),this.projects=new ee(this._client)}};te.AuditLogs=Ar;te.AdminAPIKeys=wr;te.Usage=Cr;te.Invites=xr;te.Users=xt;te.Groups=Qe;te.Roles=vr;te.DataRetention=Ir;te.SpendAlerts=Tr;te.Certificates=br;te.Projects=ee;var et=class extends d{constructor(){super(...arguments),this.organization=new te(this._client)}};et.Organization=te;var Wl=Symbol("brand.privateNullableHeaders");function*em(t){if(!t)return;if(Wl in t){let{values:n,nulls:s}=t;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Yo(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Yo(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var x=t=>{let e=new Headers,r=new Set;for(let n of t){let s=new Set;for(let[o,i]of em(n)){let a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[Wl]:!0,values:e,nulls:r}};var Fr=class extends d{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:x([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Br=class extends d{create(e,r){return this._client.post("/audio/transcriptions",ae({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Kr=class extends d{create(e,r){return this._client.post("/audio/translations",ae({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Ce=class extends d{constructor(){super(...arguments),this.transcriptions=new Br(this._client),this.translations=new Kr(this._client),this.speech=new Fr(this._client)}};Ce.Transcriptions=Br;Ce.Translations=Kr;Ce.Speech=Fr;var vt=class extends d{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",S,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(c`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var Wr=class extends d{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/assistants/${e}`,{...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/assistants/${e}`,{body:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",S,{query:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/assistants/${e}`,{...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var qr=class extends d{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Hr=class extends d{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var tt=class extends d{constructor(){super(...arguments),this.sessions=new qr(this._client),this.transcriptionSessions=new Hr(this._client)}};tt.Sessions=qr;tt.TranscriptionSessions=Hr;var Jr=class extends d{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...r,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Zr=class extends d{retrieve(e,r){return this._client.get(c`/chatkit/threads/${e}`,{...r,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",$,{query:e,...r,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/chatkit/threads/${e}`,{...r,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,$,{query:r,...n,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var rt=class extends d{constructor(){super(...arguments),this.sessions=new Jr(this._client),this.threads=new Zr(this._client)}};rt.Sessions=Jr;rt.Threads=Zr;var Vr=class extends d{create(e,r,n){return this._client.post(c`/threads/${e}/messages`,{body:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:s}=r;return this._client.get(c`/threads/${s}/messages/${e}`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:s,...o}=r;return this._client.post(c`/threads/${s}/messages/${e}`,{body:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/threads/${e}/messages`,S,{query:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:s}=r;return this._client.delete(c`/threads/${s}/messages/${e}`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Gr=class extends d{retrieve(e,r,n){let{thread_id:s,run_id:o,...i}=r;return this._client.get(c`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:s,...o}=r;return this._client.getAPIList(c`/threads/${s}/runs/${e}/steps`,S,{query:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var ql=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var Pe=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 re,Ct,Ei,Oe,Us,fe,Pt,Yr,Tt,Ks,pe,Fs,Bs,Gn,Zn,Vn,Hl,Jl,Zl,Vl,Gl,Yl,Xl,Ne=class extends Ge{constructor(){super(...arguments),re.add(this),Ei.set(this,[]),Oe.set(this,{}),Us.set(this,{}),fe.set(this,void 0),Pt.set(this,void 0),Yr.set(this,void 0),Tt.set(this,void 0),Ks.set(this,void 0),pe.set(this,void 0),Fs.set(this,void 0),Bs.set(this,void 0),Gn.set(this,void 0)}[(Ei=new WeakMap,Oe=new WeakMap,Us=new WeakMap,fe=new WeakMap,Pt=new WeakMap,Yr=new WeakMap,Tt=new WeakMap,Ks=new WeakMap,pe=new WeakMap,Fs=new WeakMap,Bs=new WeakMap,Gn=new WeakMap,re=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Ct;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=Te.fromReadableStream(e,this.controller);for await(let o of s)f(this,re,"m",Zn).call(this,o);if(s.controller.signal?.aborted)throw new B;return this._addRun(f(this,re,"m",Vn).call(this))}toReadableStream(){return new Te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,s){let o=new Ct;return o._run(()=>o._runToolAssistantStream(e,r,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...s,signal:this.controller.signal});this._connected();for await(let u of a)f(this,re,"m",Zn).call(this,u);if(a.controller.signal?.aborted)throw new B;return this._addRun(f(this,re,"m",Vn).call(this))}static createThreadAssistantStream(e,r,n){let s=new Ct;return s._run(()=>s._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,r,n,s){let o=new Ct;return o._run(()=>o._runAssistantStream(e,r,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return f(this,Fs,"f")}currentRun(){return f(this,Bs,"f")}currentMessageSnapshot(){return f(this,fe,"f")}currentRunStepSnapshot(){return f(this,Gn,"f")}async finalRunSteps(){return await this.done(),Object.values(f(this,Oe,"f"))}async finalMessages(){return await this.done(),Object.values(f(this,Us,"f"))}async finalRun(){if(await this.done(),!f(this,Pt,"f"))throw Error("Final run was not received.");return f(this,Pt,"f")}async _createThreadAssistantStream(e,r,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},i=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of i)f(this,re,"m",Zn).call(this,a);if(i.controller.signal?.aborted)throw new B;return this._addRun(f(this,re,"m",Vn).call(this))}async _createAssistantStream(e,r,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...s,signal:this.controller.signal});this._connected();for await(let u of a)f(this,re,"m",Zn).call(this,u);if(a.controller.signal?.aborted)throw new B;return this._addRun(f(this,re,"m",Vn).call(this))}static accumulateDelta(e,r){for(let[n,s]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Mn(o)&&Mn(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!Mn(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let u=o[a];u==null?o.push(i):o[a]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,s){return await this._createAssistantStream(r,e,n,s)}async _runToolAssistantStream(e,r,n,s){return await this._createToolAssistantStream(r,e,n,s)}};Ct=Ne,Zn=function(e){if(!this.ended)switch(C(this,Fs,e,"f"),f(this,re,"m",Zl).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":f(this,re,"m",Xl).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":f(this,re,"m",Jl).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":f(this,re,"m",Hl).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Vn=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");if(!f(this,Pt,"f"))throw Error("Final run has not been received");return f(this,Pt,"f")},Hl=function(e){let[r,n]=f(this,re,"m",Gl).call(this,e,f(this,fe,"f"));C(this,fe,r,"f"),f(this,Us,"f")[r.id]=r;for(let s of n){let o=r.content[s.index];o?.type=="text"&&this._emit("textCreated",o.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 s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=r.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=f(this,Yr,"f")){if(f(this,Tt,"f"))switch(f(this,Tt,"f").type){case"text":this._emit("textDone",f(this,Tt,"f").text,f(this,fe,"f"));break;case"image_file":this._emit("imageFileDone",f(this,Tt,"f").image_file,f(this,fe,"f"));break}C(this,Yr,s.index,"f")}C(this,Tt,r.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(f(this,Yr,"f")!==void 0){let s=e.data.content[f(this,Yr,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,f(this,fe,"f"));break;case"text":this._emit("textDone",s.text,f(this,fe,"f"));break}}f(this,fe,"f")&&this._emit("messageDone",e.data),C(this,fe,void 0,"f")}},Jl=function(e){let r=f(this,re,"m",Vl).call(this,e);switch(C(this,Gn,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==f(this,Ks,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(f(this,pe,"f")&&this._emit("toolCallDone",f(this,pe,"f")),C(this,Ks,o.index,"f"),C(this,pe,r.step_details.tool_calls[o.index],"f"),f(this,pe,"f")&&this._emit("toolCallCreated",f(this,pe,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":C(this,Gn,void 0,"f"),e.data.step_details.type=="tool_calls"&&f(this,pe,"f")&&(this._emit("toolCallDone",f(this,pe,"f")),C(this,pe,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Zl=function(e){f(this,Ei,"f").push(e),this._emit("event",e)},Vl=function(e){switch(e.event){case"thread.run.step.created":return f(this,Oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=f(this,Oe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=Ct.accumulateDelta(r,n.delta);f(this,Oe,"f")[e.data.id]=s}return f(this,Oe,"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":f(this,Oe,"f")[e.data.id]=e.data;break}if(f(this,Oe,"f")[e.data.id])return f(this,Oe,"f")[e.data.id];throw new Error("No snapshot available")},Gl=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in r.content){let i=r.content[o.index];r.content[o.index]=f(this,re,"m",Yl).call(this,o,i)}else r.content[o.index]=o,n.push(o);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Yl=function(e,r){return Ct.accumulateDelta(r,e)},Xl=function(e){switch(C(this,Bs,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":C(this,Pt,e.data,"f"),f(this,pe,"f")&&(this._emit("toolCallDone",f(this,pe,"f")),C(this,pe,void 0,"f"));break;case"thread.run.cancelling":break}};var Ot=class extends d{constructor(){super(...arguments),this.steps=new Gr(this._client)}create(e,r,n){let{include:s,...o}=r;return this._client.post(c`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:s}=r;return this._client.get(c`/threads/${s}/runs/${e}`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:s,...o}=r;return this._client.post(c`/threads/${s}/runs/${e}`,{body:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/threads/${e}/runs`,S,{query:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:s}=r;return this._client.post(c`/threads/${s}/runs/${e}/cancel`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let s=await this.create(e,r,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,r,n){return Ne.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let s=x([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(a=l)}}await xe(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,r,n){return Ne.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:s,...o}=r;return this._client.post(c`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let s=await this.submitToolOutputs(e,r,n);return await this.poll(s.id,r,n)}submitToolOutputsStream(e,r,n){return Ne.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Ot.Steps=Gr;var nt=class extends d{constructor(){super(...arguments),this.runs=new Ot(this._client),this.messages=new Vr(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/threads/${e}`,{...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/threads/${e}`,{body:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/threads/${e}`,{...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ne.createThreadAssistantStream(e,this._client.beta.threads,r)}};nt.Runs=Ot;nt.Messages=Vr;var he=class extends d{constructor(){super(...arguments),this.realtime=new tt(this._client),this.chatkit=new rt(this._client),this.assistants=new Wr(this._client),this.threads=new nt(this._client)}};he.Realtime=tt;he.ChatKit=rt;he.Assistants=Wr;he.Threads=nt;var kt=class extends d{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Xr=class extends d{retrieve(e,r,n){let{container_id:s}=r;return this._client.get(c`/containers/${s}/files/${e}/content`,{...n,headers:x([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var St=class extends d{constructor(){super(...arguments),this.content=new Xr(this._client)}create(e,r,n){return this._client.post(c`/containers/${e}/files`,Ve({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:s}=r;return this._client.get(c`/containers/${s}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/containers/${e}/files`,S,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:s}=r;return this._client.delete(c`/containers/${s}/files/${e}`,{...n,headers:x([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};St.Content=Xr;var st=class extends d{constructor(){super(...arguments),this.files=new St(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",S,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/containers/${e}`,{...r,headers:x([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};st.Files=St;var Qr=class extends d{create(e,r,n){let{include:s,...o}=r;return this._client.post(c`/conversations/${e}/items`,{query:{include:s},body:o,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{conversation_id:s,...o}=r;return this._client.get(c`/conversations/${s}/items/${e}`,{query:o,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/conversations/${e}/items`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:s}=r;return this._client.delete(c`/conversations/${s}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var ot=class extends d{constructor(){super(...arguments),this.items=new Qr(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};ot.Items=Qr;var Et=class extends d{create(e,r){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&q(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...r,__security:{bearerAuth:!0}});return n?o:(q(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let u=a.embedding;a.embedding=ql(u)}),i)))}};var en=class extends d{retrieve(e,r,n){let{eval_id:s,run_id:o}=r;return this._client.get(c`/evals/${s}/runs/${o}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r,n){let{eval_id:s,...o}=r;return this._client.getAPIList(c`/evals/${s}/runs/${e}/output_items`,S,{query:o,...n,__security:{bearerAuth:!0}})}};var Mt=class extends d{constructor(){super(...arguments),this.outputItems=new en(this._client)}create(e,r,n){return this._client.post(c`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:s}=r;return this._client.get(c`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/evals/${e}/runs`,S,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:s}=r;return this._client.delete(c`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:s}=r;return this._client.post(c`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Mt.OutputItems=en;var it=class extends d{constructor(){super(...arguments),this.runs=new Mt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",S,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};it.Runs=Mt;var Rt=class extends d{create(e,r){return this._client.post("/files",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(c`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",S,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(c`/files/${e}/content`,{...r,headers:x([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await xe(r),i=await this.retrieve(e),Date.now()-o>n)throw new be({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var tn=class extends d{};var rn=class extends d{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 $t=class extends d{constructor(){super(...arguments),this.graders=new rn(this._client)}};$t.Graders=rn;var nn=class extends d{create(e,r,n){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ie,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,$,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:s}=r;return this._client.delete(c`/fine_tuning/checkpoints/${s}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Nt=class extends d{constructor(){super(...arguments),this.permissions=new nn(this._client)}};Nt.Permissions=nn;var sn=class extends d{list(e,r={},n){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,S,{query:r,...n,__security:{bearerAuth:!0}})}};var Lt=class extends d{constructor(){super(...arguments),this.checkpoints=new sn(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(c`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,S,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};Lt.Checkpoints=sn;var ge=class extends d{constructor(){super(...arguments),this.methods=new tn(this._client),this.jobs=new Lt(this._client),this.checkpoints=new Nt(this._client),this.alpha=new $t(this._client)}};ge.Methods=tn;ge.Jobs=Lt;ge.Checkpoints=Nt;ge.Alpha=$t;var on=class extends d{};var at=class extends d{constructor(){super(...arguments),this.graderModels=new on(this._client)}};at.GraderModels=on;var Dt=class extends d{createVariation(e,r){return this._client.post("/images/variations",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",ae({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 jt=class extends d{retrieve(e,r){return this._client.get(c`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",ie,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var zt=class extends d{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var an=class extends d{accept(e,r,n){return this._client.post(c`/realtime/calls/${e}/accept`,{body:r,...n,headers:x([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(c`/realtime/calls/${e}/hangup`,{...r,headers:x([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(c`/realtime/calls/${e}/refer`,{body:r,...n,headers:x([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(c`/realtime/calls/${e}/reject`,{body:r,...n,headers:x([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var ln=class extends d{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Le=class extends d{constructor(){super(...arguments),this.clientSecrets=new ln(this._client),this.calls=new an(this._client)}};Le.ClientSecrets=ln;Le.Calls=an;function Ql(t,e){return!e||!Em(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:Mi(t,e)}function Mi(t,e){let r=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:$m(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:Sm(e,i.text)}:i);return{...s,content:o}}return s}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||Ws(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function Sm(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Em(t){return!!Un(t.text?.format)}function Mm(t){return t?.$brand==="auto-parseable-tool"}function Rm(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function $m(t,e){let r=Rm(t.tools??[],e.name);return{...e,...e,parsed_arguments:Mm(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Ws(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var un,qs,lt,Hs,eu,tu,ru,nu,Js=class t extends Ge{constructor(e){super(),un.add(this),qs.set(this,void 0),lt.set(this,void 0),Hs.set(this,void 0),C(this,qs,e,"f")}static createResponse(e,r,n){let s=new t(r);return s._run(()=>s._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,r,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),f(this,un,"m",eu).call(this);let o,i=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)f(this,un,"m",tu).call(this,a,i);if(o.controller.signal?.aborted)throw new B;return f(this,un,"m",ru).call(this)}[(qs=new WeakMap,lt=new WeakMap,Hs=new WeakMap,un=new WeakSet,eu=function(){this.ended||C(this,lt,void 0,"f")},tu=function(r,n){if(this.ended)return;let s=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},o=f(this,un,"m",nu).call(this,r);switch(s("event",r),r.type){case"response.output_text.delta":{let i=o.output[r.output_index];if(!i)throw new v(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new v(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new v(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[r.output_index];if(!i)throw new v(`missing output at index ${r.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:s(r.type,r);break}},ru=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let r=f(this,lt,"f");if(!r)throw new v("request ended without sending any events");C(this,lt,void 0,"f");let n=Nm(r,f(this,qs,"f"));return C(this,Hs,n,"f"),n},nu=function(r){let n=f(this,lt,"f");if(!n){if(r.type!=="response.created")throw new v(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=C(this,lt,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let s=n.output[r.output_index];if(!s)throw new v(`missing output at index ${r.output_index}`);let o=s.type,i=r.part;o==="message"&&i.type!=="reasoning_text"?s.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(s.content||(s.content=[]),s.content.push(i));break}case"response.output_text.delta":{let s=n.output[r.output_index];if(!s)throw new v(`missing output at index ${r.output_index}`);if(s.type==="message"){let o=s.content[r.content_index];if(!o)throw new v(`missing content at index ${r.content_index}`);if(o.type!=="output_text")throw new v(`expected content to be 'output_text', got ${o.type}`);o.text+=r.delta}break}case"response.function_call_arguments.delta":{let s=n.output[r.output_index];if(!s)throw new v(`missing output at index ${r.output_index}`);s.type==="function_call"&&(s.arguments+=r.delta);break}case"response.reasoning_text.delta":{let s=n.output[r.output_index];if(!s)throw new v(`missing output at index ${r.output_index}`);if(s.type==="reasoning"){let o=s.content?.[r.content_index];if(!o)throw new v(`missing content at index ${r.content_index}`);if(o.type!=="reasoning_text")throw new v(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=r.delta}break}case"response.completed":{C(this,lt,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=f(this,Hs,"f");if(!e)throw new v("stream ended without producing a ChatCompletion");return e}};function Nm(t,e){return Ql(t,e)}var cn=class extends d{list(e,r={},n){return this._client.getAPIList(c`/responses/${e}/input_items`,S,{query:r,...n,__security:{bearerAuth:!0}})}};var pn=class extends d{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var De=class extends d{constructor(){super(...arguments),this.inputItems=new cn(this._client),this.inputTokens=new pn(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Ws(n),n))}retrieve(e,r={},n){return this._client.get(c`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ws(s),s))}delete(e,r){return this._client.delete(c`/responses/${e}`,{...r,headers:x([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Mi(n,e))}stream(e,r){return Js.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(c`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};De.InputItems=cn;De.InputTokens=pn;var dn=class extends d{retrieve(e,r){return this._client.get(c`/skills/${e}/content`,{...r,headers:x([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var mn=class extends d{retrieve(e,r,n){let{skill_id:s}=r;return this._client.get(c`/skills/${s}/versions/${e}/content`,{...n,headers:x([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Ut=class extends d{constructor(){super(...arguments),this.content=new mn(this._client)}create(e,r={},n){return this._client.post(c`/skills/${e}/versions`,Ve({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:s}=r;return this._client.get(c`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/skills/${e}/versions`,S,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:s}=r;return this._client.delete(c`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Ut.Content=mn;var je=class extends d{constructor(){super(...arguments),this.content=new dn(this._client),this.versions=new Ut(this._client)}create(e={},r){return this._client.post("/skills",Ve({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(c`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",S,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};je.Content=dn;je.Versions=Ut;var fn=class extends d{create(e,r,n){return this._client.post(c`/uploads/${e}/parts`,ae({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var ut=class extends d{constructor(){super(...arguments),this.parts=new fn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(c`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(c`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};ut.Parts=fn;var su=async t=>{let e=await Promise.allSettled(t),r=e.filter(s=>s.status==="rejected");if(r.length){for(let s of r)console.error(s.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var hn=class extends d{create(e,r,n){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:s}=r;return this._client.get(c`/vector_stores/${s}/file_batches/${e}`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:s}=r;return this._client.post(c`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let s=await this.create(e,r);return await this.poll(e,s.id,n)}listFiles(e,r,n){let{vector_store_id:s,...o}=r;return this._client.getAPIList(c`/vector_stores/${s}/file_batches/${e}/files`,S,{query:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let s=x([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(r,{vector_store_id:e},{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(a=l)}}await xe(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},s){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 o=s?.maxConcurrency??5,i=Math.min(o,r.length),a=this._client,u=r.values(),l=[...n];async function p(_){for(let h of _){let A=await a.files.create({file:h,purpose:"assistants"},s);l.push(A.id)}}let m=Array(i).fill(u).map(p);return await su(m),await this.createAndPoll(e,{file_ids:l})}};var gn=class extends d{create(e,r,n){return this._client.post(c`/vector_stores/${e}/files`,{body:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:s}=r;return this._client.get(c`/vector_stores/${s}/files/${e}`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:s,...o}=r;return this._client.post(c`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(c`/vector_stores/${e}/files`,S,{query:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:s}=r;return this._client.delete(c`/vector_stores/${s}/files/${e}`,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let s=await this.create(e,r,n);return await this.poll(e,s.id,n)}async poll(e,r,n){let s=x([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(r,{vector_store_id:e},{...n,headers:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(a=l)}}await xe(a);break;case"failed":case"completed":return i}}}async upload(e,r,n){let s=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,r,n){let s=await this.upload(e,r,n);return await this.poll(e,s.id,n)}content(e,r,n){let{vector_store_id:s}=r;return this._client.getAPIList(c`/vector_stores/${s}/files/${e}/content`,ie,{...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var ze=class extends d{constructor(){super(...arguments),this.files=new gn(this._client),this.fileBatches=new hn(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(c`/vector_stores/${e}`,{...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(c`/vector_stores/${e}`,{body:r,...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",S,{query:e,...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/vector_stores/${e}`,{...r,headers:x([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(c`/vector_stores/${e}/search`,ie,{body:r,method:"post",...n,headers:x([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};ze.Files=gn;ze.FileBatches=hn;var Ft=class extends d{create(e,r){return this._client.post("/videos",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(c`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(c`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(c`/videos/${e}/content`,{query:r,...n,headers:x([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(c`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(c`/videos/${e}/remix`,Ve({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var _n,ou,Zs,Bt=class extends d{constructor(){super(...arguments),_n.add(this)}async unwrap(e,r,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,r,n,s),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,s=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");f(this,_n,"m",ou).call(this,n);let o=x([r]).values,i=f(this,_n,"m",Zs).call(this,o,"webhook-signature"),a=f(this,_n,"m",Zs).call(this,o,"webhook-timestamp"),u=f(this,_n,"m",Zs).call(this,o,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new Ie("Invalid webhook timestamp format");let p=Math.floor(Date.now()/1e3);if(p-l>s)throw new Ie("Webhook timestamp is too old");if(l>p+s)throw new Ie("Webhook timestamp is too new");let m=i.split(" ").map(I=>I.startsWith("v1,")?I.substring(3):I),_=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=u?`${u}.${a}.${e}`:`${a}.${e}`,A=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let I of m)try{let E=Buffer.from(I,"base64");if(await crypto.subtle.verify("HMAC",A,E,new TextEncoder().encode(h)))return}catch{continue}throw new Ie("The given webhook signature does not match the expected signature")}};_n=new WeakSet,ou=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")},Zs=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Ri,$i,Vs,iu,qm="workload-identity-auth",P=class{constructor({baseURL:e=Pe("OPENAI_BASE_URL"),apiKey:r=Pe("OPENAI_API_KEY")??null,adminAPIKey:n=Pe("OPENAI_ADMIN_KEY")??null,organization:s=Pe("OPENAI_ORG_ID")??null,project:o=Pe("OPENAI_PROJECT_ID")??null,webhookSecret:i=Pe("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:a,...u}={}){Ri.add(this),Vs.set(this,void 0),this.completions=new kt(this),this.chat=new Xe(this),this.embeddings=new Et(this),this.files=new Rt(this),this.images=new Dt(this),this.audio=new Ce(this),this.moderations=new zt(this),this.models=new jt(this),this.fineTuning=new ge(this),this.graders=new at(this),this.vectorStores=new ze(this),this.webhooks=new Bt(this),this.beta=new he(this),this.batches=new vt(this),this.uploads=new ut(this),this.admin=new et(this),this.responses=new De(this),this.realtime=new Le(this),this.conversations=new ot(this),this.evals=new it(this),this.containers=new st(this),this.skills=new je(this),this.videos=new Ft(this);let l={apiKey:r,adminAPIKey:n,organization:s,project:o,webhookSecret:i,workloadIdentity:a,...u,baseURL:e||"https://api.openai.com/v1"};if(r&&a)throw new v("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!a)throw new v("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&cl())throw new v(`It looks like you're running in a browser-like environment.
52
+
53
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
54
+ If you understand the risks and have appropriate mitigations in place,
55
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
56
+
57
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
58
+
59
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
60
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??$i.DEFAULT_TIMEOUT,this.logger=l.logger??console;let p="warn";this.logLevel=p,this.logLevel=ui(l.logLevel,"ClientOptions.logLevel",this)??ui(Pe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??p,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Is(),C(this,Vs,ml,"f");let m=Pe("OPENAI_CUSTOM_HEADERS");if(m){let _={};for(let h of m.split(`
61
+ `)){let A=h.indexOf(":");A>=0&&(_[h.substring(0,A).trim()]=h.substring(A+1).trim())}l.defaultHeaders=x([_,l.defaultHeaders])}this._options=l,a&&(this._workloadIdentityAuth=new ks(a,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=s,this.project=o,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return x([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return x([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return x([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return x([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Il(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ze}`}defaultIdempotencyKey(){return`stainless-node-retry-${Go()}`}makeStatusError(e,r,n,s){return F.generate(e,r,n,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof v?n:new v(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new v(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let s=!f(this,Ri,"m",iu).call(this)&&n||this.baseURL,o=nl(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!Xo(i)||!Xo(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:r,...s})))}request(e,r=null){return new _t(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let s=await e,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:u}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(q(this).debug(`[${l}] sending request`,Ee({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),s.signal?.aborted)throw new B;let _=s.__security??{bearerAuth:!0},h=new AbortController,A=await this.fetchWithAuth(a,i,u,h,_).catch(Sn),I=Date.now();if(A instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new B;let k=kn(A)||/timed? ?out/i.test(String(A)+("cause"in A?String(A.cause):""));if(r)return q(this).info(`[${l}] connection ${k?"timed out":"failed"} - ${w}`),q(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${w})`,Ee({retryOfRequestLogID:n,url:a,durationMs:I-m,message:A.message})),this.retryRequest(s,r,n??l);throw q(this).info(`[${l}] connection ${k?"timed out":"failed"} - error; no more retries left`),q(this).debug(`[${l}] connection ${k?"timed out":"failed"} (error; no more retries left)`,Ee({retryOfRequestLogID:n,url:a,durationMs:I-m,message:A.message})),A instanceof ht||A instanceof En?A:k?new be:new Je({cause:A})}let E=[...A.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,k])=>", "+w+": "+JSON.stringify(k)).join(""),g=`[${l}${p}${E}] ${i.method} ${a} ${A.ok?"succeeded":"failed"} with status ${A.status} in ${I-m}ms`;if(!A.ok){if(A.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!s.__metadata?.hasStreamingBody&&!s.__metadata?.workloadIdentityTokenRefreshed)return await ti(A.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let w=await this.shouldRetry(A);if(r&&w){let U=`retrying, ${r} attempts remaining`;return await ti(A.body),q(this).info(`${g} - ${U}`),q(this).debug(`[${l}] response error (${U})`,Ee({retryOfRequestLogID:n,url:A.url,status:A.status,headers:A.headers,durationMs:I-m})),this.retryRequest(s,r,n??l,A.headers)}let k=w?"error; no more retries left":"error; not retryable";q(this).info(`${g} - ${k}`);let L=await A.text().catch(U=>Sn(U).message),R=il(L),j=R?void 0:L;throw q(this).debug(`[${l}] response error (${k})`,Ee({retryOfRequestLogID:n,url:A.url,status:A.status,headers:A.headers,message:j,durationMs:Date.now()-m})),this.makeStatusError(A.status,R,j,A.headers)}return q(this).info(g),q(this).debug(`[${l}] response start`,Ee({retryOfRequestLogID:n,url:A.url,status:A.status,headers:A.headers,durationMs:I-m})),{response:A,options:s,controller:h,requestLogID:l,retryOfRequestLogID:n,startTime:m}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Ln(this,n,e)}async fetchWithAuth(e,r,n,s,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let a=r.headers,u=a.get("Authorization");if(!u||u===`Bearer ${qm}`){let l=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,s)}async fetchWithTimeout(e,r,n,s){let{signal:o,method:i,...a}=r||{},u=this._makeAbort(s);o&&o.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),p=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,m={signal:s.signal,...p?{duplex:"half"}:{},method:"GET",...a};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let a=s?.get("retry-after");if(a&&!o){let u=parseFloat(a);Number.isNaN(u)?o=Date.parse(a)-Date.now():o=u*1e3}if(o===void 0){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,u)}return await xe(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:s,path:o,query:i,defaultBaseURL:a}=n,u=this.buildURL(o,i,a);"timeout"in n&&ol("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:p,isStreamingBody:m}=this.buildBody({options:n});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let _=await this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:_,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"},...p&&{body:p},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=x([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...pl(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=x([r]),s=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,o=!s&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||s?{bodyHeaders:void 0,body:e,isStreamingBody:!o}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:xs(e),isStreamingBody:!0}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...f(this,Vs,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};$i=P,Vs=new WeakMap,Ri=new WeakSet,iu=function(){return this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=$i;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=v;P.APIError=F;P.APIConnectionError=Je;P.APIConnectionTimeoutError=be;P.APIUserAbortError=B;P.NotFoundError=or;P.ConflictError=ir;P.RateLimitError=lr;P.BadRequestError=rr;P.AuthenticationError=nr;P.InternalServerError=ur;P.PermissionDeniedError=sr;P.UnprocessableEntityError=ar;P.InvalidWebhookSignatureError=Ie;P.toFile=jn;P.Completions=kt;P.Chat=Xe;P.Embeddings=Et;P.Files=Rt;P.Images=Dt;P.Audio=Ce;P.Moderations=zt;P.Models=jt;P.FineTuning=ge;P.Graders=at;P.VectorStores=ze;P.Webhooks=Bt;P.Beta=he;P.Batches=vt;P.Uploads=ut;P.Admin=et;P.Responses=De;P.Realtime=Le;P.Conversations=ot;P.Evals=it;P.Containers=st;P.Skills=je;P.Videos=Ft;function Hm(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 _e(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===be.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===B.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Hm(t)?e=Pa.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=On(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=On(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=On(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=On(t,"MODEL_NOT_FOUND"):e=t,e}var ye=t=>t();function Ue(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Jm(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 Li(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Zm="LC_AUTOGENERATED";function yn(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'."),Zm)}function Fe(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(!us.isInstance(t))throw new Error("Invalid generic chat message");return Jm(t);default:throw new Error(`Unknown message type: ${e}`)}}function au(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function Be(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:s,baseURL:o,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((n||i)&&s&&e)return`${s}/${e}`;if((n||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return o}function Di(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function lu(t){let e=ye(()=>{if(Di(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Di(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,n])=>typeof n=="string").map(([n,s])=>[n,s]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function uu(){let t=Ca();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Ke(t,e=!1,r="1.0.0"){let n=lu(t),s=uu(),o=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${o}/${r} (${s})${n["User-Agent"]}`:`${o}/${r} (${s})`}}function cu(t,e){let r;return vn(t)?r=zo(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Vm(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function pu(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(du(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
62
+ `)}function du(t,e){let r=[];for(let[n,s]of Object.entries(t.properties??{}))s.description&&e<2&&r.push(`// ${s.description}`),t.required?.includes(n)?r.push(`${n}: ${Gs(s,e)},`):r.push(`${n}?: ${Gs(s,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
63
+ `)}function Gs(t,e){if(Vm(t))return t.anyOf.map(r=>Gs(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["{",du(t,e+2),"}"].join(`
64
+ `);case"array":return t.items?`${Gs(t.items,e)}[]`:"any[]";default:return""}}function Ys(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 wn(t){return"type"in t&&t.type!=="function"}function mu(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 fu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Kt(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 Xs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function hu(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 gu(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 _u(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function yu(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 wu(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 Au(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 Iu=Symbol("Let zodToJsonSchema decide on which parser to use"),bu={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"},xu=t=>typeof t=="string"?{...bu,basePath:["#"],definitions:{},name:t}:{...bu,basePath:["#"],definitions:{},...t};var Yn=t=>"_def"in t?t._def:t;function vu(t){if(!t)return!0;for(let e in t)return!1;return!0}var Tu=t=>{let e=xu(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[Yn(s),{def:Yn(s),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ji(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function N(t,e,r,n,s){t[e]=r,ji(t,e,n,s)}function Cu(){return{}}function Pu(t,e){let r={type:"array"};return t.type?._def?.typeName!==M.ZodAny&&(r.items=O(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&N(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&N(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(N(r,"minItems",t.exactLength.value,t.exactLength.message,e),N(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Ou(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?N(r,"minimum",n.value,n.message,e):N(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),N(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?N(r,"maximum",n.value,n.message,e):N(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),N(r,"maximum",n.value,n.message,e));break;case"multipleOf":N(r,"multipleOf",n.value,n.message,e);break}return r}function ku(){return{type:"boolean"}}function Su(t,e){return O(t.type._def,e)}var Eu=(t,e)=>O(t.innerType._def,e);function zi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>zi(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Gm(t,e)}}var Gm=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":N(r,"minimum",n.value,n.message,e);break;case"max":N(r,"maximum",n.value,n.message,e);break}return r};function Mu(t,e){return{...O(t.innerType._def,e),default:t.defaultValue()}}function Ru(t,e,r){return e.effectStrategy==="input"?O(t.schema._def,e,r):{}}function $u(t){return{type:"string",enum:[...t.values]}}var Ym=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Nu(t,e){let r=[O(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),O(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(Ym(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...u}=o;i=u}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function Lu(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 Ui,Wt={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:()=>(Ui===void 0&&(Ui=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ui),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Qs(t,e){let r={type:"string"};function n(s){return e.patternStrategy==="escape"?Xm(s):s}if(t.checks)for(let s of t.checks)switch(s.kind){case"min":N(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,s.value):s.value,s.message,e);break;case"max":N(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":we(r,"email",s.message,e);break;case"format:idn-email":we(r,"idn-email",s.message,e);break;case"pattern:zod":Ae(r,Wt.email,s.message,e);break}break;case"url":we(r,"uri",s.message,e);break;case"uuid":we(r,"uuid",s.message,e);break;case"regex":Ae(r,s.regex,s.message,e);break;case"cuid":Ae(r,Wt.cuid,s.message,e);break;case"cuid2":Ae(r,Wt.cuid2,s.message,e);break;case"startsWith":Ae(r,RegExp(`^${n(s.value)}`),s.message,e);break;case"endsWith":Ae(r,RegExp(`${n(s.value)}$`),s.message,e);break;case"datetime":we(r,"date-time",s.message,e);break;case"date":we(r,"date",s.message,e);break;case"time":we(r,"time",s.message,e);break;case"duration":we(r,"duration",s.message,e);break;case"length":N(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,s.value):s.value,s.message,e),N(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,s.value):s.value,s.message,e);break;case"includes":{Ae(r,RegExp(n(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&we(r,"ipv4",s.message,e),s.version!=="v4"&&we(r,"ipv6",s.message,e);break}case"emoji":Ae(r,Wt.emoji,s.message,e);break;case"ulid":{Ae(r,Wt.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{we(r,"binary",s.message,e);break}case"contentEncoding:base64":{N(r,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{Ae(r,Wt.base64,s.message,e);break}}break}case"nanoid":Ae(r,Wt.nanoid,s.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Xm=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),we=(t,e,r,n)=>{t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):N(t,"format",e,r,n)},Ae=(t,e,r,n)=>{t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Du(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):N(t,"pattern",Du(e,n),r,n)},Du=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},s=n.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,u=!1;for(let l=0;l<s.length;l++){if(i){o+=s[l],i=!1;continue}if(n.i){if(a){if(s[l].match(/[a-z]/)){u?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),u=!1):s[l+1]==="-"&&s[l+2]?.match(/[a-z]/)?(o+=s[l],u=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
65
+ ]))`;continue}else if(s[l]==="$"){o+=`($|(?=[\r
66
+ ]))`;continue}}if(n.s&&s[l]==="."){o+=a?`${s[l]}\r
67
+ `:`[${s[l]}\r
68
+ ]`;continue}o+=s[l],s[l]==="\\"?i=!0:a&&s[l]==="]"?a=!1:!a&&s[l]==="["&&(a=!0)}try{let l=new RegExp(o)}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 o};function eo(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===M.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Qs(t.keyType._def,e)).reduce((s,[o,i])=>o==="type"?s:{...s,[o]:i},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===M.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function ju(t,e){if(e.mapStrategy==="record")return eo(t,e);let r=O(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function zu(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Uu(){return{not:{}}}function Fu(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ku(t,e){if(e.target==="openApi3")return Bu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Xn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Xn[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Bu(t,e)}var Bu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>O(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Wu(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Xn[t.innerType._def.typeName],nullable:!0}:{type:[Xn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=O(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function qu(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ji(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?N(r,"minimum",n.value,n.message,e):N(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),N(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?N(r,"maximum",n.value,n.message,e):N(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),N(r,"maximum",n.value,n.message,e));break;case"multipleOf":N(r,"multipleOf",n.value,n.message,e);break}return r}function Qm(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Hu(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[s,o])=>{if(o===void 0||o._def===void 0)return n;let i=[...e.currentPath,"properties",s],a=O(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return n;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[s]:a},required:o.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,s]}},{properties:{},required:[]}),additionalProperties:Qm(t,e)};return r.required.length||delete r.required,r}var Ju=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return O(t.innerType._def,{...e,currentPath:e.currentPath});let r=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var Zu=(t,e)=>{if(e.pipeStrategy==="input")return O(t.in._def,e);if(e.pipeStrategy==="output")return O(t.out._def,e);let r=O(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=O(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Vu(t,e){return O(t.type._def,e)}function Gu(t,e){let n={type:"array",uniqueItems:!0,items:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&N(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&N(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Yu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>O(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:O(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>O(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Xu(){return{not:{}}}function Qu(){return{}}var ec=(t,e)=>O(t.innerType._def,e);function O(t,e,r=!1){let n=e.seen.get(t);if(e.override){let i=e.override?.(t,e,n,r);if(i!==Iu)return i}if(n&&!r){let i=ef(n,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=rf(t,t.typeName,e,r);return o&&nf(t,e,o),s.jsonSchema=o,o}var ef=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:tf(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,s)=>e.currentPath[s]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},tf=(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("/")},rf=(t,e,r,n)=>{switch(e){case M.ZodString:return Qs(t,r);case M.ZodNumber:return qu(t,r);case M.ZodObject:return Hu(t,r);case M.ZodBigInt:return Ou(t,r);case M.ZodBoolean:return ku();case M.ZodDate:return zi(t,r);case M.ZodUndefined:return Xu();case M.ZodNull:return Fu(r);case M.ZodArray:return Pu(t,r);case M.ZodUnion:case M.ZodDiscriminatedUnion:return Ku(t,r);case M.ZodIntersection:return Nu(t,r);case M.ZodTuple:return Yu(t,r);case M.ZodRecord:return eo(t,r);case M.ZodLiteral:return Lu(t,r);case M.ZodEnum:return $u(t);case M.ZodNativeEnum:return zu(t);case M.ZodNullable:return Wu(t,r);case M.ZodOptional:return Ju(t,r);case M.ZodMap:return ju(t,r);case M.ZodSet:return Gu(t,r);case M.ZodLazy:return O(t.getter()._def,r);case M.ZodPromise:return Vu(t,r);case M.ZodNaN:case M.ZodNever:return Uu();case M.ZodEffects:return Ru(t,r,n);case M.ZodAny:return Cu();case M.ZodUnknown:return Qu();case M.ZodDefault:return Mu(t,r);case M.ZodBranded:return Su(t,r);case M.ZodReadonly:return ec(t,r);case M.ZodCatch:return Eu(t,r);case M.ZodPipeline:return Zu(t,r);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(s=>{})(e)}},nf=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Fi=(t,e)=>{let r=Tu(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=O(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(s.title=o);let i=(()=>{if(vu(r.definitions))return;let u={},l=new Set;for(let p=0;p<500;p++){let m=Object.entries(r.definitions).filter(([_])=>!l.has(_));if(m.length===0)break;for(let[_,h]of m)u[_]=O(Yn(h),{...r,currentPath:[...r.basePath,r.definitionPath,_]},!0)??{},l.add(_)}return u})(),a=n===void 0?i?{...s,[r.definitionPath]:i}:s:r.nameStrategy==="duplicate-ref"?{...s,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:s}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function tc(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 We(e,[],e)}function Bi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Bi(e))return!0;for(let e of t.anyOf??[])if(Bi(e))return!0;return!1}function We(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!qt(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(qt(n))for(let[_,h]of Object.entries(n))We(h,[...e,"$defs",_],r);let s=t.definitions;if(qt(s))for(let[_,h]of Object.entries(s))We(h,[...e,"definitions",_],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(qt(a)){for(let[_,h]of Object.entries(a))if(!Bi(h)&&!i.includes(_))throw new Error(`Zod field at \`${[...e,"properties",_].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([_,h])=>[_,We(h,[...e,"properties",_],r)]))}let u=t.items;qt(u)&&(t.items=We(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((_,h)=>We(_,[...e,"anyOf",String(h)],r)));let p=t.allOf;if(Array.isArray(p))if(p.length===1){let _=We(p[0],[...e,"allOf","0"],r);Object.assign(t,_),delete t.allOf}else t.allOf=p.map((_,h)=>We(_,[...e,"allOf",String(h)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&of(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let _=sf(r,m);if(typeof _=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!qt(_))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(_)}`);return Object.assign(t,{..._,...t}),delete t.$ref,We(t,e,r)}return t}function sf(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let s of r){if(!qt(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let o=n[s];if(o===void 0)throw new Error(`Key ${s} not found while resolving ${e}`);n=o}return n}function qt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function of(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function af(t,e){return Fi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function lf(t){return tc($a(t,{target:"draft-7"}))}function uf(t){return"_zod"in t}function rc(t,e,r){return $l({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:uf(t)?lf(t):af(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var nc=["jsonSchema","functionCalling","jsonMode"];function sc(t,e){if(typeof e<"u"&&!nc.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${nc.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 cf(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function oc(t,e,r){if(Na(t))return rc(t,e,r);if(ds(t))return cf({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:ft(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Ma(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function ic(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var ac={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function An(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Ht=class extends _s{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??me("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??me("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.4.7")}_getReasoningParams(t){if(!Ue(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)?oc(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=Be({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Ke(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Kt(t)?Au(t.metadata.customTool):hs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:cu(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if(wn(n)||Kt(n))return n;if(mu(n))return n.extras.providerToolDefinition;let s=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return vn(n)&&n.extras?.defer_loading===!0?{...s,defer_loading:!0}:s}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let s=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens(Fe(o))]),u=o.name!==void 0?n+await this.getNumTokens(o.name):0,l=i+r+a+u,p=o;if(p._getType()==="function"&&(l-=2),p.additional_kwargs?.function_call&&(l+=3),p?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(p.additional_kwargs.function_call?.name)),p.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(p.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(p.additional_kwargs.function_call)),l+=await this.getNumTokens(p.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:s}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let s=pu(e);n+=await this.getNumTokens(s),n+=9}return e&&t.find(s=>s._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(s){throw _e(s)}})}get profile(){return ac[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:s,name:o,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=sc(this.model,e?.method);if(a==="jsonMode"){n=Do(s);let u=ft(s);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...u}}})}else if(a==="jsonSchema"){let u=ft(s),l={name:o??"extract",description:No(u),schema:mt(s)?s: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(s)||ps(s)){let p=Do(s);n=fs.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:p.invoke(m.content))}else n=new ja}else{let u=o??"extract",l=ft(s),p;mt(s)||ps(s)?p={name:u,description:l.description,parameters:l}:typeof s.name=="string"&&typeof s.parameters=="object"&&s.parameters!=null?(p=s,u=s.name):(u=s.title??u,p={name:u,description:s.description??"",parameters:s}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:p}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=za(s,u)}return Ua(r,n,i)}};var to={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=Eo({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=So(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=So(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=Eo({dataUrl:t.url}),r=yn(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=yn(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`)}},Ki=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,s=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let l of n??[])try{o.push(gs(l,{returnId:!0}))}catch(p){i.push(Yt(l,p.message))}let a={function_call:t.function_call,tool_calls:n};r!==void 0&&(a.__raw_response=e),s!==void 0&&(a.reasoning_content=s);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new D({content:ic(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:u,id:e.id})}default:return new us(t.content||"",t.role??"unknown")}},Wi=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let s=t.role??n,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(s==="user")return new $o({content:o,response_metadata:a});if(s==="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 qe({content:o,tool_call_chunks:u,additional_kwargs:i,id:e.id,response_metadata:a})}else return s==="system"?new cs({content:o,response_metadata:a}):s==="developer"?new cs({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new ka({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):s==="tool"?new Mo({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Oa({content:o,role:s,response_metadata:a})},lc=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=Sa(()=>{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=yn(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}}}},uc=({message:t,model:e})=>{let r=Fe(t);if(r==="system"&&Ue(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(s=>s.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(s=>s.type==="text")};if(r==="assistant"){let s={role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};return D.isInstance(t)&&t.tool_calls?.length?s.tool_calls=t.tool_calls.map(Lo):t.additional_kwargs.tool_calls!=null&&(s.tool_calls=t.additional_kwargs.tool_calls),s}else{if(r==="tool"&&W.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(s=>s.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(s=>s.type==="text").join("")}}function*n(s){for(let o of s){o.type==="text"&&(yield{type:"text",text:o.text});let i=lc(o);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Qn=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return uc({message:r});let n=Fe(r);n==="system"&&Ue(e)&&(n="developer");let s=typeof r.content=="string"?r.content:r.content.flatMap(i=>as(i)?ls(i,to):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),o={role:n,content:s};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),D.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(Lo):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),W.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var ro=class extends Ht{constructor(t,e){super(An(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let s={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:Ys(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(s.prediction=t.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),t?.service_tier!==void 0&&(s.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(s.reasoning_effort=o.effort),Ue(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},s=this.invocationParams(e),o=Qn({messages:t,model:this.model});if(s.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let h of i){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let A=h.generationInfo?.completion??0;a[A]===void 0?a[A]=h:a[A]=a[A].concat(h)}let u=Object.entries(a).sort(([h],[A])=>parseInt(h,10)-parseInt(A,10)).map(([h,A])=>A),{functions:l,function_call:p}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,p),_=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=_,n.total_tokens=m+_,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let i=await this.completionWithRetry({...s,stream:!1,messages:o},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:u,total_tokens:l,prompt_tokens_details:p,completion_tokens_details:m}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(p?.audio_tokens!==null||p?.cached_tokens!==null)&&(n.input_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.cached_tokens!==null&&{cache_read:p?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let _=[];for(let h of i?.choices??[]){let A={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},i)};A.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},Ro(A.message)&&(A.message.usage_metadata=n),A.message=new D(Object.fromEntries(Object.entries(A.message).filter(([I])=>!I.startsWith("lc_")))),_.push(A)}return{generations:_,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let n=Qn({messages:t,model:this.model}),s={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},o,i=await this.completionWithRetry(s,e),a;for await(let u of i){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(a=u.usage),!l)continue;let{delta:p}=l;if(!p)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(p,u,o);o=p.role??o;let _={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let h={..._};l.finish_reason!=null&&(h.finish_reason=l.finish_reason,h.system_fingerprint=u.system_fingerprint,h.model_name=u.model,h.service_tier=u.service_tier),this.logprobs&&(h.logprobs=l.logprobs);let A=new xn({message:m,text:m.content,generationInfo:h});yield A,await r?.handleLLMNewToken(A.text??"",_,void 0,void 0,void 0,{chunk:A})}if(a){let u={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},l={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},p=new xn({message:new qe({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield p,await r?.handleLLMNewToken(p.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:p})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(s){throw _e(s)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Wi({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Ki({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var no="__openai_function_call_ids__",so="__openai_custom_tool_call_ids__";function gc(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 df(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 qi=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}},oo=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],s=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let u={...a};return delete u.parsed_arguments,u}return a}),o={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(i.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(gc),...a.phase!==null?{phase:a.phase}:{}}):u.type==="refusal"?(i.refusal=u.refusal,[]):u));else if(a.type==="function_call"){let u={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(gs(u,{returnId:!0}))}catch(l){let p;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(p=l.message),n.push(Yt(u,p))}i[no]??={},a.id&&(i[no][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let u=a.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(a.type==="custom_tool_call"){let u=hu(a);u?(r.push(u),i[so]??={},a.id&&a.call_id&&(i[so][a.call_id]=a.id)):n.push(Yt(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let u=gu(a);u?r.push(u):n.push(Yt(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new D({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:qi(t.usage),additional_kwargs:i,response_metadata:o})},_c=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let s=r[r.length-1];return s.index===n.index?s.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},Hi=t=>{let e=[],r={},n,s=[],o={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[gc(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")s.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[no]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")s.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[so]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")s.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let u=oo(t.response);if(n=qi(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{i.parsed??=JSON.parse(u.text)}catch{}for(let[l,p]of Object.entries(t.response))l!=="id"&&(l==="output"?o[l]=u.response_metadata.output:o[l]=p)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")s.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.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.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((p,m)=>({...p,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(p=>p.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new xn({text:e.map(u=>u.text).join(""),message:new qe({id:a,content:e,tool_call_chunks:s,usage_metadata:n,additional_kwargs:i,response_metadata:o}),generationInfo:r})},yc=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=ye(()=>{try{let g=Fe(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),s,o=new Set,i=new Set,a=new Map,u=new Map;function*l(){if(!s)return;let g=s.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield s),s=void 0}let p=(g,w)=>{s||(s={type:"message",role:n,content:[],...w?{phase:w}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[{type:"input_text",text:s.content},...g]:[...g]:s.content.push(...g)},m=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},_=g=>{let w=ye(()=>{let k=g.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(g.fileId)return{type:"input_image",detail:w,file_id:g.fileId};if(g.url)return{type:"input_image",detail:w,image_url:g.url};if(g.data){let k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:w,image_url:`data:${g.mimeType??"image/png"};base64,${k}`}}},h=g=>{if(g.fileId){let w=Li(g);return{type:"input_file",file_id:g.fileId,...w?{filename:w}:{}}}if(g.url){let w=Li(g);return{...w?{filename:w}:{},type:"input_file",file_url:g.url}}if(g.data){let w=yn(g),k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${k}`,filename:w}}},A=g=>{let w=ye(()=>{if(Array.isArray(g.summary)){let R=g.summary?.map(j=>j?.text).filter(j=>typeof j=="string")??[];if(R.length>0)return R}return g.reasoning?[g.reasoning]:[]}),k=w.length>0?w.map(R=>({type:"summary_text",text:R})):[{type:"summary_text",text:""}],L={type:"reasoning",id:g.id??"",summary:k};return g.reasoning&&(L.content=[{type:"reasoning_text",text:g.reasoning}]),L},I=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:m(g.args)}),E=g=>{let w=m(g.output),k=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:w,...k?{status:k}:{}}};for(let g of t.contentBlocks)if(g.type==="text"){let w=ye(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});p([{type:"input_text",text:g.text}],w)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield A(g);else if(g.type==="tool_call"){yield*l();let w=g.id??"";w&&(o.add(w),a.delete(w)),yield I(g)}else if(g.type==="tool_call_chunk"){if(g.id){let w=a.get(g.id)??{name:g.name,args:[]};g.name&&(w.name=g.name),g.args&&w.args.push(g.args),a.set(g.id,w)}}else if(g.type==="server_tool_call"){yield*l();let w=g.id??"";w&&(i.add(w),u.delete(w)),yield I(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let w=u.get(g.id)??{name:g.name,args:[]};g.name&&(w.name=g.name),g.args&&w.args.push(g.args),u.set(g.id,w)}}else if(g.type==="server_tool_call_result")yield*l(),yield E(g);else if(g.type!=="audio")if(g.type==="file"){let w=h(g);w&&p([w])}else if(g.type==="image"){let w=_(g);w&&p([w])}else if(g.type==="video"){let w=h(g);w&&p([w])}else g.type==="text-plain"?g.text&&p([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(let[g,w]of a){if(!g||o.has(g))continue;let k=w.args.join("");!w.name&&!k||(yield{type:"function_call",call_id:g,name:w.name??"",arguments:k})}for(let[g,w]of u){if(!g||i.has(g))continue;let k=w.args.join("");!w.name&&!k||(yield{type:"function_call",call_id:g,name:w.name??"",arguments:k})}}return Array.from(r())},io=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let s=n.response_metadata;if(s?.output_version==="v1")return yc(n);let o=n.additional_kwargs,i=Fe(n);if(i==="system"&&Ue(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=n;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(_=>_.type==="input_image");if(l)return l;let p=a.content.find(_=>_.type==="computer_screenshot");if(p)return p;let m=a.content.find(_=>_.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let u=Array.isArray(a.content)&&a.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:u?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&s?.output!=null&&Array.isArray(s?.output)&&s?.output.length>0&&s?.output.every(I=>"type"in I))return s?.output;let a=[],u=o?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let I=_c(u);a.push(I)}let{content:p}=n;if(o?.refusal&&(typeof p=="string"&&(p=[{type:"output_text",text:p,annotations:[]}]),p=[...p,{type:"refusal",refusal:o.refusal}]),typeof p=="string"||p.length>0){let I={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:ye(()=>typeof p=="string"?p:p.flatMap(E=>{if(E.type==="text"){let g=E;return{type:"output_text",text:g.text,annotations:(g.annotations??[]).map(df)}}return E.type==="output_text"||E.type==="refusal"?E:[]})),phase:ye(()=>{if(Array.isArray(p))return p.find(E=>"phase"in E&&typeof E.phase=="string")?.phase})};a.push(I)}let m=o?.[no],_=o?.[so];D.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(I=>yu(I,_)?{type:"custom_tool_call",id:"call_id"in I&&typeof I.call_id=="string"?I.call_id:_?.[I.id??""]??"",call_id:I.id??"",input:I.args.input,name:I.name}:_u(I)?{type:"computer_call",id:I.call_id,call_id:I.id??"",action:I.args.action}:{type:"function_call",name:I.name,arguments:JSON.stringify(I.args),call_id:I.id,...e?{}:{id:m?.[I.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(I=>({type:"function_call",name:I.function.name,call_id:I.id,arguments:I.function.arguments,...e?{}:{id:m?.[I.id]}})));let h=s?.output?.length?s?.output:o.tool_outputs,A=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(h!=null){let I=h?.filter(E=>A.includes(E.type));I.length>0&&a.push(...I)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],u=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),as(l)?ls(l,to):l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:ye(()=>{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:ye(()=>{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&&a.push({type:"message",role:i,content:u}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var ao=class extends Ht{constructor(t,e){super(An(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:fu(t?.tool_choice)?t?.tool_choice:(()=>{let s=Ys(t?.tool_choice);if(typeof s=="object"&&"type"in s){if(s.type==="function")return{type:"function",name:s.function.name};if(s.type==="allowed_tools")return{type:"allowed_tools",mode:s.allowed_tools.mode,tools:s.allowed_tools.tools};if(s.type==="custom")return{type:"custom",name:s.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let s=this._getResponseFormat(t?.response_format);return s?.type==="json_schema"?s.json_schema.schema!=null?{format:{type:"json_schema",schema:s.json_schema.schema,description:s.json_schema.description,name:s.json_schema.name,strict:s.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:s,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let s=this._streamResponseChunks(t,e,r),o;for await(let i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let s=await this.completionWithRetry({input:io({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:oo(s)}],llmOutput:{id:s.id,estimatedTokenUsage:s.usage?{promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:io({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let s of n){if(e.signal?.aborted)return;let o=Hi(s);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw _e(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(wn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(Kt(n)){let s=n.metadata.customTool;r.push({type:"custom",name:s.name,description:s.description,format:s.format})}else if(hs(n)){let s={};for(let[o,i]of Object.entries(n))o!=="type"&&o!=="function"&&(s[o]=i);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...s})}else Xs(n)&&r.push(wu(n));return r}};var lo=class wc extends Ht{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=An(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new ao(n),this.completions=n?.completions??new ro(n)}_useResponsesApi(e){let r=e?.tools?.some(wn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,s=e?.tools?.some(Xs)||e?.tools?.some(Kt);return this.useResponsesApi||r||n||s||au(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new wc(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var uo=class extends La{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??me("OPENAI_API_KEY");this.organization=e?.configuration?.organization??me("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=jo(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),n=await Promise.all(r),s=[];for(let o=0;o<n.length;o+=1){let i=e[o],{data:a}=n[o];for(let u=0;u<i.length;u+=1)s.push(a[u].embedding)}return s}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=Be({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=Ke(n.defaultHeaders),this.client=new P(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw _e(r)}})}};var gf=b.object({type:b.literal("screenshot")}),_f=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),yf=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),wf=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),Af=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),bf=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),If=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),xf=b.object({type:b.literal("type"),text:b.string()}),vf=b.object({type:b.literal("wait"),duration:b.number().optional()}),Tf=b.union([gf,_f,yf,wf,Af,bf,If,xf,vf]),hD=b.object({action:Tf});var Cf=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),wD=b.union([Cf]);var xD=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var Pf=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),Of=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),kf=b.object({type:b.literal("delete_file"),path:b.string()}),PD=b.union([Pf,Of,kf]);var bc={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Vi={default:"text-embedding-ada-002"},Ji=new Map,co=null,Ef=()=>{let t=Zi.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},Ic=async t=>{let e=Ef();Ji.size===0&&(co||(co=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(s=>Ji.set(s.name,s))}catch(n){throw co=null,n}})()),await co);let r=Ji.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Mf=async(t="default")=>await Ic(bc[t]),Rf=async(t="default")=>await Ic(Vi[t]);var ts=(t,e)=>e,xc=(t,e)=>({...t,...e}),vc=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let s=n.split(`
69
+
70
+ `);return s[s.length-1]?.trim()===r?t:`${t}
71
+
72
+ ${r}`},Tc=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),po=()=>({agentExecutionContext:z({reducer:xc,default:Tc}),outputMessage:z({reducer:vc,default:()=>""}),summary:z({reducer:ts,default:()=>""}),status:z({reducer:ts})});var Xj=z.Root({agentExecutionContext:z({default:Tc,reducer:xc}),currentIntent:z({default:()=>"none",reducer:ts}),lastExecutedAgent:z({default:()=>"",reducer:ts}),requiresFollowUp:z({default:()=>!0,reducer:ts}),stepCount:z({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:z({default:()=>"",reducer:vc})}),ct=async(t,e)=>{await qa("trace_message",t,e)};var Cc=t=>async(e,r)=>{let n=new Headers(r?.headers);return n.delete("Authorization"),n.delete("api-key"),t&&t.length>0&&(n.set("X-Esri-Authorization",`Bearer ${t}`),n.set("X-Esri-Request-Source","MapsSDK")),await fetch(e,{...r,headers:n})},Pc=async(t="default",e=0)=>{let r=Zi.getDefault(),n=await Ac.getCredential(`${r.url}/sharing`),s=bc[t],o=await Mf(t);return new lo({modelName:s,apiKey:"dummy-key",...t!=="default"&&{temperature:e},configuration:{baseURL:o,fetch:Cc(n.token)}})},$f=async(t="default")=>{let e=Zi.getDefault(),r=await Ac.getCredential(`${e.url}/sharing`),n=Vi[t],s=await Rf(t);return new uo({modelName:n,apiKey:"dummy-key",configuration:{baseURL:s,fetch:Cc(r.token)},batchSize:2048,maxConcurrency:10})},Nf=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(Nf);var Oc=async t=>{try{return await(await $f()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var Lf="0.1",es=1536,Df="openai",jf=Vi.default,zf=`Name: {name}
73
+ Title: {title}
74
+ Description: {description}`,Uf=`Name: {name}
75
+ Alias: {alias}
76
+ Description: {description}`,Qj=b.object({schemaVersion:b.literal(Lf),modified:b.number().int().nonnegative(),embeddings:b.object({modelProvider:b.literal(Df),model:b.literal(jf),dimensions:b.literal(es),templates:b.object({layer:b.string().default(zf),field:b.string().default(Uf)})}),layers:b.array(b.object({id:b.string().min(1),name:b.string().min(1),title:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(es,{message:`Layer vector must be exactly ${es} dimensions`}),fields:b.array(b.object({name:b.string().min(1),alias:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(es,{message:`Field vector must be exactly ${es} dimensions`})}))})).default([])});var kc=(t,e)=>{let r=Fa.fromTemplate(t);return Ba.fromMessages([r,...e])},Ff=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:s}=t,o=kc(e,s??[]),i=await Pc(r,n);return o.pipe(i)},Sc=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:s,inputVariables:o}=t,i=await(await Ff({promptText:e,modelTier:r,temperature:n,messages:s})).invoke(o??{});if(typeof i=="string")return i;let a=i.content;return typeof a=="string"?a:JSON.stringify(a)},rs=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:s,inputVariables:o,schema:i}=t,a=kc(e,s??[]),u=(await Pc(r,n)).withStructuredOutput(i);return await a.pipe(u).invoke(o??{})};var Bf=T.object({name:T.string(),description:T.string(),valueType:T.string(),alias:T.string()}),ez=T.object({fields:T.array(Bf)});var tz=T.object({title:T.string(),description:T.string(),name:T.string().nullable()});var Ec=(t,e)=>{if(t.length!==e.length)throw new Error("Vectors must be the same length");let r=0,n=0,s=0;for(let a=0;a<t.length;++a){let u=t[a],l=e[a];r+=u*l,n+=u*u,s+=l*l}let o=Math.sqrt(n*s);if(o===0)return 0;let i=r/o;return Math.max(-1,Math.min(1,i))};var Gi={};ca(Gi,{JsonPatchError:()=>K,_areEquals:()=>os,applyOperation:()=>Jt,applyPatch:()=>In,applyReducer:()=>Jf,deepClone:()=>qf,getValueByPointer:()=>_o,validate:()=>Rc,validator:()=>yo});var Kf=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)s.hasOwnProperty(o)&&(n[o]=s[o])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),Wf=Object.prototype.hasOwnProperty;function fo(t,e){return Wf.call(t,e)}function ho(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var s in t)fo(t,s)&&n.push(s);return n}function ne(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function go(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function ke(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function ns(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function mo(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(mo(t[e]))return!0}else if(typeof t=="object"){for(var n=ho(t),s=n.length,o=0;o<s;o++)if(mo(t[n[o]]))return!0}}return!1}function Mc(t,e){var r=[t];for(var n in e){var s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&r.push(n+": "+s)}return r.join(`
77
+ `)}var ss=(function(t){Kf(e,t);function e(r,n,s,o,i){var a=this.constructor,u=t.call(this,Mc(r,{name:n,index:s,operation:o,tree:i}))||this;return u.name=n,u.index=s,u.operation=o,u.tree=i,Object.setPrototypeOf(u,a.prototype),u.message=Mc(r,{name:n,index:s,operation:o,tree:i}),u}return e})(Error);var K=ss,qf=ne,bn={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=_o(r,this.path);n&&(n=ne(n));var s=Jt(r,{op:"remove",path:this.from}).removed;return Jt(r,{op:"add",path:this.path,value:s}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=_o(r,this.from);return Jt(r,{op:"add",path:this.path,value:ne(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:os(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},Hf={add:function(t,e,r){return go(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:bn.move,copy:bn.copy,test:bn.test,_get:bn._get};function _o(t,e){if(e=="")return t;var r={op:"_get",path:e};return Jt(t,r),r.value}function Jt(t,e,r,n,s,o){if(r===void 0&&(r=!1),n===void 0&&(n=!0),s===void 0&&(s=!0),o===void 0&&(o=0),r&&(typeof r=="function"?r(e,0,t,e.path):yo(e,0)),e.path===""){var i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=_o(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=os(t,e.value),i.test===!1)throw new K("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new K("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return i}}else{n||(t=ne(t));var a=e.path||"",u=a.split("/"),l=t,p=1,m=u.length,_=void 0,h=void 0,A=void 0;for(typeof r=="function"?A=r:A=yo;;){if(h=u[p],h&&h.indexOf("~")!=-1&&(h=ns(h)),s&&(h=="__proto__"||h=="prototype"&&p>0&&u[p-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&_===void 0&&(l[h]===void 0?_=u.slice(0,p).join("/"):p==m-1&&(_=e.path),_!==void 0&&A(e,0,t,_)),p++,Array.isArray(l)){if(h==="-")h=l.length;else{if(r&&!go(h))throw new K("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,t);go(h)&&(h=~~h)}if(p>=m){if(r&&e.op==="add"&&h>l.length)throw new K("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var i=Hf[e.op].call(e,l,h,t);if(i.test===!1)throw new K("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return i}}else if(p>=m){var i=bn[e.op].call(e,l,h,t);if(i.test===!1)throw new K("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return i}if(l=l[h],r&&p<m&&(!l||typeof l!="object"))throw new K("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function In(t,e,r,n,s){if(n===void 0&&(n=!0),s===void 0&&(s=!0),r&&!Array.isArray(e))throw new K("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=ne(t));for(var o=new Array(e.length),i=0,a=e.length;i<a;i++)o[i]=Jt(t,e[i],r,!0,s,i),t=o[i].newDocument;return o.newDocument=t,o}function Jf(t,e,r){var n=Jt(t,e);if(n.test===!1)throw new K("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function yo(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new K("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(bn[t.op]){if(typeof t.path!="string")throw new K("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new K('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new K("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new K("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&mo(t.value))throw new K("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var s=t.path.split("/").length,o=n.split("/").length;if(s!==o+1&&s!==o)throw new K("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new K("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},a=Rc([i],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new K("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new K("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Rc(t,e,r){try{if(!Array.isArray(t))throw new K("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)In(ne(e),ne(t),r||!0);else{r=r||yo;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(s){if(s instanceof K)return s;throw s}}function os(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),s,o,i;if(r&&n){if(o=t.length,o!=e.length)return!1;for(s=o;s--!==0;)if(!os(t[s],e[s]))return!1;return!0}if(r!=n)return!1;var a=Object.keys(t);if(o=a.length,o!==Object.keys(e).length)return!1;for(s=o;s--!==0;)if(!e.hasOwnProperty(a[s]))return!1;for(s=o;s--!==0;)if(i=a[s],!os(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var ea={};ca(ea,{compare:()=>th,generate:()=>Yi,observe:()=>eh,unobserve:()=>Qf});var Xi=new WeakMap,Zf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Vf=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function Gf(t){return Xi.get(t)}function Yf(t,e){return t.observers.get(e)}function Xf(t,e){t.observers.delete(e.callback)}function Qf(t,e){e.unobserve()}function eh(t,e){var r=[],n,s=Gf(t);if(!s)s=new Zf(t),Xi.set(t,s);else{var o=Yf(s,e);n=o&&o.observer}if(n)return n;if(n={},s.value=ne(t),e){n.callback=e,n.next=null;var i=function(){Yi(n)},a=function(){clearTimeout(n.next),n.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return n.patches=r,n.object=t,n.unobserve=function(){Yi(n),clearTimeout(n.next),Xf(s,n),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},s.observers.set(e,new Vf(e,n)),n}function Yi(t,e){e===void 0&&(e=!1);var r=Xi.get(t.object);Qi(r.value,t.object,t.patches,"",e),t.patches.length&&In(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function Qi(t,e,r,n,s){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=ho(e),i=ho(t),a=!1,u=!1,l=i.length-1;l>=0;l--){var p=i[l],m=t[p];if(fo(e,p)&&!(e[p]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var _=e[p];typeof m=="object"&&m!=null&&typeof _=="object"&&_!=null&&Array.isArray(m)===Array.isArray(_)?Qi(m,_,r,n+"/"+ke(p),s):m!==_&&(a=!0,s&&r.push({op:"test",path:n+"/"+ke(p),value:ne(m)}),r.push({op:"replace",path:n+"/"+ke(p),value:ne(_)}))}else Array.isArray(t)===Array.isArray(e)?(s&&r.push({op:"test",path:n+"/"+ke(p),value:ne(m)}),r.push({op:"remove",path:n+"/"+ke(p)}),u=!0):(s&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),a=!0)}if(!(!u&&o.length==i.length))for(var l=0;l<o.length;l++){var p=o[l];!fo(t,p)&&e[p]!==void 0&&r.push({op:"add",path:n+"/"+ke(p),value:ne(e[p])})}}}function th(t,e,r){r===void 0&&(r=!1);var n=[];return Qi(t,e,n,"",r),n}var lz=Object.assign({},Gi,ea,{JsonPatchError:ss,deepClone:ne,escapePathComponent:ke,unescapePathComponent:ns});var sh=pa`:host{display:block;height:100%}.margin-lg{margin:var(--calcite-spacing-lg)}.display-flex-row{display:flex;flex-direction:row}.assistant-split-container{display:flex;width:100%;height:calc(100vh - 78px);overflow:hidden;border-radius:10px}.assistant-panel{display:flex;flex-direction:column;height:100%;border:1px solid var(--calcite-color-surface-3);background-color:var(--calcite-color-surface-2);overflow:hidden}.chat-panel{min-width:320px}.builder-panel{min-width:320px;max-width:100%;border-left:1px solid var(--calcite-color-surface-3)}.panel-actions{display:flex;gap:8px;padding:6px;align-items:center}.builder-header,.builder-footer{padding:10px;background:var(--calcite-color-surface-1);border-bottom:1px solid var(--calcite-color-surface-3)}.builder-content{flex:1;overflow:auto;padding:12px}.builder-content pre{white-space:pre-wrap;word-wrap:break-word;max-height:100%;overflow:auto}.builder-actions{display:flex;gap:6px;align-items:center}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-surface-4);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-surface-1);border-radius:10px;padding:10px}.chat-panel{--calcite-color-focus: var(--calcite-color-brand);--calcite-panel-border-color: var(--calcite-color-border-2);--calcite-internal-panel-header-vertical-padding: 0px;--calcite-panel-header-content-space: 0px;border:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);height:100%}.header-content{display:flex;align-items:center;gap:var(--calcite-spacing-sm);height:65px;box-sizing:border-box;padding-inline-start:var(--calcite-space-2xl)}.header-title{font-size:var(--calcite-font-size-md);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-text-1)}.beta-chip{--calcite-chip-corner-radius: var(--calcite-corner-radius-half)}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button,.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-surface-1, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-surface-3);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-surface-4);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-surface-4)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;align-items:center;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-surface-1)}#closeAssistantButton{--calcite-action-text-color: var(--calcite-color-text-1)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-surface-1)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;async function pt(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
78
+ Available prompts:
79
+ ${Object.keys(t).join(`
80
+ `)}`);return await r[1]()}function sa(t){return t?.configurable?.context?.translations}function Lc(t){if(typeof window>"u"||t.length<=1)return;let e=t.map(n=>n.solution.id),r=t.map(n=>n.solution.title);window.dispatchEvent(new CustomEvent("searchTermSet",{detail:{scope:"all-solutions",searchTerm:""}})),window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant",{detail:{solutionIds:e,solutionTitles:r},bubbles:!0,composed:!0})),window.dispatchEvent(new CustomEvent("navTabSelected",{detail:{tabType:"all-solutions"}}))}function Dc(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var jc=Object.assign({"./prompts/solutions_assistant_description.md":()=>import("./JQLLXM7G.js").then(t=>t.default),"./prompts/solutions_assistant_prompts.md":()=>import("./JMO7ZFWL.js").then(t=>t.default)}),zc=z.Root({...po()}),oh=async(t,e)=>{let r=sa(e);await ct({text:r?.executingSolutionsAssistantAgent||"Preparing a response..."},e);let n=await pt(jc,"solutions_assistant_prompts"),s=t.agentExecutionContext.messages.slice(-11),o=await Sc({promptText:n,modelTier:"fast",temperature:0,messages:s}),i=e?.configurable?.context?.clearSuggestedPrompts;i&&i();let a=new CustomEvent("assistantProcessing",{detail:!1});return window.dispatchEvent(a),{outputMessage:o,summary:o,status:"success"}},ih=()=>new Xt(zc).addNode("assistantLLM",oh).addEdge(Gt,"assistantLLM").addEdge("assistantLLM",Se),ah=await pt(jc,"solutions_assistant_description"),lh={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:ah,createGraph:ih,workspace:zc},Uc=t=>{if(t&&Array.isArray(t.id)&&t.id.length>0)return t.id[t.id.length-1].replace("Message","").toLowerCase();if(t&&typeof t._getType=="function")try{return t._getType()}catch{return"human"}return"human"},uh=t=>{let e=Uc(t);if(t&&t.kwargs)return{role:e,...t.kwargs};if(t&&typeof t=="object"){let r={role:e,content:typeof t.content=="string"?t.content:String(t.content||"")};return t.id&&(r.id=t.id),t.name&&(r.name=t.name),t.additional_kwargs&&(r.additional_kwargs=t.additional_kwargs),t.response_metadata&&(r.response_metadata=t.response_metadata),r}return{role:"human",content:String(t)}},ch=t=>Uc(t)==="human",ph=(t,e=3)=>t.filter(r=>ch(r)).slice(-e).map(uh),dh=(t,e=" ")=>ph(t).map(r=>r.content).join(e).trim(),mh={understandingRequest:"Understanding your request...",selectTemplatePrompt:"This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.",searchingExistingSolutions:"Searching for existing solutions...",existingSolutionMatch:"I found an existing solution that closely matches your use case and may already meet your needs: {{solutionMatch}}. Do you want to continue building your solution?",creatingDesign:"Generating solution design...",updatingDesign:"Updating solution design...",applyChangeFailed:"I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.",createDesignFailed:"I wasn't able to create a solution design from that request. Please try rephrasing and try again.",discardMessage:"Are you sure you want to discard your solution?",discardForNewSolution:"I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?"},fh={builderMessages:mh},hh=new Set(["add","all","alter","and","any","as","asc","backup","between","by","case","check","column","constraint","create","database","date","default","delete","desc","distinct","drop","exec","exists","foreign","from","full","group","having","in","index","inner","insert","into","is","join","key","left","like","limit","not","null","on","or","order","outer","primary","procedure","right","rownum","select","set","table","top","truncate","union","unique","update","values","view","where"]),Io=class{constructor(e,r,n=!0){this.isValid=!0,this.issues=[],this.response=e,this.template=r,this.newDesign=n,this.validate()}validate(){this.compareModels(),this.validateResponse()}compareModels(){this.compareStrings(),this.compareItems(),this.compareFeatureLayers()}compareStrings(){let e=new Set(this.template.solution.strings.map(n=>n.key)),r=new Set(this.response.solution.strings.map(n=>n.key));(e.size!==r.size||[...e].some(n=>!r.has(n)))&&this.logIssue("String keys in llm response do not match the template.");for(let n of this.response.solution.strings)n.value||this.logIssue(`String key '${n.key}' has no value.`)}compareItems(){let e=new Set(this.template.items.map(n=>n.id)),r=new Set(this.response.items.map(n=>n.id));(e.size!==r.size||[...e].some(n=>!r.has(n)))&&this.logIssue("Item ids in llm response do not match the template.")}compareFeatureLayers(){let e=this.template.featureLayer,r=this.response.featureLayer;if(e.itemId!==r.itemId){this.logIssue(`Feature Layer itemId '${r.itemId}' does not match template '${e.itemId}'.`);return}if(!e.addLayers){let n=new Set(e.layers.map(o=>o.id)),s=new Set(r.layers.map(o=>o.id));(n.size!==s.size||[...n].some(o=>!s.has(o)))&&this.logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`)}}validateResponse(){let e=this.template.featureLayer.layers;this.response.featureLayer.layers.length||this.logIssue("Feature layer item must contain at least one layer.");let r=this.response.featureLayer.layers.map(n=>n.name.toLowerCase());r.length!==new Set(r).size&&this.logIssue("Layer names must be unique (case-insensitive).");for(let n of this.response.featureLayer.layers){this.validateLayer(n);let s=e.find(o=>o.id===n.id);s&&this.validateRequiredFields(n,s)}}validateRequiredFields(e,r){let n=new Set(e.requiredFields.map(s=>s.name));for(let s of r.requiredFields)n.has(s.name)||this.logIssue(`Layer '${e.name}' is missing required field '${s.name}'.`)}validateLayer(e){let r=new Set(["objectid","globalid","created_date","created_user","last_edited_date","last_edited_user"]),n=e.systemFields??[];if(n.length){let o=new Set(n.map(i=>i.name));(o.size!==r.size||[...r].some(i=>!o.has(i)))&&this.logIssue(`Layer '${e.name}' has invalid system fields: ${JSON.stringify([...o])}.`)}let s=[...e.customFields,...e.requiredFields,...n].map(o=>o.name);s.length!==new Set(s).size&&this.logIssue(`Layer '${e.name}' has duplicate fields: ${JSON.stringify(s)}.`);for(let o of[...e.customFields,...e.requiredFields,...n])this.validateField(o)}validateField(e){if(e.alias||this.logIssue(`Field '${e.name}' has no display name (alias).`),/^[A-Za-z]/u.test(e.name)||this.logIssue(`Field '${e.name}' does not start with a letter.`),/^[A-Za-z][A-Za-z0-9_]*$/u.test(e.name)||this.logIssue(`Field '${e.name}' contains invalid characters (only letters, numbers, and underscores allowed).`),e.name.length>31&&this.logIssue(`Field '${e.name}' exceeds 31 characters.`),hh.has(e.name.toLowerCase())&&this.logIssue(`Field '${e.name}' is a SQL reserved keyword.`),e.choiceList&&(e.choiceList.some(r=>!r)&&this.logIssue(`Field '${e.name}' has empty domain values.`),e.choiceList.length!==new Set(e.choiceList).size&&this.logIssue(`Field '${e.name}' has duplicate domain values.`),e.length!=null)){let r=Math.max(...e.choiceList.map(n=>n.length));r>e.length&&(this.newDesign?(console.debug(`Field '${e.name}' length ${e.length} is insufficient for choiceList value of length ${r}. Auto-fixing to ${r}.`),e.length=r):this.logIssue(`Field '${e.name}' length ${e.length} is insufficient for choiceList value of length ${r}.`))}}logIssue(e){console.debug(e),this.issues.push(e),this.isValid=!1}},gh=T.object({key:T.string().describe("Stable key identifier for the string."),value:T.string().describe("Display value for the string."),description:T.string().describe("Explanation of where/how the string is used.")}),_h=T.object({id:T.string().describe("ArcGIS item id (32 hex characters)."),title:T.string().describe("Item title."),description:T.string().describe("Item description."),type:T.enum(["Feature Layer (hosted)","Feature Layer (hosted, view)","Web Map","Instant App","Dashboard","Web Experience","Form","Table (hosted)","Table (hosted, view)","Hub Site Application","Hub Page","CSV","Data Pipeline","Desktop Application Template","Group","Notebook","QuickCapture Project"]).describe("ArcGIS item type.")}),Nc=T.object({name:T.string().describe("Field name."),type:T.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:T.string().describe("Field alias for display."),description:T.string().describe("Field description."),choiceList:T.array(T.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:T.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),yh=T.object({id:T.number().int().describe("Layer/table id within the feature service."),type:T.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),name:T.string().describe("Layer/table name."),description:T.string().describe("Layer/table description."),customFields:T.array(Nc).describe("User/business fields specific to the solution."),requiredFields:T.array(Nc).describe("Fields required for solution functionality (e.g., relationship keys).")}),wh=T.object({itemId:T.string().describe("ArcGIS item id for the feature layer."),addLayers:T.boolean().describe("Indicates whether new layers can be added during solution design."),layers:T.array(yh)}),oa=T.object({response:T.string().describe("Conversational response to the user's query."),solution:T.object({itemId:T.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),title:T.string().describe("Title of the solution."),description:T.string().describe("Description of the solution."),tags:T.array(T.string()).describe("Keywords/tags associated with the solution."),strings:T.array(gh).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:T.array(_h).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:wh.describe("Primary feature layer item and its schema/layers/tables details.")}),Ah=T.object({op:T.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:T.string().describe("RFC 6901 JSON Pointer to the target location."),value:T.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null \u2014 not an empty string \u2014 for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),from:T.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null \u2014 not an empty string \u2014 for all other operations.")}),bh=T.object({response:T.string().describe("Conversational response describing the accepted design changes."),patches:T.array(Ah).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),Ih=T.object({matchedTitles:T.array(T.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),xh=T.object({templateId:T.string().min(1).describe("Template id from the available template list."),confidence:T.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:T.string().min(1).describe("Short description this template in the user's use case/workflow.")}),vh=T.object({assistantResponse:T.string().describe("Natural-language response for the user."),isValidUseCase:T.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:T.array(xh).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),ia=t=>t in Qt,Th=5,Ch=.8,Ph=.15,Oh="Web Mapping Application",kh="Embeddings",wo=null,ta=null,Ao=null,bo=null,Sh="Build",is=Object.assign({"./prompts/description.md":()=>import("./GYL4W6ZG.js").then(t=>t.default),"./prompts/designSolution.md":()=>import("./TSYIZSCP.js").then(t=>t.default),"./prompts/findExistingSolution.md":()=>import("./PRXFYNIG.js").then(t=>t.default),"./prompts/initialAssessment.md":()=>import("./SXVCHOTK.js").then(t=>t.default),"./prompts/updateDesign.md":()=>import("./RMCQZMLA.js").then(t=>t.default)}),Eh=fh.builderMessages,de=(t,e,r)=>{let n=sa(e)?.builderMessages?.[t]??Eh[t];if(!r)return n;for(let[s,o]of Object.entries(r))n=n.replaceAll(`{{${s}}}`,o);return n},Fc=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},Mh=async(t,e,r)=>{if(!t)return null;let n=`type:"${Oh}" AND typekeywords:${kh} AND group:${t}`;return(await Oo({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function Rh(t,e,r){try{let n=await Mh(t,e,r);if(!n)return null;let s=new nh({id:n.id});return await s.load(),await s.fetchData("json")}catch{return null}}var $h=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${Sh} AND group:${t}`;return(await Oo({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},Nh=async(t,e,r)=>{try{let n=await xa(t,{params:e?{token:e}:void 0,portal:r}),s=n?.buildSolution;if(!s)return null;let o=n?.params,i=o&&typeof o=="object"&&!Array.isArray(o)?o:null;return{buildSolution:s,params:i}}catch{return null}},Vt=(t,e={})=>{let r=t;return"itemId"in e&&(r={...r,solution:{...r.solution,itemId:e.itemId??null}}),e.sourceBuildSolution!=null&&(r={...r,sourceBuildSolution:e.sourceBuildSolution}),"params"in e&&(r={...r,params:e.params??null}),"templateId"in e&&(r={...r,templateId:e.templateId??null}),r},Bc=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Uo({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},aa=async t=>{if(ta){Object.entries(ta).forEach(([i,a])=>{Qt[i]&&(Qt[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=Wc(t),n=qc(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let s=await $h(r,e,n),o={};await Promise.all(s.map(async i=>{let a=i.properties?.templateInfo;if(!a||typeof a!="object")return;let u=a.id;if(typeof u!="string"||o[u])return;let l=await Nh(i.id,e,n);if(!l)return;let{buildSolution:p,params:m}=l;if(typeof p=="object"&&p!==null&&"solution"in p){let h=p.solution;h.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0}let _={...a,buildSolution:p};o[u]=Vt(new Uo(_).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(p),params:m?structuredClone(m):null}),Qt[u]={...a,initialTemplate:o[u]}})),ta=o},Kc=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},Wc=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},qc=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},Lh=async t=>{await Promise.all([Jc(t),aa(t)])},Hc=async t=>{let e=Kc(t);(!Ao||e&&e!==bo)&&(bo=e??bo,Ao=Lh(t).catch(r=>{throw Ao=null,bo=null,r})),await Ao};async function Jc(t){if(wo)return wo;let e=Wc(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=qc(t),n=t?.configurable?.context?.configContext?.portalURL;await new rh(n?{url:n}:void 0).load();let s=Kc(t)??void 0,o=await Rh(e,s,r);return o?(wo=o.items,wo):null}var Dh=()=>Object.entries(Qt).map(([t,e])=>`ID: ${t}
81
+ Label: ${e.label}
82
+ Description: ${e.description}`).join(`
83
+
84
+ `),jh=t=>{let e=t?.configurable?.context?.solutionDesignJson;if(typeof e!="string"||!e.trim())return null;try{let r=JSON.parse(e),n=Vt({response:"",...r},{itemId:r?.solution?.itemId??null}),s=oa.safeParse(n);if(!s.success)return null;let{response:o,...i}=s.data,a=r.templateId,u=typeof a=="string"&&ia(a)?a:null;return Vt(i,{sourceBuildSolution:r.sourceBuildSolution,templateId:u,params:r.params??null})}catch{return null}},Zt=t=>{let e=new CustomEvent("assistantProcessing",{detail:t});window.dispatchEvent(e)},Zc=z.Root({...po(),templateDescription:z({reducer:(t,e)=>typeof e=="string"||e===null?e:t??null,default:()=>null}),currentDesign:z({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),assessment:z({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),selectedTemplate:z({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),existingMatches:z({reducer:(t=[],e)=>e===void 0?t:e??[],default:()=>[]})}),zh=(t,e)=>{let r=jh(e),n=r?.templateId??null,s={};return JSON.stringify(t.currentDesign)!==JSON.stringify(r)&&(s.currentDesign=r),n&&t.selectedTemplate!==n&&(s.selectedTemplate=n),s},Uh=async(t,e)=>{await ct({text:de("understandingRequest",e)},e),await Hc(e);let r=t.agentExecutionContext.userRequest,n=Dh(),s=t.agentExecutionContext.messages.slice(-11),o=await rs({promptText:await pt(is,"initialAssessment"),modelTier:"advanced",temperature:0,schema:vh,messages:s,inputVariables:{query:r,availableTemplates:n}}),i=o.matchedTemplates.filter(m=>ia(m.templateId)),a={...o,matchedTemplates:i},[u,l]=i,p=u&&u.confidence>=Ch&&(l===void 0||u.confidence-l.confidence>=Ph)?u.templateId:null;return{assessment:a,selectedTemplate:p,existingMatches:[]}},Fh=t=>{let e=t.assessment?.assistantResponse??"";return Zt(!1),{outputMessage:e,summary:e,status:"success"}},Bh=(t,e)=>{let{hitlResponse:r}=e.configurable,n="selectTemplate",s=t.assessment?.matchedTemplates.filter(u=>ia(u.templateId))??[],o=s.map(u=>`${u.templateDescription}`);if(r?.agentId!=="solutionBuilder"||r.id!==n){let u={agentId:"solutionBuilder",id:n,kind:"singleSelection",message:de("selectTemplatePrompt",e),metadata:[...o]};throw new ko(u)}let i=String(r.payload??""),a=o.findIndex(u=>u===i);return{selectedTemplate:(a>=0?s[a]:void 0)?.templateId??s[0]?.templateId??null}},Kh=async(t,e)=>{await ct({text:de("searchingExistingSolutions",e)},e);let r=t.agentExecutionContext.userRequest,n=dh(t.agentExecutionContext.messages)||r,s=await Jc(e);if(!s)return console.warn("Solutions Search: failed to load solution embeddings cache; skipping search."),{existingMatches:[]};if(!s.length)return{existingMatches:[]};let[o]=await Oc([n]),i=s.map(p=>({solution:p,score:Ec(o,p.embedding)}));i.sort((p,m)=>m.score-p.score);let a=i.slice(0,Th);if(!a.length)return{existingMatches:[]};let u=a.map(({solution:p})=>`${p.title}
85
+ Snippet: ${p.snippet}
86
+ Description: ${p.description}`).join(`
87
+
88
+ `),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await rs({promptText:await pt(is,"findExistingSolution"),modelTier:"fast",temperature:0,schema:Ih,messages:l,inputVariables:{query:r,candidates:u}})).matchedTitles.map(p=>a.find(({solution:m})=>m.title===p)).filter(p=>p!==void 0)}},Wh=(t,e)=>{let{existingMatches:r}=t,{hitlResponse:n}=e.configurable,s=`confirmExistingSolution:${r[0].solution.id}`;if(n?.agentId!=="solutionBuilder"||n.id!==s){r.length===1?Dc(r[0].solution.id):Lc(r);let o=r.map(u=>`${u.solution.title}`).join(", "),i=de("existingSolutionMatch",e,{solutionMatch:o}),a={agentId:"solutionBuilder",id:s,kind:"booleanChoice",message:i,metadata:[]};throw new ko(a)}return{}},Vc=async(t,e)=>{await Hc(e);let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await ct({text:de("creatingDesign",e)},e);let s=Tn(t.selectedTemplate);if(s?.initialTemplate||(await aa(e),s=Tn(t.selectedTemplate)),!s?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let o=Vt(r??s.initialTemplate,{itemId:(r??s.initialTemplate)?.solution?.itemId??null,sourceBuildSolution:r?.sourceBuildSolution??s.initialTemplate.sourceBuildSolution,params:r?.params??s.initialTemplate.params??null}),i=t.agentExecutionContext.messages.slice(-11),a=await rs({promptText:await pt(is,"designSolution"),modelTier:"advanced",temperature:0,schema:oa,messages:i,inputVariables:{currentDesign:JSON.stringify(Fo(o)),templateInstructions:s.instructions,query:n}}),{response:u,featureLayer:l,...p}=a,m=Bo(l,o.featureLayer),_=Vt({...p,featureLayer:m},{itemId:o?.solution?.itemId,sourceBuildSolution:o.sourceBuildSolution,templateId:t.selectedTemplate??null,params:o.params??null}),h=new Io(_,s.initialTemplate);if(!h.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:h.issues,llmResponse:a}),{outputMessage:de("createDesignFailed",e)};let A=_.sourceBuildSolution,I=Bc(_,A);if(!I.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:I.error,llmResponse:a,design:_});let E=de("createDesignFailed",e);return{outputMessage:E,summary:E,status:"success"}}return Zt(!1),Fc(_),{outputMessage:u,summary:u,status:"success",currentDesign:_}},qh=async(t,e)=>{let{currentDesign:r}=t;if(!r)return Vc(t,e);let n=t.agentExecutionContext.userRequest,s=t.agentExecutionContext.messages.slice(-11);await ct({text:de("updatingDesign",e)},e);let o=await rs({promptText:await pt(is,"updateDesign"),modelTier:"advanced",temperature:0,schema:bh,messages:s,inputVariables:{currentDesign:JSON.stringify(Ka(r)),query:n}}),{response:i,patches:a}=o,u=[...a.map(R=>({op:R.op,path:R.path.replace(/\/+$/,""),...R.value!=null&&R.value!==""?{value:JSON.parse(R.value)}:{},...R.from!=null&&R.from!==""?{from:R.from}:{}}))].sort((R,j)=>R.op!=="remove"||j.op!=="remove"?0:j.path.localeCompare(R.path,void 0,{numeric:!0})),l=structuredClone(Fo(r));try{In(l,u,!0)}catch(R){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:R,llmResponse:o,patches:u,patchTarget:l}),Zt(!1);let j=de("applyChangeFailed",e);return{outputMessage:j,summary:j,status:"success"}}let p=Vt({response:"",...l},{itemId:r.solution?.itemId??null}),m=oa.safeParse(p);if(!m.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:m.error.issues,llmResponse:o,patchedDesign:p}),Zt(!1);let R=de("applyChangeFailed",e);return{outputMessage:R,summary:R,status:"success"}}let{response:_,featureLayer:h,...A}=m.data,I=Bo(h,r.featureLayer),E=Vt({...A,featureLayer:I},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),g=Tn(t.selectedTemplate);if(g?.initialTemplate||(await aa(e),g=Tn(t.selectedTemplate)),!g?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let w=new Io(E,g.initialTemplate,!1);if(!w.isValid)return console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:w.issues,llmResponse:o,patchedDesign:E}),Zt(!1),{outputMessage:de("applyChangeFailed",e)};let k=E.sourceBuildSolution,L=Bc(E,k);if(!L.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:L.error,llmResponse:o,design:E});let R=de("applyChangeFailed",e);return Zt(!1),{outputMessage:R,summary:R,status:"success"}}return Zt(!1),Fc(E),{outputMessage:i,summary:i,status:"success",currentDesign:E}},Hh=t=>t.currentDesign!==null?"updateDesign":"assessInitialRequest",Jh=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidUseCaseExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",Zh=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",Vh=()=>new Xt(Zc).addNode("syncCurrentDesignFromContext",zh).addNode("assessInitialRequest",Uh).addNode("invalidUseCaseExit",Fh).addNode("selectTemplateHIL",Bh).addNode("findExistingSolutions",Kh).addNode("confirmContinueBuildingHIL",Wh).addNode("designSolution",Vc).addNode("updateDesign",qh).addEdge(Gt,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",Hh,{updateDesign:"updateDesign",assessInitialRequest:"assessInitialRequest"}).addConditionalEdges("assessInitialRequest",Jh,{invalidUseCaseExit:"invalidUseCaseExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidUseCaseExit",Se).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Zh,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addEdge("confirmContinueBuildingHIL","designSolution").addEdge("designSolution",Se).addEdge("updateDesign",Se),Gh=await pt(is,"description"),Yh={id:"solutionsBuilder",name:"Solutions Builder Agent",description:Gh,createGraph:Vh,workspace:Zc},Xh=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./MZXUUA7G.js").then(t=>t.default)});function Qh(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">&#91;$1&#93;</a></sup>')}function eg(t,e){let r=[];return(e?.configurable?.context?.configContext.allCards??[]).forEach(n=>{let s=n.title;if(t.toLowerCase().includes(s.toLowerCase())){let o=`<a href="" target="solutionId:${n.deployCommonId}">${s}</a>`,i=new RegExp(s,"gi");t=t.replace(i,o),r.push({solution:{title:n.title,id:n.deployCommonId,snippet:n.snippet,description:n.description},score:100})}}),{source:t,allMatches:r}}function tg(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function Gc(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function ra(t,e,r){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",token:r},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status} calling ${e}`);return n.json()}var rg=t=>new Promise(e=>setTimeout(e,t)),Yc=z.Root({...po(),solutionResponse:z({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:z({reducer:(t,e)=>e??null,default:()=>null}),conversationId:z({reducer:(t,e)=>e??t,default:()=>null})}),ng=()=>new Xt(Yc).addNode("initializeAgent",og).addNode("askSolutionsQuestions",sg).addEdge(Gt,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",Se),Xc=async(t,e,r)=>{if(!t)return;let n=Gc(t);if(!n)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"}}}};r&&(s.conversationId=r),ra(s,n,e??"")},sg=async(t,e)=>{let r=sa(e),n=t.documentSkillUrl,s=[];await ct({text:r.agentProgress.explorerAgentSearching},e);let o=await ra({message:t.agentExecutionContext.userRequest,conversationId:e?.configurable?.context?.convoId??void 0,context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"}}}},n,e?.configurable?.context?.token??"");o.conversationId&&e?.configurable?.context?.setConversationId&&e.configurable.context.setConversationId(o.conversationId);let i={message:o.message,conversationId:o.conversationId,hasMore:o.hasMore,ackSequenceNumber:o.sequenceNumber,inquiryId:o.inquiryId},a="",u=null,l=async m=>{let _=m.context?.results?.[0]?.reply??"";if(_!==""){let A=Qh(_),I=eg(A,e);a=I.source,s=[...s,...I.allMatches.filter(E=>!s.some(g=>g.solution.id===E.solution.id))]}_!==""&&m.context?.results?.[0]?.followupQuestions&&(u=m.context.results[0].followupQuestions);let h=m.context?.results?.[0]?.status?.currentStatusStep;if(h){let A="";h===1?A=r.agentProgress.explorerAgentReading:h===2?A=r.agentProgress.explorerAgentReviewing:h===3&&(A=r.agentProgress.explorerAgentPreparing),await ct({text:A},e)}};for(await l(o);i.hasMore;)await rg(500),o=await ra({conversationId:i.conversationId,ackSequenceNumber:i.ackSequenceNumber,inquiryId:i.inquiryId},n,e?.configurable?.context?.token??""),i={message:o.message,conversationId:o.conversationId,hasMore:o.hasMore,ackSequenceNumber:o.sequenceNumber,inquiryId:o.inquiryId},await l(o);if(u&&e?.configurable?.context?.updateSuggestedPrompts){let m=e.configurable.context.updateSuggestedPrompts,_=u;setTimeout(()=>m(_),0)}Gc(e?.configurable?.context.portal)&&Xc(e?.configurable?.context.portal,e?.configurable?.context.token??"",i.conversationId),s.length&&(s.length===1?Dc(s[0].solution.id):Lc(s));let p=new CustomEvent("assistantProcessing",{detail:!1});return window.dispatchEvent(p),{outputMessage:a,summary:a,status:"success",solutionResponse:i,conversationId:i.conversationId}},og=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=tg(e.configurable.context.portal)),{documentSkillUrl:r}},ig=await pt(Xh,"solutions_explorer_description"),ag={id:"solutionsExplorer",name:"Solutions Explorer Agent",description:ig,createGraph:ng,workspace:Yc},lg="https://links.esri.com/solutions/agol-organizational-account",ug="https://links.esri.com/solutions/configure-assistants",na=class extends ya{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=Aa({name:"arcgis-solutions-assistant",blocking:!0}),this._builderWidth=48,this._solutionDesignJson='{ "solution": null }',this._isAssistantBusy=!1,this._isBuilderBusy=!1,this._preChatCheck=!1,this._assistantRef=ga(),this._configContextConsumer=Po({context:ba,subscribe:!0,callback:e=>{e?.portalURL&&($c.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Po({context:Ia,subscribe:!0,callback:e=>{e?.design&&(this._solutionDesignJson=JSON.stringify(e.design,null,2))}}),this._handleResize=()=>{this._isMobile=window.innerWidth<=800},this.closeAssistant=To(),this.assistantProcessing=To(),this._handleAssistantLinkClick=e=>{let r=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(r?.href)if(e.preventDefault(),r.target.indexOf("solutionId:")>-1){let n=r.target.split("solutionId:")[1];this._emitItemIdFromAI(n)}else window.open(r.href,"_blank","noopener,noreferrer")},this._onSolutionDesignUpdate=e=>{let r=e.detail;this._solutionDesignJson=r?JSON.stringify(r,null,2):'{ "solution": null }'},this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open},this.listenOn(window,"arcgisFeedback",e=>{let r=e.detail,{agentPicked:n,taskAssigned:s,userMessage:o}=this._parseAgentPickedAndTask(r);this._sendFeedback(r.content,o??s??"",r.feedback?.positive?"Good":r.feedback?.positive=="Bad"?"Bad":"N/A",n??"")})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_orgSettings:16,_suggestedPrompts:16,_hasInteracted:16,_isMobile:16,_translations:16,_builderWidth:16,_solutionDesignJson:16,_isAssistantBusy:16,_isBuilderBusy:16,_preChatCheck:16}}static{this.styles=sh}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}connectedCallback(){super.connectedCallback(),window.addEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.addEventListener("click",this._handleAssistantLinkClick),window.addEventListener("resize",this._handleResize),this._builderDesignContextConsumer}disconnectedCallback(){window.removeEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.removeEventListener("click",this._handleAssistantLinkClick),window.removeEventListener("resize",this._handleResize),super.disconnectedCallback()}loaded(){this._checkURLOpenParameter()}load(){this._configContextConsumer.value?.portalURL&&($c.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(e){this._loadUserFirstName()}willUpdate(e){e.has("open")&&this.open&&window.dispatchEvent(new CustomEvent("openAssistant")),this._configContextConsumer.value?.authentication&&this._configContextConsumer.value?.userSession?.token&&(this._preChatCheck||(Xc(this._configContextConsumer.value?.authentication.Portal,this._configContextConsumer.value?.userSession?.token),this._preChatCheck=!0)),this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return dt`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??Co} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return dt`<calcite-notice open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${Wa(this._translations.noPermissionMessage.replace("{{orgUrl}}",lg).replace("{{configAI}}",ug))}</div></calcite-notice>`}render(){let e=this._suggestedPrompts.length>0?this._suggestedPrompts:this._hasInteracted?[]:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length>0?e=this._suggestedPrompts:this._hasInteracted||(e=[...Object.values(this._translations.defaultFollowUpQuestions)]),dt`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?dt`${!this._isMobile&&dt`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.solutionBuilder} .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${()=>{window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"))}} scale=m slot=header-actions-end></calcite-action>`||""}<calcite-action id=newChatButton icon=speech-bubble-plus .text=${this._translations.tooltips.newConversation} @click=${()=>{this._conversationId=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._assistantRef.value?.clearChatHistory()}} scale=m slot=header-actions-end></calcite-action><calcite-tooltip placement=bottom reference-element=newChatButton><span>${this._translations.tooltips.newConversation}</span></calcite-tooltip>${!this._isMobile&&dt`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.toggleSolutionBuilder}</span></calcite-tooltip>`||""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage??Co} .suggestedPrompts=${e} @arcgisSubmit=${r=>{console.log("arcgis submit: ",r.detail),this._suggestedPrompts=[],e=[],this._hasInteracted=!0;let n=Date.now(),s=va(n),o=r.detail||"Unknown";this._telemetry?.logEvent({category:Ta.ASSISTANT,action:"Chat",dimensions:[o],metrics:[s]}),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail}} ${_a(this._assistantRef)}><arcgis-assistant-agent .agent=${ag} .context=${{token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,translations:this._translations,updateSuggestedPrompts:r=>{this._suggestedPrompts=r},setConversationId:r=>{this._conversationId=r}}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${lh} .context=${{translations:this._translations,clearSuggestedPrompts:()=>{this._suggestedPrompts=[]}}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Yh} .context=${{solutionDesignJson:this._solutionDesignJson,translations:this._translations,token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value}}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=outline kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>`:this._renderNoPermission():this._renderNoSign()}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${()=>{this.closeAssistant.emit(!0)}} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`}_sendFeedback(e,r,n,s){let o=`https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(r)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({agent:s}))}&field:version=${encodeURIComponent("v2")}`;window.open(o,"_blank")}async _loadUserFirstName(){try{let e=await this._configContextConsumer.value?.userSession?.getUser();if(e?.fullName){let r=e.fullName.split(" ")[0];this.userFirstName=r}}catch{}}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],s=[...r].sort((p,m)=>m.id-p.id).find(p=>p.role==="user"&&p.id<=e.id)?.content||null,o=n.find(p=>typeof p=="string"&&p.includes("Agent picked:"))??null;if(!o)return{agentPicked:null,taskAssigned:null,userMessage:s};let i=/Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i,a=o.match(i);if(!a)return{agentPicked:null,taskAssigned:null,userMessage:s};let u=a[1].trim(),l=a[2].trim();return{agentPicked:u,taskAssigned:l,userMessage:s}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};wa("arcgis-solutions-assistant",na);return na},"config","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,c)