@vibecontrols/vibe-plugin-ai-codex 2026.602.1 → 2026.1107.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,24 @@
1
1
  // @bun
2
- var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res)=>()=>(fn&&(res=fn(fn=0)),res);var default_format="RFC3986",formatters,RFC1738="RFC1738";var init_formats=__esm(()=>{formatters={RFC1738:(v)=>String(v).replace(/%20/g,"+"),RFC3986:(v)=>String(v)}});function is_buffer(obj){if(!obj||typeof obj!=="object")return!1;return!!(obj.constructor&&obj.constructor.isBuffer&&obj.constructor.isBuffer(obj))}function maybe_map(val,fn){if(is_array(val)){let mapped=[];for(let i=0;i<val.length;i+=1)mapped.push(fn(val[i]));return mapped}return fn(val)}var is_array,hex_table,limit=1024,encode=(str,_defaultEncoder,charset,_kind,format)=>{if(str.length===0)return str;let string=str;if(typeof str==="symbol")string=Symbol.prototype.toString.call(str);else if(typeof str!=="string")string=String(str);if(charset==="iso-8859-1")return escape(string).replace(/%u[0-9a-f]{4}/gi,function($0){return"%26%23"+parseInt($0.slice(2),16)+"%3B"});let out="";for(let j=0;j<string.length;j+=limit){let segment=string.length>=limit?string.slice(j,j+limit):string,arr=[];for(let i=0;i<segment.length;++i){let c=segment.charCodeAt(i);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||format===RFC1738&&(c===40||c===41)){arr[arr.length]=segment.charAt(i);continue}if(c<128){arr[arr.length]=hex_table[c];continue}if(c<2048){arr[arr.length]=hex_table[192|c>>6]+hex_table[128|c&63];continue}if(c<55296||c>=57344){arr[arr.length]=hex_table[224|c>>12]+hex_table[128|c>>6&63]+hex_table[128|c&63];continue}i+=1,c=65536+((c&1023)<<10|segment.charCodeAt(i)&1023),arr[arr.length]=hex_table[240|c>>18]+hex_table[128|c>>12&63]+hex_table[128|c>>6&63]+hex_table[128|c&63]}out+=arr.join("")}return out};var init_utils=__esm(()=>{init_formats();is_array=Array.isArray,hex_table=(()=>{let array=[];for(let i=0;i<256;++i)array.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase());return array})()});function is_non_nullish_primitive(v){return typeof v==="string"||typeof v==="number"||typeof v==="boolean"||typeof v==="symbol"||typeof v==="bigint"}function inner_stringify(object,prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,sideChannel){let obj=object,tmp_sc=sideChannel,step=0,find_flag=!1;while((tmp_sc=tmp_sc.get(sentinel))!==void 0&&!find_flag){let pos=tmp_sc.get(object);if(step+=1,typeof pos<"u")if(pos===step)throw RangeError("Cyclic object value");else find_flag=!0;if(typeof tmp_sc.get(sentinel)>"u")step=0}if(typeof filter==="function")obj=filter(prefix,obj);else if(obj instanceof Date)obj=serializeDate?.(obj);else if(generateArrayPrefix==="comma"&&is_array2(obj))obj=maybe_map(obj,function(value){if(value instanceof Date)return serializeDate?.(value);return value});if(obj===null){if(strictNullHandling)return encoder&&!encodeValuesOnly?encoder(prefix,defaults.encoder,charset,"key",format):prefix;obj=""}if(is_non_nullish_primitive(obj)||is_buffer(obj)){if(encoder){let key_value=encodeValuesOnly?prefix:encoder(prefix,defaults.encoder,charset,"key",format);return[formatter?.(key_value)+"="+formatter?.(encoder(obj,defaults.encoder,charset,"value",format))]}return[formatter?.(prefix)+"="+formatter?.(String(obj))]}let values=[];if(typeof obj>"u")return values;let obj_keys;if(generateArrayPrefix==="comma"&&is_array2(obj)){if(encodeValuesOnly&&encoder)obj=maybe_map(obj,encoder);obj_keys=[{value:obj.length>0?obj.join(",")||null:void 0}]}else if(is_array2(filter))obj_keys=filter;else{let keys=Object.keys(obj);obj_keys=sort?keys.sort(sort):keys}let encoded_prefix=encodeDotInKeys?String(prefix).replace(/\./g,"%2E"):String(prefix),adjusted_prefix=commaRoundTrip&&is_array2(obj)&&obj.length===1?encoded_prefix+"[]":encoded_prefix;if(allowEmptyArrays&&is_array2(obj)&&obj.length===0)return adjusted_prefix+"[]";for(let j=0;j<obj_keys.length;++j){let key=obj_keys[j],value=typeof key==="object"&&typeof key.value<"u"?key.value:obj[key];if(skipNulls&&value===null)continue;let encoded_key=allowDots&&encodeDotInKeys?key.replace(/\./g,"%2E"):key,key_prefix=is_array2(obj)?typeof generateArrayPrefix==="function"?generateArrayPrefix(adjusted_prefix,encoded_key):adjusted_prefix:adjusted_prefix+(allowDots?"."+encoded_key:"["+encoded_key+"]");sideChannel.set(object,step);let valueSideChannel=new WeakMap;valueSideChannel.set(sentinel,sideChannel),push_to_array(values,inner_stringify(value,key_prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,generateArrayPrefix==="comma"&&encodeValuesOnly&&is_array2(obj)?null:encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,valueSideChannel))}return values}function normalize_stringify_options(opts=defaults){if(typeof opts.allowEmptyArrays<"u"&&typeof opts.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof opts.encodeDotInKeys<"u"&&typeof opts.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(opts.encoder!==null&&typeof opts.encoder<"u"&&typeof opts.encoder!=="function")throw TypeError("Encoder has to be a function.");let charset=opts.charset||defaults.charset;if(typeof opts.charset<"u"&&opts.charset!=="utf-8"&&opts.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let format=default_format;if(typeof opts.format<"u"){if(!has.call(formatters,opts.format))throw TypeError("Unknown format option provided.");format=opts.format}let formatter=formatters[format],filter=defaults.filter;if(typeof opts.filter==="function"||is_array2(opts.filter))filter=opts.filter;let arrayFormat;if(opts.arrayFormat&&opts.arrayFormat in array_prefix_generators)arrayFormat=opts.arrayFormat;else if("indices"in opts)arrayFormat=opts.indices?"indices":"repeat";else arrayFormat=defaults.arrayFormat;if("commaRoundTrip"in opts&&typeof opts.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let allowDots=typeof opts.allowDots>"u"?!!opts.encodeDotInKeys===!0?!0:defaults.allowDots:!!opts.allowDots;return{addQueryPrefix:typeof opts.addQueryPrefix==="boolean"?opts.addQueryPrefix:defaults.addQueryPrefix,allowDots,allowEmptyArrays:typeof opts.allowEmptyArrays==="boolean"?!!opts.allowEmptyArrays:defaults.allowEmptyArrays,arrayFormat,charset,charsetSentinel:typeof opts.charsetSentinel==="boolean"?opts.charsetSentinel:defaults.charsetSentinel,commaRoundTrip:!!opts.commaRoundTrip,delimiter:typeof opts.delimiter>"u"?defaults.delimiter:opts.delimiter,encode:typeof opts.encode==="boolean"?opts.encode:defaults.encode,encodeDotInKeys:typeof opts.encodeDotInKeys==="boolean"?opts.encodeDotInKeys:defaults.encodeDotInKeys,encoder:typeof opts.encoder==="function"?opts.encoder:defaults.encoder,encodeValuesOnly:typeof opts.encodeValuesOnly==="boolean"?opts.encodeValuesOnly:defaults.encodeValuesOnly,filter,format,formatter,serializeDate:typeof opts.serializeDate==="function"?opts.serializeDate:defaults.serializeDate,skipNulls:typeof opts.skipNulls==="boolean"?opts.skipNulls:defaults.skipNulls,sort:typeof opts.sort==="function"?opts.sort:null,strictNullHandling:typeof opts.strictNullHandling==="boolean"?opts.strictNullHandling:defaults.strictNullHandling}}function stringify(object,opts={}){let obj=object,options=normalize_stringify_options(opts),obj_keys,filter;if(typeof options.filter==="function")filter=options.filter,obj=filter("",obj);else if(is_array2(options.filter))filter=options.filter,obj_keys=filter;let keys=[];if(typeof obj!=="object"||obj===null)return"";let generateArrayPrefix=array_prefix_generators[options.arrayFormat],commaRoundTrip=generateArrayPrefix==="comma"&&options.commaRoundTrip;if(!obj_keys)obj_keys=Object.keys(obj);if(options.sort)obj_keys.sort(options.sort);let sideChannel=new WeakMap;for(let i=0;i<obj_keys.length;++i){let key=obj_keys[i];if(options.skipNulls&&obj[key]===null)continue;push_to_array(keys,inner_stringify(obj[key],key,generateArrayPrefix,commaRoundTrip,options.allowEmptyArrays,options.strictNullHandling,options.skipNulls,options.encodeDotInKeys,options.encode?options.encoder:null,options.filter,options.sort,options.allowDots,options.serializeDate,options.format,options.formatter,options.encodeValuesOnly,options.charset,sideChannel))}let joined=keys.join(options.delimiter),prefix=options.addQueryPrefix===!0?"?":"";if(options.charsetSentinel)if(options.charset==="iso-8859-1")prefix+="utf8=%26%2310003%3B&";else prefix+="utf8=%E2%9C%93&";return joined.length>0?prefix+joined:""}var has,array_prefix_generators,is_array2,push,push_to_array=function(arr,value_or_array){push.apply(arr,is_array2(value_or_array)?value_or_array:[value_or_array])},to_ISO,defaults,sentinel;var init_stringify=__esm(()=>{init_utils();init_formats();has=Object.prototype.hasOwnProperty,array_prefix_generators={brackets(prefix){return String(prefix)+"[]"},comma:"comma",indices(prefix,key){return String(prefix)+"["+key+"]"},repeat(prefix){return String(prefix)}},is_array2=Array.isArray,push=Array.prototype.push,to_ISO=Date.prototype.toISOString,defaults={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:encode,encodeValuesOnly:!1,format:default_format,formatter:formatters[default_format],indices:!1,serializeDate(date){return to_ISO.call(date)},skipNulls:!1,strictNullHandling:!1};sentinel={}});var init_qs=__esm(()=>{init_stringify()});var VERSION="4.104.0";function setShims(shims,options={auto:!1}){if(auto)throw Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`);if(kind)throw Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``);auto=options.auto,kind=shims.kind,fetch2=shims.fetch,Request2=shims.Request,Response2=shims.Response,Headers2=shims.Headers,FormData2=shims.FormData,Blob2=shims.Blob,File2=shims.File,ReadableStream2=shims.ReadableStream,getMultipartRequestOptions=shims.getMultipartRequestOptions,getDefaultAgent=shims.getDefaultAgent,fileFromPath=shims.fileFromPath,isFsReadStream=shims.isFsReadStream}var auto=!1,kind=void 0,fetch2=void 0,Request2=void 0,Response2=void 0,Headers2=void 0,FormData2=void 0,Blob2=void 0,File2=void 0,ReadableStream2=void 0,getMultipartRequestOptions=void 0,getDefaultAgent=void 0,fileFromPath=void 0,isFsReadStream=void 0;var MultipartBody;var init_MultipartBody=__esm(()=>{MultipartBody=class MultipartBody{constructor(body){this.body=body}get[Symbol.toStringTag](){return"MultipartBody"}}});function getRuntime({manuallyImported}={}){let recommendation=manuallyImported?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",_fetch,_Request,_Response,_Headers;try{_fetch=fetch,_Request=Request,_Response=Response,_Headers=Headers}catch(error){throw Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`)}return{kind:"web",fetch:_fetch,Request:_Request,Response:_Response,Headers:_Headers,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`)}},getMultipartRequestOptions:async(form,opts)=>({...opts,body:new MultipartBody(form)}),getDefaultAgent:(url)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(value)=>!1}}var init_web_runtime=__esm(()=>{init_MultipartBody()});import{ReadStream as FsReadStream}from"fs";function getRuntime2(){let runtime=getRuntime();function isFsReadStream2(value){return value instanceof FsReadStream}return{...runtime,isFsReadStream:isFsReadStream2}}var init_bun_runtime=__esm(()=>{init_web_runtime()});var init_runtime_bun=__esm(()=>{init_bun_runtime()});var init=()=>{if(!kind)setShims(getRuntime2(),{auto:!0})};var init__shims=__esm(()=>{init_runtime_bun();init()});var OpenAIError,APIError,APIUserAbortError,APIConnectionError,APIConnectionTimeoutError,BadRequestError,AuthenticationError,PermissionDeniedError,NotFoundError,ConflictError,UnprocessableEntityError,RateLimitError,InternalServerError,LengthFinishReasonError,ContentFilterFinishReasonError;var init_error=__esm(()=>{init_core();OpenAIError=class OpenAIError extends Error{};APIError=class APIError extends OpenAIError{constructor(status,error,message,headers){super(`${APIError.makeMessage(status,error,message)}`);this.status=status,this.headers=headers,this.request_id=headers?.["x-request-id"],this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message==="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;if(status&&msg)return`${status} ${msg}`;if(status)return`${status} status code (no body)`;if(msg)return msg;return"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;if(status===400)return new BadRequestError(status,error,message,headers);if(status===401)return new AuthenticationError(status,error,message,headers);if(status===403)return new PermissionDeniedError(status,error,message,headers);if(status===404)return new NotFoundError(status,error,message,headers);if(status===409)return new ConflictError(status,error,message,headers);if(status===422)return new UnprocessableEntityError(status,error,message,headers);if(status===429)return new RateLimitError(status,error,message,headers);if(status>=500)return new InternalServerError(status,error,message,headers);return new APIError(status,error,message,headers)}};APIUserAbortError=class APIUserAbortError extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}};APIConnectionError=class APIConnectionError extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0);if(cause)this.cause=cause}};APIConnectionTimeoutError=class APIConnectionTimeoutError extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}};BadRequestError=class BadRequestError extends APIError{};AuthenticationError=class AuthenticationError extends APIError{};PermissionDeniedError=class PermissionDeniedError extends APIError{};NotFoundError=class NotFoundError extends APIError{};ConflictError=class ConflictError extends APIError{};UnprocessableEntityError=class UnprocessableEntityError extends APIError{};RateLimitError=class RateLimitError extends APIError{};InternalServerError=class InternalServerError extends APIError{};LengthFinishReasonError=class LengthFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}};ContentFilterFinishReasonError=class ContentFilterFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}});class LineDecoder{constructor(){_LineDecoder_carriageReturnIndex.set(this,void 0),this.buffer=new Uint8Array,__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,null,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk=chunk instanceof ArrayBuffer?new Uint8Array(chunk):typeof chunk==="string"?new TextEncoder().encode(chunk):chunk,newData=new Uint8Array(this.buffer.length+binaryChunk.length);newData.set(this.buffer),newData.set(binaryChunk,this.buffer.length),this.buffer=newData;let lines=[],patternIndex;while((patternIndex=findNewlineIndex(this.buffer,__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")))!=null){if(patternIndex.carriage&&__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")==null){__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,patternIndex.index,"f");continue}if(__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")!=null&&(patternIndex.index!==__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")+1||patternIndex.carriage)){lines.push(this.decodeText(this.buffer.slice(0,__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")-1))),this.buffer=this.buffer.slice(__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")),__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,null,"f");continue}let endIndex=__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")!==null?patternIndex.preceding-1:patternIndex.preceding,line=this.decodeText(this.buffer.slice(0,endIndex));lines.push(line),this.buffer=this.buffer.slice(patternIndex.index),__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,null,"f")}return lines}decodeText(bytes){if(bytes==null)return"";if(typeof bytes==="string")return bytes;if(typeof Buffer<"u"){if(bytes instanceof Buffer)return bytes.toString();if(bytes instanceof Uint8Array)return Buffer.from(bytes).toString();throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(bytes instanceof Uint8Array||bytes instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(bytes);throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`)}throw new OpenAIError("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
3
- `)}}function findNewlineIndex(buffer,startIndex){for(let i=startIndex??0;i<buffer.length;i++){if(buffer[i]===10)return{preceding:i,index:i+1,carriage:!1};if(buffer[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function findDoubleNewlineIndex(buffer){for(let i=0;i<buffer.length-1;i++){if(buffer[i]===10&&buffer[i+1]===10)return i+2;if(buffer[i]===13&&buffer[i+1]===13)return i+2;if(buffer[i]===13&&buffer[i+1]===10&&i+3<buffer.length&&buffer[i+2]===13&&buffer[i+3]===10)return i+4}return-1}var __classPrivateFieldSet=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_LineDecoder_carriageReturnIndex;var init_line=__esm(()=>{init_error();_LineDecoder_carriageReturnIndex=new WeakMap;LineDecoder.NEWLINE_CHARS=new Set([`
4
- `,"\r"]);LineDecoder.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();if(result?.done)reader.releaseLock();return result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function*_iterSSEMessages(response,controller){if(!response.body)throw controller.abort(),new OpenAIError("Attempted to iterate over a response with no body");let sseDecoder=new SSEDecoder,lineDecoder=new LineDecoder,iter=ReadableStreamToAsyncIterable(response.body);for await(let sseChunk of iterSSEChunks(iter))for(let line of lineDecoder.decode(sseChunk)){let sse=sseDecoder.decode(line);if(sse)yield sse}for(let line of lineDecoder.flush()){let sse=sseDecoder.decode(line);if(sse)yield sse}}async function*iterSSEChunks(iterator){let data=new Uint8Array;for await(let chunk of iterator){if(chunk==null)continue;let binaryChunk=chunk instanceof ArrayBuffer?new Uint8Array(chunk):typeof chunk==="string"?new TextEncoder().encode(chunk):chunk,newData=new Uint8Array(data.length+binaryChunk.length);newData.set(data),newData.set(binaryChunk,data.length),data=newData;let patternIndex;while((patternIndex=findDoubleNewlineIndex(data))!==-1)yield data.slice(0,patternIndex),data=data.slice(patternIndex)}if(data.length>0)yield data}class SSEDecoder{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(line){if(line.endsWith("\r"))line=line.substring(0,line.length-1);if(!line){if(!this.event&&!this.data.length)return null;let sse={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],sse}if(this.chunks.push(line),line.startsWith(":"))return null;let[fieldname,_,value]=partition(line,":");if(value.startsWith(" "))value=value.substring(1);if(fieldname==="event")this.event=value;else if(fieldname==="data")this.data.push(value);return null}}function partition(str,delimiter){let index=str.indexOf(delimiter);if(index!==-1)return[str.substring(0,index),delimiter,str.substring(index+delimiter.length)];return[str,"",""]}var Stream;var init_streaming=__esm(()=>{init__shims();init_error();init_line();init_core();init_error();Stream=class Stream{constructor(iterator,controller){this.iterator=iterator,this.controller=controller}static fromSSEResponse(response,controller){let consumed=!1;async function*iterator(){if(consumed)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let sse of _iterSSEMessages(response,controller)){if(done)continue;if(sse.data.startsWith("[DONE]")){done=!0;continue}if(sse.event===null||sse.event.startsWith("response.")||sse.event.startsWith("transcript.")){let data;try{data=JSON.parse(sse.data)}catch(e){throw console.error("Could not parse message into JSON:",sse.data),console.error("From chunk:",sse.raw),e}if(data&&data.error)throw new APIError(void 0,data.error,void 0,createResponseHeaders(response.headers));yield data}else{let data;try{data=JSON.parse(sse.data)}catch(e){throw console.error("Could not parse message into JSON:",sse.data),console.error("From chunk:",sse.raw),e}if(sse.event=="error")throw new APIError(void 0,data.error,data.message,void 0);yield{event:sse.event,data}}}done=!0}catch(e){if(e instanceof Error&&e.name==="AbortError")return;throw e}finally{if(!done)controller.abort()}}return new Stream(iterator,controller)}static fromReadableStream(readableStream,controller){let consumed=!1;async function*iterLines(){let lineDecoder=new LineDecoder,iter=ReadableStreamToAsyncIterable(readableStream);for await(let chunk of iter)for(let line of lineDecoder.decode(chunk))yield line;for(let line of lineDecoder.flush())yield line}async function*iterator(){if(consumed)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let line of iterLines()){if(done)continue;if(line)yield JSON.parse(line)}done=!0}catch(e){if(e instanceof Error&&e.name==="AbortError")return;throw e}finally{if(!done)controller.abort()}}return new Stream(iterator,controller)}[Symbol.asyncIterator](){return this.iterator()}tee(){let left=[],right=[],iterator=this.iterator(),teeIterator=(queue)=>{return{next:()=>{if(queue.length===0){let result=iterator.next();left.push(result),right.push(result)}return queue.shift()}}};return[new Stream(()=>teeIterator(left),this.controller),new Stream(()=>teeIterator(right),this.controller)]}toReadableStream(){let self=this,iter,encoder=new TextEncoder;return new ReadableStream2({async start(){iter=self[Symbol.asyncIterator]()},async pull(ctrl){try{let{value,done}=await iter.next();if(done)return ctrl.close();let bytes=encoder.encode(JSON.stringify(value)+`
6
- `);ctrl.enqueue(bytes)}catch(err){ctrl.error(err)}},async cancel(){await iter.return?.()}})}}});async function toFile(value,name,options){if(value=await value,isFileLike(value))return value;if(isResponseLike(value)){let blob=await value.blob();name||(name=new URL(value.url).pathname.split(/[\\/]/).pop()??"unknown_file");let data=isBlobLike(blob)?[await blob.arrayBuffer()]:[blob];return new File2(data,name,options)}let bits=await getBytes(value);if(name||(name=getName(value)??"unknown_file"),!options?.type){let type=bits[0]?.type;if(typeof type==="string")options={...options,type}}return new File2(bits,name,options)}async function getBytes(value){let parts=[];if(typeof value==="string"||ArrayBuffer.isView(value)||value instanceof ArrayBuffer)parts.push(value);else if(isBlobLike(value))parts.push(await value.arrayBuffer());else if(isAsyncIterableIterator(value))for await(let chunk of value)parts.push(chunk);else throw Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);return parts}function propsForError(value){return`[${Object.getOwnPropertyNames(value).map((p)=>`"${p}"`).join(", ")}]`}function getName(value){return getStringFromMaybeBuffer(value.name)||getStringFromMaybeBuffer(value.filename)||getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop()}var isResponseLike=(value)=>value!=null&&typeof value==="object"&&typeof value.url==="string"&&typeof value.blob==="function",isFileLike=(value)=>value!=null&&typeof value==="object"&&typeof value.name==="string"&&typeof value.lastModified==="number"&&isBlobLike(value),isBlobLike=(value)=>value!=null&&typeof value==="object"&&typeof value.size==="number"&&typeof value.type==="string"&&typeof value.text==="function"&&typeof value.slice==="function"&&typeof value.arrayBuffer==="function",isUploadable=(value)=>{return isFileLike(value)||isResponseLike(value)||isFsReadStream(value)},getStringFromMaybeBuffer=(x)=>{if(typeof x==="string")return x;if(typeof Buffer<"u"&&x instanceof Buffer)return String(x);return},isAsyncIterableIterator=(value)=>value!=null&&typeof value==="object"&&typeof value[Symbol.asyncIterator]==="function",isMultipartBody=(body)=>body&&typeof body==="object"&&body.body&&body[Symbol.toStringTag]==="MultipartBody",multipartFormRequestOptions=async(opts)=>{let form=await createForm(opts.body);return getMultipartRequestOptions(form,opts)},createForm=async(body)=>{let form=new FormData2;return await Promise.all(Object.entries(body||{}).map(([key,value])=>addFormValue(form,key,value))),form},addFormValue=async(form,key,value)=>{if(value===void 0)return;if(value==null)throw TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);if(typeof value==="string"||typeof value==="number"||typeof value==="boolean")form.append(key,String(value));else if(isUploadable(value)){let file=await toFile(value);form.append(key,file)}else if(Array.isArray(value))await Promise.all(value.map((entry)=>addFormValue(form,key+"[]",entry)));else if(typeof value==="object")await Promise.all(Object.entries(value).map(([name,prop])=>addFormValue(form,`${key}[${name}]`,prop)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`)};var init_uploads=__esm(()=>{init__shims();init__shims()});async function defaultParseResponse(props){let{response}=props;if(props.options.stream){if(debug("response",response.status,response.url,response.headers,response.body),props.options.__streamClass)return props.options.__streamClass.fromSSEResponse(response,props.controller);return Stream.fromSSEResponse(response,props.controller)}if(response.status===204)return null;if(props.options.__binaryResponse)return response;let mediaType=response.headers.get("content-type")?.split(";")[0]?.trim();if(mediaType?.includes("application/json")||mediaType?.endsWith("+json")){let json=await response.json();return debug("response",response.status,response.url,response.headers,json),_addRequestID(json,response)}let text=await response.text();return debug("response",response.status,response.url,response.headers,text),text}function _addRequestID(value,response){if(!value||typeof value!=="object"||Array.isArray(value))return value;return Object.defineProperty(value,"_request_id",{value:response.headers.get("x-request-id"),enumerable:!1})}class APIClient{constructor({baseURL,maxRetries=2,timeout=600000,httpAgent,fetch:overriddenFetch}){this.baseURL=baseURL,this.maxRetries=validatePositiveInteger("maxRetries",maxRetries),this.timeout=validatePositiveInteger("timeout",timeout),this.httpAgent=httpAgent,this.fetch=overriddenFetch??fetch2}authHeaders(opts){return{}}defaultHeaders(opts){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...getPlatformHeaders(),...this.authHeaders(opts)}}validateHeaders(headers,customHeaders){}defaultIdempotencyKey(){return`stainless-node-retry-${uuid4()}`}get(path,opts){return this.methodRequest("get",path,opts)}post(path,opts){return this.methodRequest("post",path,opts)}patch(path,opts){return this.methodRequest("patch",path,opts)}put(path,opts){return this.methodRequest("put",path,opts)}delete(path,opts){return this.methodRequest("delete",path,opts)}methodRequest(method,path,opts){return this.request(Promise.resolve(opts).then(async(opts2)=>{let body=opts2&&isBlobLike(opts2?.body)?new DataView(await opts2.body.arrayBuffer()):opts2?.body instanceof DataView?opts2.body:opts2?.body instanceof ArrayBuffer?new DataView(opts2.body):opts2&&ArrayBuffer.isView(opts2?.body)?new DataView(opts2.body.buffer):opts2?.body;return{method,path,...opts2,body}}))}getAPIList(path,Page,opts){return this.requestAPIList(Page,{method:"get",path,...opts})}calculateContentLength(body){if(typeof body==="string"){if(typeof Buffer<"u")return Buffer.byteLength(body,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(body).length.toString()}else if(ArrayBuffer.isView(body))return body.byteLength.toString();return null}buildRequest(inputOptions,{retryCount=0}={}){let options={...inputOptions},{method,path,query,headers={}}=options,body=ArrayBuffer.isView(options.body)||options.__binaryRequest&&typeof options.body==="string"?options.body:isMultipartBody(options.body)?options.body.body:options.body?JSON.stringify(options.body,null,2):null,contentLength=this.calculateContentLength(body),url=this.buildURL(path,query);if("timeout"in options)validatePositiveInteger("timeout",options.timeout);options.timeout=options.timeout??this.timeout;let httpAgent=options.httpAgent??this.httpAgent??getDefaultAgent(url),minAgentTimeout=options.timeout+1000;if(typeof httpAgent?.options?.timeout==="number"&&minAgentTimeout>(httpAgent.options.timeout??0))httpAgent.options.timeout=minAgentTimeout;if(this.idempotencyHeader&&method!=="get"){if(!inputOptions.idempotencyKey)inputOptions.idempotencyKey=this.defaultIdempotencyKey();headers[this.idempotencyHeader]=inputOptions.idempotencyKey}let reqHeaders=this.buildHeaders({options,headers,contentLength,retryCount});return{req:{method,...body&&{body},headers:reqHeaders,...httpAgent&&{agent:httpAgent},signal:options.signal??null},url,timeout:options.timeout}}buildHeaders({options,headers,contentLength,retryCount}){let reqHeaders={};if(contentLength)reqHeaders["content-length"]=contentLength;let defaultHeaders=this.defaultHeaders(options);if(applyHeadersMut(reqHeaders,defaultHeaders),applyHeadersMut(reqHeaders,headers),isMultipartBody(options.body)&&kind!=="node")delete reqHeaders["content-type"];if(getHeader(defaultHeaders,"x-stainless-retry-count")===void 0&&getHeader(headers,"x-stainless-retry-count")===void 0)reqHeaders["x-stainless-retry-count"]=String(retryCount);if(getHeader(defaultHeaders,"x-stainless-timeout")===void 0&&getHeader(headers,"x-stainless-timeout")===void 0&&options.timeout)reqHeaders["x-stainless-timeout"]=String(Math.trunc(options.timeout/1000));return this.validateHeaders(reqHeaders,headers),reqHeaders}async prepareOptions(options){}async prepareRequest(request,{url,options}){}parseHeaders(headers){return!headers?{}:(Symbol.iterator in headers)?Object.fromEntries(Array.from(headers).map((header)=>[...header])):{...headers}}makeStatusError(status,error,message,headers){return APIError.generate(status,error,message,headers)}request(options,remainingRetries=null){return new APIPromise(this.makeRequest(options,remainingRetries))}async makeRequest(optionsInput,retriesRemaining){let options=await optionsInput,maxRetries=options.maxRetries??this.maxRetries;if(retriesRemaining==null)retriesRemaining=maxRetries;await this.prepareOptions(options);let{req,url,timeout}=this.buildRequest(options,{retryCount:maxRetries-retriesRemaining});if(await this.prepareRequest(req,{url,options}),debug("request",url,options,req.headers),options.signal?.aborted)throw new APIUserAbortError;let controller=new AbortController,response=await this.fetchWithTimeout(url,req,timeout,controller).catch(castToError);if(response instanceof Error){if(options.signal?.aborted)throw new APIUserAbortError;if(retriesRemaining)return this.retryRequest(options,retriesRemaining);if(response.name==="AbortError")throw new APIConnectionTimeoutError;throw new APIConnectionError({cause:response})}let responseHeaders=createResponseHeaders(response.headers);if(!response.ok){if(retriesRemaining&&this.shouldRetry(response)){let retryMessage2=`retrying, ${retriesRemaining} attempts remaining`;return debug(`response (error; ${retryMessage2})`,response.status,url,responseHeaders),this.retryRequest(options,retriesRemaining,responseHeaders)}let errText=await response.text().catch((e)=>castToError(e).message),errJSON=safeJSON(errText),errMessage=errJSON?void 0:errText;throw debug(`response (error; ${retriesRemaining?"(error; no more retries left)":"(error; not retryable)"})`,response.status,url,responseHeaders,errMessage),this.makeStatusError(response.status,errJSON,errMessage,responseHeaders)}return{response,options,controller}}requestAPIList(Page,options){let request=this.makeRequest(options,null);return new PagePromise(this,request,Page)}buildURL(path,query){let url=isAbsoluteURL(path)?new URL(path):new URL(this.baseURL+(this.baseURL.endsWith("/")&&path.startsWith("/")?path.slice(1):path)),defaultQuery=this.defaultQuery();if(!isEmptyObj(defaultQuery))query={...defaultQuery,...query};if(typeof query==="object"&&query&&!Array.isArray(query))url.search=this.stringifyQuery(query);return url.toString()}stringifyQuery(query){return Object.entries(query).filter(([_,value])=>typeof value<"u").map(([key,value])=>{if(typeof value==="string"||typeof value==="number"||typeof value==="boolean")return`${encodeURIComponent(key)}=${encodeURIComponent(value)}`;if(value===null)return`${encodeURIComponent(key)}=`;throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(url,init2,ms,controller){let{signal,...options}=init2||{};if(signal)signal.addEventListener("abort",()=>controller.abort());let timeout=setTimeout(()=>controller.abort(),ms),fetchOptions={signal:controller.signal,...options};if(fetchOptions.method)fetchOptions.method=fetchOptions.method.toUpperCase();return this.fetch.call(void 0,url,fetchOptions).finally(()=>{clearTimeout(timeout)})}shouldRetry(response){let shouldRetryHeader=response.headers.get("x-should-retry");if(shouldRetryHeader==="true")return!0;if(shouldRetryHeader==="false")return!1;if(response.status===408)return!0;if(response.status===409)return!0;if(response.status===429)return!0;if(response.status>=500)return!0;return!1}async retryRequest(options,retriesRemaining,responseHeaders){let timeoutMillis,retryAfterMillisHeader=responseHeaders?.["retry-after-ms"];if(retryAfterMillisHeader){let timeoutMs=parseFloat(retryAfterMillisHeader);if(!Number.isNaN(timeoutMs))timeoutMillis=timeoutMs}let retryAfterHeader=responseHeaders?.["retry-after"];if(retryAfterHeader&&!timeoutMillis){let timeoutSeconds=parseFloat(retryAfterHeader);if(!Number.isNaN(timeoutSeconds))timeoutMillis=timeoutSeconds*1000;else timeoutMillis=Date.parse(retryAfterHeader)-Date.now()}if(!(timeoutMillis&&0<=timeoutMillis&&timeoutMillis<60000)){let maxRetries=options.maxRetries??this.maxRetries;timeoutMillis=this.calculateDefaultRetryTimeoutMillis(retriesRemaining,maxRetries)}return await sleep(timeoutMillis),this.makeRequest(options,retriesRemaining-1)}calculateDefaultRetryTimeoutMillis(retriesRemaining,maxRetries){let numRetries=maxRetries-retriesRemaining,sleepSeconds=Math.min(0.5*Math.pow(2,numRetries),8),jitter=1-Math.random()*0.25;return sleepSeconds*jitter*1000}getUserAgent(){return`${this.constructor.name}/JS ${VERSION}`}}function getBrowserInfo(){if(typeof navigator>"u"||!navigator)return null;let browserPatterns=[{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,pattern}of browserPatterns){let match=pattern.exec(navigator.userAgent);if(match){let major=match[1]||0,minor=match[2]||0,patch=match[3]||0;return{browser:key,version:`${major}.${minor}.${patch}`}}}return null}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function applyHeadersMut(targetHeaders,newHeaders){for(let k in newHeaders){if(!hasOwn(newHeaders,k))continue;let lowerKey=k.toLowerCase();if(!lowerKey)continue;let val=newHeaders[k];if(val===null)delete targetHeaders[lowerKey];else if(val!==void 0)targetHeaders[lowerKey]=val}}function debug(action,...args){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let modifiedArgs=args.map((arg)=>{if(!arg)return arg;if(arg.headers){let modifiedArg2={...arg,headers:{...arg.headers}};for(let header in arg.headers)if(SENSITIVE_HEADERS.has(header.toLowerCase()))modifiedArg2.headers[header]="REDACTED";return modifiedArg2}let modifiedArg=null;for(let header in arg)if(SENSITIVE_HEADERS.has(header.toLowerCase()))modifiedArg??(modifiedArg={...arg}),modifiedArg[header]="REDACTED";return modifiedArg??arg});console.log(`OpenAI:DEBUG:${action}`,...modifiedArgs)}}function isObj(obj){return obj!=null&&typeof obj==="object"&&!Array.isArray(obj)}var __classPrivateFieldSet2=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet2=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_AbstractPage_client,APIPromise,AbstractPage,PagePromise,createResponseHeaders=(headers)=>{return new Proxy(Object.fromEntries(headers.entries()),{get(target,name){let key=name.toString();return target[key.toLowerCase()]||target[key]}})},requestOptionsKeys,isRequestOptions=(obj)=>{return typeof obj==="object"&&obj!==null&&!isEmptyObj(obj)&&Object.keys(obj).every((k)=>hasOwn(requestOptionsKeys,k))},getPlatformProperties=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(Deno.build.os),"X-Stainless-Arch":normalizeArch(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":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(process.platform),"X-Stainless-Arch":normalizeArch(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let browserInfo=getBrowserInfo();if(browserInfo)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${browserInfo.browser}`,"X-Stainless-Runtime-Version":browserInfo.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},normalizeArch=(arch)=>{if(arch==="x32")return"x32";if(arch==="x86_64"||arch==="x64")return"x64";if(arch==="arm")return"arm";if(arch==="aarch64"||arch==="arm64")return"arm64";if(arch)return`other:${arch}`;return"unknown"},normalizePlatform=(platform)=>{if(platform=platform.toLowerCase(),platform.includes("ios"))return"iOS";if(platform==="android")return"Android";if(platform==="darwin")return"MacOS";if(platform==="win32")return"Windows";if(platform==="freebsd")return"FreeBSD";if(platform==="openbsd")return"OpenBSD";if(platform==="linux")return"Linux";if(platform)return`Other:${platform}`;return"Unknown"},_platformHeaders,getPlatformHeaders=()=>{return _platformHeaders??(_platformHeaders=getPlatformProperties())},safeJSON=(text)=>{try{return JSON.parse(text)}catch(err){return}},startsWithSchemeRegexp,isAbsoluteURL=(url)=>{return startsWithSchemeRegexp.test(url)},sleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),validatePositiveInteger=(name,n)=>{if(typeof n!=="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n},castToError=(err)=>{if(err instanceof Error)return err;if(typeof err==="object"&&err!==null)try{return Error(JSON.stringify(err))}catch{}return Error(err)},readEnv=(env)=>{if(typeof process<"u")return process.env?.[env]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(env)?.trim();return},SENSITIVE_HEADERS,uuid4=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(c)=>{let r=Math.random()*16|0;return(c==="x"?r:r&3|8).toString(16)})},isRunningInBrowser=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},isHeadersProtocol=(headers)=>{return typeof headers?.get==="function"},getHeader=(headers,header)=>{let lowerCasedHeader=header.toLowerCase();if(isHeadersProtocol(headers)){let intercapsHeader=header[0]?.toUpperCase()+header.substring(1).replace(/([^\w])(\w)/g,(_m,g1,g2)=>g1+g2.toUpperCase());for(let key of[header,lowerCasedHeader,header.toUpperCase(),intercapsHeader]){let value=headers.get(key);if(value)return value}}for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===lowerCasedHeader){if(Array.isArray(value)){if(value.length<=1)return value[0];return console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`),value[0]}return value}return},toFloat32Array=(base64Str)=>{if(typeof Buffer<"u"){let buf=Buffer.from(base64Str,"base64");return Array.from(new Float32Array(buf.buffer,buf.byteOffset,buf.length/Float32Array.BYTES_PER_ELEMENT))}else{let binaryStr=atob(base64Str),len=binaryStr.length,bytes=new Uint8Array(len);for(let i=0;i<len;i++)bytes[i]=binaryStr.charCodeAt(i);return Array.from(new Float32Array(bytes.buffer))}};var init_core=__esm(()=>{init_streaming();init_error();init__shims();init_uploads();init_uploads();init();APIPromise=class APIPromise extends Promise{constructor(responsePromise,parseResponse=defaultParseResponse){super((resolve)=>{resolve(null)});this.responsePromise=responsePromise,this.parseResponse=parseResponse}_thenUnwrap(transform){return new APIPromise(this.responsePromise,async(props)=>_addRequestID(transform(await this.parseResponse(props),props),props.response))}asResponse(){return this.responsePromise.then((p)=>p.response)}async withResponse(){let[data,response]=await Promise.all([this.parse(),this.asResponse()]);return{data,response,request_id:response.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(onfulfilled,onrejected){return this.parse().then(onfulfilled,onrejected)}catch(onrejected){return this.parse().catch(onrejected)}finally(onfinally){return this.parse().finally(onfinally)}};AbstractPage=class AbstractPage{constructor(client,response,body,options){_AbstractPage_client.set(this,void 0),__classPrivateFieldSet2(this,_AbstractPage_client,client,"f"),this.options=options,this.response=response,this.body=body}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let nextInfo=this.nextPageInfo();if(!nextInfo)throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let nextOptions={...this.options};if("params"in nextInfo&&typeof nextOptions.query==="object")nextOptions.query={...nextOptions.query,...nextInfo.params};else if("url"in nextInfo){let params=[...Object.entries(nextOptions.query||{}),...nextInfo.url.searchParams.entries()];for(let[key,value]of params)nextInfo.url.searchParams.set(key,value);nextOptions.query=void 0,nextOptions.path=nextInfo.url.toString()}return await __classPrivateFieldGet2(this,_AbstractPage_client,"f").requestAPIList(this.constructor,nextOptions)}async*iterPages(){let page=this;yield page;while(page.hasNextPage())page=await page.getNextPage(),yield page}async*[(_AbstractPage_client=new WeakMap,Symbol.asyncIterator)](){for await(let page of this.iterPages())for(let item of page.getPaginatedItems())yield item}};PagePromise=class PagePromise extends APIPromise{constructor(client,request,Page){super(request,async(props)=>new Page(client,props.response,await defaultParseResponse(props),props.options))}async*[Symbol.asyncIterator](){let page=await this;for await(let item of page)yield item}};requestOptionsKeys={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0};startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i;SENSITIVE_HEADERS=new Set(["authorization","api-key"])});var Page,CursorPage;var init_pagination=__esm(()=>{init_core();Page=class Page extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.object=body.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}};CursorPage=class CursorPage extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.has_more=body.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let info=this.nextPageInfo();if(!info)return null;if("params"in info)return info.params;let params=Object.fromEntries(info.url.searchParams);if(!Object.keys(params).length)return null;return params}nextPageInfo(){let data=this.getPaginatedItems();if(!data.length)return null;let id=data[data.length-1]?.id;if(!id)return null;return{params:{after:id}}}}});class APIResource{constructor(client){this._client=client}}var Messages;var init_messages=__esm(()=>{init_core();init_completions();Messages=class Messages extends APIResource{list(completionId,query={},options){if(isRequestOptions(query))return this.list(completionId,{},query);return this._client.getAPIList(`/chat/completions/${completionId}/messages`,ChatCompletionStoreMessagesPage,{query,...options})}}});var Completions,ChatCompletionsPage,ChatCompletionStoreMessagesPage;var init_completions=__esm(()=>{init_core();init_messages();init_messages();init_pagination();Completions=class Completions extends APIResource{constructor(){super(...arguments);this.messages=new Messages(this._client)}create(body,options){return this._client.post("/chat/completions",{body,...options,stream:body.stream??!1})}retrieve(completionId,options){return this._client.get(`/chat/completions/${completionId}`,options)}update(completionId,body,options){return this._client.post(`/chat/completions/${completionId}`,{body,...options})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/chat/completions",ChatCompletionsPage,{query,...options})}del(completionId,options){return this._client.delete(`/chat/completions/${completionId}`,options)}};ChatCompletionsPage=class ChatCompletionsPage extends CursorPage{};ChatCompletionStoreMessagesPage=class ChatCompletionStoreMessagesPage extends CursorPage{};Completions.ChatCompletionsPage=ChatCompletionsPage;Completions.Messages=Messages});var Chat;var init_chat=__esm(()=>{init_completions();init_completions();Chat=class Chat extends APIResource{constructor(){super(...arguments);this.completions=new Completions(this._client)}};Chat.Completions=Completions;Chat.ChatCompletionsPage=ChatCompletionsPage});var init_chat2=__esm(()=>{init_chat()});var init_shared=()=>{};var Speech;var init_speech=__esm(()=>{Speech=class Speech extends APIResource{create(body,options){return this._client.post("/audio/speech",{body,...options,headers:{Accept:"application/octet-stream",...options?.headers},__binaryResponse:!0})}}});var Transcriptions;var init_transcriptions=__esm(()=>{init_core();Transcriptions=class Transcriptions extends APIResource{create(body,options){return this._client.post("/audio/transcriptions",multipartFormRequestOptions({body,...options,stream:body.stream??!1,__metadata:{model:body.model}}))}}});var Translations;var init_translations=__esm(()=>{init_core();Translations=class Translations extends APIResource{create(body,options){return this._client.post("/audio/translations",multipartFormRequestOptions({body,...options,__metadata:{model:body.model}}))}}});var Audio;var init_audio=__esm(()=>{init_speech();init_speech();init_transcriptions();init_transcriptions();init_translations();init_translations();Audio=class Audio extends APIResource{constructor(){super(...arguments);this.transcriptions=new Transcriptions(this._client),this.translations=new Translations(this._client),this.speech=new Speech(this._client)}};Audio.Transcriptions=Transcriptions;Audio.Translations=Translations;Audio.Speech=Speech});var Batches,BatchesPage;var init_batches=__esm(()=>{init_core();init_pagination();Batches=class Batches extends APIResource{create(body,options){return this._client.post("/batches",{body,...options})}retrieve(batchId,options){return this._client.get(`/batches/${batchId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/batches",BatchesPage,{query,...options})}cancel(batchId,options){return this._client.post(`/batches/${batchId}/cancel`,options)}};BatchesPage=class BatchesPage extends CursorPage{};Batches.BatchesPage=BatchesPage});class EventStream{constructor(){_EventStream_instances.add(this),this.controller=new AbortController,_EventStream_connectedPromise.set(this,void 0),_EventStream_resolveConnectedPromise.set(this,()=>{}),_EventStream_rejectConnectedPromise.set(this,()=>{}),_EventStream_endPromise.set(this,void 0),_EventStream_resolveEndPromise.set(this,()=>{}),_EventStream_rejectEndPromise.set(this,()=>{}),_EventStream_listeners.set(this,{}),_EventStream_ended.set(this,!1),_EventStream_errored.set(this,!1),_EventStream_aborted.set(this,!1),_EventStream_catchingPromiseCreated.set(this,!1),__classPrivateFieldSet3(this,_EventStream_connectedPromise,new Promise((resolve,reject)=>{__classPrivateFieldSet3(this,_EventStream_resolveConnectedPromise,resolve,"f"),__classPrivateFieldSet3(this,_EventStream_rejectConnectedPromise,reject,"f")}),"f"),__classPrivateFieldSet3(this,_EventStream_endPromise,new Promise((resolve,reject)=>{__classPrivateFieldSet3(this,_EventStream_resolveEndPromise,resolve,"f"),__classPrivateFieldSet3(this,_EventStream_rejectEndPromise,reject,"f")}),"f"),__classPrivateFieldGet3(this,_EventStream_connectedPromise,"f").catch(()=>{}),__classPrivateFieldGet3(this,_EventStream_endPromise,"f").catch(()=>{})}_run(executor){setTimeout(()=>{executor().then(()=>{this._emitFinal(),this._emit("end")},__classPrivateFieldGet3(this,_EventStream_instances,"m",_EventStream_handleError).bind(this))},0)}_connected(){if(this.ended)return;__classPrivateFieldGet3(this,_EventStream_resolveConnectedPromise,"f").call(this),this._emit("connect")}get ended(){return __classPrivateFieldGet3(this,_EventStream_ended,"f")}get errored(){return __classPrivateFieldGet3(this,_EventStream_errored,"f")}get aborted(){return __classPrivateFieldGet3(this,_EventStream_aborted,"f")}abort(){this.controller.abort()}on(event,listener){return(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]||(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]=[])).push({listener}),this}off(event,listener){let listeners=__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event];if(!listeners)return this;let index=listeners.findIndex((l)=>l.listener===listener);if(index>=0)listeners.splice(index,1);return this}once(event,listener){return(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]||(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]=[])).push({listener,once:!0}),this}emitted(event){return new Promise((resolve,reject)=>{if(__classPrivateFieldSet3(this,_EventStream_catchingPromiseCreated,!0,"f"),event!=="error")this.once("error",reject);this.once(event,resolve)})}async done(){__classPrivateFieldSet3(this,_EventStream_catchingPromiseCreated,!0,"f"),await __classPrivateFieldGet3(this,_EventStream_endPromise,"f")}_emit(event,...args){if(__classPrivateFieldGet3(this,_EventStream_ended,"f"))return;if(event==="end")__classPrivateFieldSet3(this,_EventStream_ended,!0,"f"),__classPrivateFieldGet3(this,_EventStream_resolveEndPromise,"f").call(this);let listeners=__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event];if(listeners)__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]=listeners.filter((l)=>!l.once),listeners.forEach(({listener})=>listener(...args));if(event==="abort"){let error=args[0];if(!__classPrivateFieldGet3(this,_EventStream_catchingPromiseCreated,"f")&&!listeners?.length)Promise.reject(error);__classPrivateFieldGet3(this,_EventStream_rejectConnectedPromise,"f").call(this,error),__classPrivateFieldGet3(this,_EventStream_rejectEndPromise,"f").call(this,error),this._emit("end");return}if(event==="error"){let error=args[0];if(!__classPrivateFieldGet3(this,_EventStream_catchingPromiseCreated,"f")&&!listeners?.length)Promise.reject(error);__classPrivateFieldGet3(this,_EventStream_rejectConnectedPromise,"f").call(this,error),__classPrivateFieldGet3(this,_EventStream_rejectEndPromise,"f").call(this,error),this._emit("end")}}_emitFinal(){}}var __classPrivateFieldSet3=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet3=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_EventStream_instances,_EventStream_connectedPromise,_EventStream_resolveConnectedPromise,_EventStream_rejectConnectedPromise,_EventStream_endPromise,_EventStream_resolveEndPromise,_EventStream_rejectEndPromise,_EventStream_listeners,_EventStream_ended,_EventStream_errored,_EventStream_aborted,_EventStream_catchingPromiseCreated,_EventStream_handleError;var init_EventStream=__esm(()=>{init_error();_EventStream_connectedPromise=new WeakMap,_EventStream_resolveConnectedPromise=new WeakMap,_EventStream_rejectConnectedPromise=new WeakMap,_EventStream_endPromise=new WeakMap,_EventStream_resolveEndPromise=new WeakMap,_EventStream_rejectEndPromise=new WeakMap,_EventStream_listeners=new WeakMap,_EventStream_ended=new WeakMap,_EventStream_errored=new WeakMap,_EventStream_aborted=new WeakMap,_EventStream_catchingPromiseCreated=new WeakMap,_EventStream_instances=new WeakSet,_EventStream_handleError=function(error){if(__classPrivateFieldSet3(this,_EventStream_errored,!0,"f"),error instanceof Error&&error.name==="AbortError")error=new APIUserAbortError;if(error instanceof APIUserAbortError)return __classPrivateFieldSet3(this,_EventStream_aborted,!0,"f"),this._emit("abort",error);if(error instanceof OpenAIError)return this._emit("error",error);if(error instanceof Error){let openAIError=new OpenAIError(error.message);return openAIError.cause=error,this._emit("error",openAIError)}return this._emit("error",new OpenAIError(String(error)))}});function assertNever(_x){}var __classPrivateFieldGet4=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},__classPrivateFieldSet4=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},_AssistantStream_instances,_AssistantStream_events,_AssistantStream_runStepSnapshots,_AssistantStream_messageSnapshots,_AssistantStream_messageSnapshot,_AssistantStream_finalRun,_AssistantStream_currentContentIndex,_AssistantStream_currentContent,_AssistantStream_currentToolCallIndex,_AssistantStream_currentToolCall,_AssistantStream_currentEvent,_AssistantStream_currentRunSnapshot,_AssistantStream_currentRunStepSnapshot,_AssistantStream_addEvent,_AssistantStream_endRequest,_AssistantStream_handleMessage,_AssistantStream_handleRunStep,_AssistantStream_handleEvent,_AssistantStream_accumulateRunStep,_AssistantStream_accumulateMessage,_AssistantStream_accumulateContent,_AssistantStream_handleRun,AssistantStream;var init_AssistantStream=__esm(()=>{init_core();init_streaming();init_error();init_EventStream();AssistantStream=class AssistantStream extends EventStream{constructor(){super(...arguments);_AssistantStream_instances.add(this),_AssistantStream_events.set(this,[]),_AssistantStream_runStepSnapshots.set(this,{}),_AssistantStream_messageSnapshots.set(this,{}),_AssistantStream_messageSnapshot.set(this,void 0),_AssistantStream_finalRun.set(this,void 0),_AssistantStream_currentContentIndex.set(this,void 0),_AssistantStream_currentContent.set(this,void 0),_AssistantStream_currentToolCallIndex.set(this,void 0),_AssistantStream_currentToolCall.set(this,void 0),_AssistantStream_currentEvent.set(this,void 0),_AssistantStream_currentRunSnapshot.set(this,void 0),_AssistantStream_currentRunStepSnapshot.set(this,void 0)}[(_AssistantStream_events=new WeakMap,_AssistantStream_runStepSnapshots=new WeakMap,_AssistantStream_messageSnapshots=new WeakMap,_AssistantStream_messageSnapshot=new WeakMap,_AssistantStream_finalRun=new WeakMap,_AssistantStream_currentContentIndex=new WeakMap,_AssistantStream_currentContent=new WeakMap,_AssistantStream_currentToolCallIndex=new WeakMap,_AssistantStream_currentToolCall=new WeakMap,_AssistantStream_currentEvent=new WeakMap,_AssistantStream_currentRunSnapshot=new WeakMap,_AssistantStream_currentRunStepSnapshot=new WeakMap,_AssistantStream_instances=new WeakSet,Symbol.asyncIterator)](){let pushQueue=[],readQueue=[],done=!1;return this.on("event",(event)=>{let reader=readQueue.shift();if(reader)reader.resolve(event);else pushQueue.push(event)}),this.on("end",()=>{done=!0;for(let reader of readQueue)reader.resolve(void 0);readQueue.length=0}),this.on("abort",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),this.on("error",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),{next:async()=>{if(!pushQueue.length){if(done)return{value:void 0,done:!0};return new Promise((resolve,reject)=>readQueue.push({resolve,reject})).then((chunk2)=>chunk2?{value:chunk2,done:!1}:{value:void 0,done:!0})}return{value:pushQueue.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(stream){let runner=new AssistantStream;return runner._run(()=>runner._fromReadableStream(stream)),runner}async _fromReadableStream(readableStream,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller);for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(threadId,runId,runs,params,options){let runner=new AssistantStream;return runner._run(()=>runner._runToolAssistantStream(threadId,runId,runs,params,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}async _createToolAssistantStream(run,threadId,runId,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}let body={...params,stream:!0},stream=await run.submitToolOutputs(threadId,runId,body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static createThreadAssistantStream(params,thread,options){let runner=new AssistantStream;return runner._run(()=>runner._threadAssistantStream(params,thread,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}static createAssistantStream(threadId,runs,params,options){let runner=new AssistantStream;return runner._run(()=>runner._runAssistantStream(threadId,runs,params,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}currentEvent(){return __classPrivateFieldGet4(this,_AssistantStream_currentEvent,"f")}currentRun(){return __classPrivateFieldGet4(this,_AssistantStream_currentRunSnapshot,"f")}currentMessageSnapshot(){return __classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f")}currentRunStepSnapshot(){return __classPrivateFieldGet4(this,_AssistantStream_currentRunStepSnapshot,"f")}async finalRunSteps(){return await this.done(),Object.values(__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f"))}async finalMessages(){return await this.done(),Object.values(__classPrivateFieldGet4(this,_AssistantStream_messageSnapshots,"f"))}async finalRun(){if(await this.done(),!__classPrivateFieldGet4(this,_AssistantStream_finalRun,"f"))throw Error("Final run was not received.");return __classPrivateFieldGet4(this,_AssistantStream_finalRun,"f")}async _createThreadAssistantStream(thread,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}let body={...params,stream:!0},stream=await thread.createAndRun(body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}async _createAssistantStream(run,threadId,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}let body={...params,stream:!0},stream=await run.create(threadId,body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static accumulateDelta(acc,delta){for(let[key,deltaValue]of Object.entries(delta)){if(!acc.hasOwnProperty(key)){acc[key]=deltaValue;continue}let accValue=acc[key];if(accValue===null||accValue===void 0){acc[key]=deltaValue;continue}if(key==="index"||key==="type"){acc[key]=deltaValue;continue}if(typeof accValue==="string"&&typeof deltaValue==="string")accValue+=deltaValue;else if(typeof accValue==="number"&&typeof deltaValue==="number")accValue+=deltaValue;else if(isObj(accValue)&&isObj(deltaValue))accValue=this.accumulateDelta(accValue,deltaValue);else if(Array.isArray(accValue)&&Array.isArray(deltaValue)){if(accValue.every((x)=>typeof x==="string"||typeof x==="number")){accValue.push(...deltaValue);continue}for(let deltaEntry of deltaValue){if(!isObj(deltaEntry))throw Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);let index=deltaEntry.index;if(index==null)throw console.error(deltaEntry),Error("Expected array delta entry to have an `index` property");if(typeof index!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${index}`);let accEntry=accValue[index];if(accEntry==null)accValue.push(deltaEntry);else accValue[index]=this.accumulateDelta(accEntry,deltaEntry)}continue}else throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);acc[key]=accValue}return acc}_addRun(run){return run}async _threadAssistantStream(params,thread,options){return await this._createThreadAssistantStream(thread,params,options)}async _runAssistantStream(threadId,runs,params,options){return await this._createAssistantStream(runs,threadId,params,options)}async _runToolAssistantStream(threadId,runId,runs,params,options){return await this._createToolAssistantStream(runs,threadId,runId,params,options)}};_AssistantStream_addEvent=function(event){if(this.ended)return;switch(__classPrivateFieldSet4(this,_AssistantStream_currentEvent,event,"f"),__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleEvent).call(this,event),event.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":__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleRun).call(this,event);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":__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleRunStep).call(this,event);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleMessage).call(this,event);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:assertNever(event)}},_AssistantStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");if(!__classPrivateFieldGet4(this,_AssistantStream_finalRun,"f"))throw Error("Final run has not been received");return __classPrivateFieldGet4(this,_AssistantStream_finalRun,"f")},_AssistantStream_handleMessage=function(event){let[accumulatedMessage,newContent]=__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_accumulateMessage).call(this,event,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));__classPrivateFieldSet4(this,_AssistantStream_messageSnapshot,accumulatedMessage,"f"),__classPrivateFieldGet4(this,_AssistantStream_messageSnapshots,"f")[accumulatedMessage.id]=accumulatedMessage;for(let content of newContent){let snapshotContent=accumulatedMessage.content[content.index];if(snapshotContent?.type=="text")this._emit("textCreated",snapshotContent.text)}switch(event.event){case"thread.message.created":this._emit("messageCreated",event.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",event.data.delta,accumulatedMessage),event.data.delta.content)for(let content of event.data.delta.content){if(content.type=="text"&&content.text){let textDelta=content.text,snapshot=accumulatedMessage.content[content.index];if(snapshot&&snapshot.type=="text")this._emit("textDelta",textDelta,snapshot.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(content.index!=__classPrivateFieldGet4(this,_AssistantStream_currentContentIndex,"f")){if(__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f"))switch(__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f").type){case"text":this._emit("textDone",__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f").text,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break;case"image_file":this._emit("imageFileDone",__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f").image_file,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break}__classPrivateFieldSet4(this,_AssistantStream_currentContentIndex,content.index,"f")}__classPrivateFieldSet4(this,_AssistantStream_currentContent,accumulatedMessage.content[content.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(__classPrivateFieldGet4(this,_AssistantStream_currentContentIndex,"f")!==void 0){let currentContent=event.data.content[__classPrivateFieldGet4(this,_AssistantStream_currentContentIndex,"f")];if(currentContent)switch(currentContent.type){case"image_file":this._emit("imageFileDone",currentContent.image_file,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break;case"text":this._emit("textDone",currentContent.text,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break}}if(__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"))this._emit("messageDone",event.data);__classPrivateFieldSet4(this,_AssistantStream_messageSnapshot,void 0,"f")}},_AssistantStream_handleRunStep=function(event){let accumulatedRunStep=__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_accumulateRunStep).call(this,event);switch(__classPrivateFieldSet4(this,_AssistantStream_currentRunStepSnapshot,accumulatedRunStep,"f"),event.event){case"thread.run.step.created":this._emit("runStepCreated",event.data);break;case"thread.run.step.delta":let delta=event.data.delta;if(delta.step_details&&delta.step_details.type=="tool_calls"&&delta.step_details.tool_calls&&accumulatedRunStep.step_details.type=="tool_calls")for(let toolCall of delta.step_details.tool_calls)if(toolCall.index==__classPrivateFieldGet4(this,_AssistantStream_currentToolCallIndex,"f"))this._emit("toolCallDelta",toolCall,accumulatedRunStep.step_details.tool_calls[toolCall.index]);else{if(__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallDone",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"));if(__classPrivateFieldSet4(this,_AssistantStream_currentToolCallIndex,toolCall.index,"f"),__classPrivateFieldSet4(this,_AssistantStream_currentToolCall,accumulatedRunStep.step_details.tool_calls[toolCall.index],"f"),__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallCreated",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))}this._emit("runStepDelta",event.data.delta,accumulatedRunStep);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(__classPrivateFieldSet4(this,_AssistantStream_currentRunStepSnapshot,void 0,"f"),event.data.step_details.type=="tool_calls"){if(__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallDone",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet4(this,_AssistantStream_currentToolCall,void 0,"f")}this._emit("runStepDone",event.data,accumulatedRunStep);break;case"thread.run.step.in_progress":break}},_AssistantStream_handleEvent=function(event){__classPrivateFieldGet4(this,_AssistantStream_events,"f").push(event),this._emit("event",event)},_AssistantStream_accumulateRunStep=function(event){switch(event.event){case"thread.run.step.created":return __classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id]=event.data,event.data;case"thread.run.step.delta":let snapshot=__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id];if(!snapshot)throw Error("Received a RunStepDelta before creation of a snapshot");let data=event.data;if(data.delta){let accumulated=AssistantStream.accumulateDelta(snapshot,data.delta);__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id]=accumulated}return __classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.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":__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id]=event.data;break}if(__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id])return __classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id];throw Error("No snapshot available")},_AssistantStream_accumulateMessage=function(event,snapshot){let newContent=[];switch(event.event){case"thread.message.created":return[event.data,newContent];case"thread.message.delta":if(!snapshot)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let data=event.data;if(data.delta.content)for(let contentElement of data.delta.content)if(contentElement.index in snapshot.content){let currentContent=snapshot.content[contentElement.index];snapshot.content[contentElement.index]=__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_accumulateContent).call(this,contentElement,currentContent)}else snapshot.content[contentElement.index]=contentElement,newContent.push(contentElement);return[snapshot,newContent];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(snapshot)return[snapshot,newContent];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_AssistantStream_accumulateContent=function(contentElement,currentContent){return AssistantStream.accumulateDelta(currentContent,contentElement)},_AssistantStream_handleRun=function(event){switch(__classPrivateFieldSet4(this,_AssistantStream_currentRunSnapshot,event.data,"f"),event.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":if(__classPrivateFieldSet4(this,_AssistantStream_finalRun,event.data,"f"),__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallDone",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet4(this,_AssistantStream_currentToolCall,void 0,"f");break;case"thread.run.cancelling":break}}});var Assistants,AssistantsPage;var init_assistants=__esm(()=>{init_core();init_pagination();Assistants=class Assistants extends APIResource{create(body,options){return this._client.post("/assistants",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(assistantId,options){return this._client.get(`/assistants/${assistantId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(assistantId,body,options){return this._client.post(`/assistants/${assistantId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/assistants",AssistantsPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(assistantId,options){return this._client.delete(`/assistants/${assistantId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};AssistantsPage=class AssistantsPage extends CursorPage{};Assistants.AssistantsPage=AssistantsPage});function isRunnableFunctionWithParse(fn){return typeof fn.parse==="function"}var isAssistantMessage=(message)=>{return message?.role==="assistant"},isFunctionMessage=(message)=>{return message?.role==="function"},isToolMessage=(message)=>{return message?.role==="tool"};function isAutoParsableResponseFormat(response_format){return response_format?.$brand==="auto-parseable-response-format"}function isAutoParsableTool(tool){return tool?.$brand==="auto-parseable-tool"}function maybeParseChatCompletion(completion,params){if(!params||!hasAutoParseableInput(params))return{...completion,choices:completion.choices.map((choice)=>({...choice,message:{...choice.message,parsed:null,...choice.message.tool_calls?{tool_calls:choice.message.tool_calls}:void 0}}))};return parseChatCompletion(completion,params)}function parseChatCompletion(completion,params){let choices=completion.choices.map((choice)=>{if(choice.finish_reason==="length")throw new LengthFinishReasonError;if(choice.finish_reason==="content_filter")throw new ContentFilterFinishReasonError;return{...choice,message:{...choice.message,...choice.message.tool_calls?{tool_calls:choice.message.tool_calls?.map((toolCall)=>parseToolCall(params,toolCall))??void 0}:void 0,parsed:choice.message.content&&!choice.message.refusal?parseResponseFormat(params,choice.message.content):null}}});return{...completion,choices}}function parseResponseFormat(params,content){if(params.response_format?.type!=="json_schema")return null;if(params.response_format?.type==="json_schema"){if("$parseRaw"in params.response_format)return params.response_format.$parseRaw(content);return JSON.parse(content)}return null}function parseToolCall(params,toolCall){let inputTool=params.tools?.find((inputTool2)=>inputTool2.function?.name===toolCall.function.name);return{...toolCall,function:{...toolCall.function,parsed_arguments:isAutoParsableTool(inputTool)?inputTool.$parseRaw(toolCall.function.arguments):inputTool?.function.strict?JSON.parse(toolCall.function.arguments):null}}}function shouldParseToolCall(params,toolCall){if(!params)return!1;let inputTool=params.tools?.find((inputTool2)=>inputTool2.function?.name===toolCall.function.name);return isAutoParsableTool(inputTool)||inputTool?.function.strict||!1}function hasAutoParseableInput(params){if(isAutoParsableResponseFormat(params.response_format))return!0;return params.tools?.some((t)=>isAutoParsableTool(t)||t.type==="function"&&t.function.strict===!0)??!1}function validateInputTools(tools){for(let tool of tools??[]){if(tool.type!=="function")throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``);if(tool.function.strict!==!0)throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var init_parser=__esm(()=>{init_error()});var __classPrivateFieldGet5=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_AbstractChatCompletionRunner_instances,_AbstractChatCompletionRunner_getFinalContent,_AbstractChatCompletionRunner_getFinalMessage,_AbstractChatCompletionRunner_getFinalFunctionCall,_AbstractChatCompletionRunner_getFinalFunctionCallResult,_AbstractChatCompletionRunner_calculateTotalUsage,_AbstractChatCompletionRunner_validateParams,_AbstractChatCompletionRunner_stringifyFunctionCallResult,DEFAULT_MAX_CHAT_COMPLETIONS=10,AbstractChatCompletionRunner;var init_AbstractChatCompletionRunner=__esm(()=>{init_error();init_EventStream();init_parser();AbstractChatCompletionRunner=class AbstractChatCompletionRunner extends EventStream{constructor(){super(...arguments);_AbstractChatCompletionRunner_instances.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(chatCompletion){this._chatCompletions.push(chatCompletion),this._emit("chatCompletion",chatCompletion);let message=chatCompletion.choices[0]?.message;if(message)this._addMessage(message);return chatCompletion}_addMessage(message,emit=!0){if(!("content"in message))message.content=null;if(this.messages.push(message),emit){if(this._emit("message",message),(isFunctionMessage(message)||isToolMessage(message))&&message.content)this._emit("functionCallResult",message.content);else if(isAssistantMessage(message)&&message.function_call)this._emit("functionCall",message.function_call);else if(isAssistantMessage(message)&&message.tool_calls){for(let tool_call of message.tool_calls)if(tool_call.type==="function")this._emit("functionCall",tool_call.function)}}}async finalChatCompletion(){await this.done();let completion=this._chatCompletions[this._chatCompletions.length-1];if(!completion)throw new OpenAIError("stream ended without producing a ChatCompletion");return completion}async finalContent(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this)}async finalMessage(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this)}async finalFunctionCall(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCall).call(this)}async finalFunctionCallResult(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this)}async totalUsage(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let completion=this._chatCompletions[this._chatCompletions.length-1];if(completion)this._emit("finalChatCompletion",completion);let finalMessage=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this);if(finalMessage)this._emit("finalMessage",finalMessage);let finalContent=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this);if(finalContent)this._emit("finalContent",finalContent);let finalFunctionCall=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCall).call(this);if(finalFunctionCall)this._emit("finalFunctionCall",finalFunctionCall);let finalFunctionCallResult=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);if(finalFunctionCallResult!=null)this._emit("finalFunctionCallResult",finalFunctionCallResult);if(this._chatCompletions.some((c)=>c.usage))this._emit("totalUsage",__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this))}async _createChatCompletion(client,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_validateParams).call(this,params);let chatCompletion=await client.chat.completions.create({...params,stream:!1},{...options,signal:this.controller.signal});return this._connected(),this._addChatCompletion(parseChatCompletion(chatCompletion,params))}async _runChatCompletion(client,params,options){for(let message of params.messages)this._addMessage(message,!1);return await this._createChatCompletion(client,params,options)}async _runFunctions(client,params,options){let{function_call="auto",stream,...restParams}=params,singleFunctionToCall=typeof function_call!=="string"&&function_call?.name,{maxChatCompletions=DEFAULT_MAX_CHAT_COMPLETIONS}=options||{},functionsByName={};for(let f of params.functions)functionsByName[f.name||f.function.name]=f;let functions=params.functions.map((f)=>({name:f.name||f.function.name,parameters:f.parameters,description:f.description}));for(let message of params.messages)this._addMessage(message,!1);for(let i=0;i<maxChatCompletions;++i){let message=(await this._createChatCompletion(client,{...restParams,function_call,functions,messages:[...this.messages]},options)).choices[0]?.message;if(!message)throw new OpenAIError("missing message in ChatCompletion response");if(!message.function_call)return;let{name,arguments:args}=message.function_call,fn=functionsByName[name];if(!fn){let content2=`Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions.map((f)=>JSON.stringify(f.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name,content:content2});continue}else if(singleFunctionToCall&&singleFunctionToCall!==name){let content2=`Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;this._addMessage({role:"function",name,content:content2});continue}let parsed;try{parsed=isRunnableFunctionWithParse(fn)?await fn.parse(args):args}catch(error){this._addMessage({role:"function",name,content:error instanceof Error?error.message:String(error)});continue}let rawContent=await fn.function(parsed,this),content=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this,rawContent);if(this._addMessage({role:"function",name,content}),singleFunctionToCall)return}}async _runTools(client,params,options){let{tool_choice="auto",stream,...restParams}=params,singleFunctionToCall=typeof tool_choice!=="string"&&tool_choice?.function?.name,{maxChatCompletions=DEFAULT_MAX_CHAT_COMPLETIONS}=options||{},inputTools=params.tools.map((tool)=>{if(isAutoParsableTool(tool)){if(!tool.$callback)throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:tool.$callback,name:tool.function.name,description:tool.function.description||"",parameters:tool.function.parameters,parse:tool.$parseRaw,strict:!0}}}return tool}),functionsByName={};for(let f of inputTools)if(f.type==="function")functionsByName[f.function.name||f.function.function.name]=f.function;let tools="tools"in params?inputTools.map((t)=>t.type==="function"?{type:"function",function:{name:t.function.name||t.function.function.name,parameters:t.function.parameters,description:t.function.description,strict:t.function.strict}}:t):void 0;for(let message of params.messages)this._addMessage(message,!1);for(let i=0;i<maxChatCompletions;++i){let message=(await this._createChatCompletion(client,{...restParams,tool_choice,tools,messages:[...this.messages]},options)).choices[0]?.message;if(!message)throw new OpenAIError("missing message in ChatCompletion response");if(!message.tool_calls?.length)return;for(let tool_call of message.tool_calls){if(tool_call.type!=="function")continue;let tool_call_id=tool_call.id,{name,arguments:args}=tool_call.function,fn=functionsByName[name];if(!fn){let content2=`Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2)=>JSON.stringify(name2)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id,content:content2});continue}else if(singleFunctionToCall&&singleFunctionToCall!==name){let content2=`Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id,content:content2});continue}let parsed;try{parsed=isRunnableFunctionWithParse(fn)?await fn.parse(args):args}catch(error){let content2=error instanceof Error?error.message:String(error);this._addMessage({role:"tool",tool_call_id,content:content2});continue}let rawContent=await fn.function(parsed,this),content=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this,rawContent);if(this._addMessage({role:"tool",tool_call_id,content}),singleFunctionToCall)return}}return}};_AbstractChatCompletionRunner_instances=new WeakSet,_AbstractChatCompletionRunner_getFinalContent=function(){return __classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this).content??null},_AbstractChatCompletionRunner_getFinalMessage=function(){let i=this.messages.length;while(i-- >0){let message=this.messages[i];if(isAssistantMessage(message)){let{function_call,...rest}=message,ret={...rest,content:message.content??null,refusal:message.refusal??null};if(function_call)ret.function_call=function_call;return ret}}throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant")},_AbstractChatCompletionRunner_getFinalFunctionCall=function(){for(let i=this.messages.length-1;i>=0;i--){let message=this.messages[i];if(isAssistantMessage(message)&&message?.function_call)return message.function_call;if(isAssistantMessage(message)&&message?.tool_calls?.length)return message.tool_calls.at(-1)?.function}return},_AbstractChatCompletionRunner_getFinalFunctionCallResult=function(){for(let i=this.messages.length-1;i>=0;i--){let message=this.messages[i];if(isFunctionMessage(message)&&message.content!=null)return message.content;if(isToolMessage(message)&&message.content!=null&&typeof message.content==="string"&&this.messages.some((x)=>x.role==="assistant"&&x.tool_calls?.some((y)=>y.type==="function"&&y.id===message.tool_call_id)))return message.content}return},_AbstractChatCompletionRunner_calculateTotalUsage=function(){let total={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage}of this._chatCompletions)if(usage)total.completion_tokens+=usage.completion_tokens,total.prompt_tokens+=usage.prompt_tokens,total.total_tokens+=usage.total_tokens;return total},_AbstractChatCompletionRunner_validateParams=function(params){if(params.n!=null&&params.n>1)throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_AbstractChatCompletionRunner_stringifyFunctionCallResult=function(rawContent){return typeof rawContent==="string"?rawContent:rawContent===void 0?"undefined":JSON.stringify(rawContent)}});var ChatCompletionRunner;var init_ChatCompletionRunner=__esm(()=>{init_AbstractChatCompletionRunner();ChatCompletionRunner=class ChatCompletionRunner extends AbstractChatCompletionRunner{static runFunctions(client,params,options){let runner=new ChatCompletionRunner,opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return runner._run(()=>runner._runFunctions(client,params,opts)),runner}static runTools(client,params,options){let runner=new ChatCompletionRunner,opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runTools"}};return runner._run(()=>runner._runTools(client,params,opts)),runner}_addMessage(message,emit=!0){if(super._addMessage(message,emit),isAssistantMessage(message)&&message.content)this._emit("content",message.content)}}});function parseJSON(jsonString,allowPartial=Allow.ALL){if(typeof jsonString!=="string")throw TypeError(`expecting str, got ${typeof jsonString}`);if(!jsonString.trim())throw Error(`${jsonString} is empty`);return _parseJSON(jsonString.trim(),allowPartial)}var Allow,PartialJSON,MalformedJSON,_parseJSON=(jsonString,allow)=>{let length=jsonString.length,index=0,markPartialJSON=(msg)=>{throw new PartialJSON(`${msg} at position ${index}`)},throwMalformedError=(msg)=>{throw new MalformedJSON(`${msg} at position ${index}`)},parseAny=()=>{if(skipBlank(),index>=length)markPartialJSON("Unexpected end of input");if(jsonString[index]==='"')return parseStr();if(jsonString[index]==="{")return parseObj();if(jsonString[index]==="[")return parseArr();if(jsonString.substring(index,index+4)==="null"||Allow.NULL&allow&&length-index<4&&"null".startsWith(jsonString.substring(index)))return index+=4,null;if(jsonString.substring(index,index+4)==="true"||Allow.BOOL&allow&&length-index<4&&"true".startsWith(jsonString.substring(index)))return index+=4,!0;if(jsonString.substring(index,index+5)==="false"||Allow.BOOL&allow&&length-index<5&&"false".startsWith(jsonString.substring(index)))return index+=5,!1;if(jsonString.substring(index,index+8)==="Infinity"||Allow.INFINITY&allow&&length-index<8&&"Infinity".startsWith(jsonString.substring(index)))return index+=8,1/0;if(jsonString.substring(index,index+9)==="-Infinity"||Allow.MINUS_INFINITY&allow&&1<length-index&&length-index<9&&"-Infinity".startsWith(jsonString.substring(index)))return index+=9,-1/0;if(jsonString.substring(index,index+3)==="NaN"||Allow.NAN&allow&&length-index<3&&"NaN".startsWith(jsonString.substring(index)))return index+=3,NaN;return parseNum()},parseStr=()=>{let start=index,escape2=!1;index++;while(index<length&&(jsonString[index]!=='"'||escape2&&jsonString[index-1]==="\\"))escape2=jsonString[index]==="\\"?!escape2:!1,index++;if(jsonString.charAt(index)=='"')try{return JSON.parse(jsonString.substring(start,++index-Number(escape2)))}catch(e){throwMalformedError(String(e))}else if(Allow.STR&allow)try{return JSON.parse(jsonString.substring(start,index-Number(escape2))+'"')}catch(e){return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("\\"))+'"')}markPartialJSON("Unterminated string literal")},parseObj=()=>{index++,skipBlank();let obj={};try{while(jsonString[index]!=="}"){if(skipBlank(),index>=length&&Allow.OBJ&allow)return obj;let key=parseStr();skipBlank(),index++;try{let value=parseAny();Object.defineProperty(obj,key,{value,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Allow.OBJ&allow)return obj;else throw e}if(skipBlank(),jsonString[index]===",")index++}}catch(e){if(Allow.OBJ&allow)return obj;else markPartialJSON("Expected '}' at end of object")}return index++,obj},parseArr=()=>{index++;let arr=[];try{while(jsonString[index]!=="]")if(arr.push(parseAny()),skipBlank(),jsonString[index]===",")index++}catch(e){if(Allow.ARR&allow)return arr;markPartialJSON("Expected ']' at end of array")}return index++,arr},parseNum=()=>{if(index===0){if(jsonString==="-"&&Allow.NUM&allow)markPartialJSON("Not sure what '-' is");try{return JSON.parse(jsonString)}catch(e){if(Allow.NUM&allow)try{if(jsonString[jsonString.length-1]===".")return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf(".")));return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf("e")))}catch(e2){}throwMalformedError(String(e))}}let start=index;if(jsonString[index]==="-")index++;while(jsonString[index]&&!",]}".includes(jsonString[index]))index++;if(index==length&&!(Allow.NUM&allow))markPartialJSON("Unterminated number literal");try{return JSON.parse(jsonString.substring(start,index))}catch(e){if(jsonString.substring(start,index)==="-"&&Allow.NUM&allow)markPartialJSON("Not sure what '-' is");try{return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("e")))}catch(e2){throwMalformedError(String(e2))}}},skipBlank=()=>{while(index<length&&`
7
- \r `.includes(jsonString[index]))index++};return parseAny()},partialParse=(input)=>parseJSON(input,Allow.ALL^Allow.NUM);var init_parser2=__esm(()=>{Allow={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};PartialJSON=class PartialJSON extends Error{};MalformedJSON=class MalformedJSON extends Error{}});function finalizeChatCompletion(snapshot,params){let{id,choices,created,model,system_fingerprint,...rest}=snapshot,completion={...rest,id,choices:choices.map(({message,finish_reason,index,logprobs,...choiceRest})=>{if(!finish_reason)throw new OpenAIError(`missing finish_reason for choice ${index}`);let{content=null,function_call,tool_calls,...messageRest}=message,role=message.role;if(!role)throw new OpenAIError(`missing role for choice ${index}`);if(function_call){let{arguments:args,name}=function_call;if(args==null)throw new OpenAIError(`missing function_call.arguments for choice ${index}`);if(!name)throw new OpenAIError(`missing function_call.name for choice ${index}`);return{...choiceRest,message:{content,function_call:{arguments:args,name},role,refusal:message.refusal??null},finish_reason,index,logprobs}}if(tool_calls)return{...choiceRest,index,finish_reason,logprobs,message:{...messageRest,role,content,refusal:message.refusal??null,tool_calls:tool_calls.map((tool_call,i)=>{let{function:fn,type,id:id2,...toolRest}=tool_call,{arguments:args,name,...fnRest}=fn||{};if(id2==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id
8
- ${str(snapshot)}`);if(type==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
9
- ${str(snapshot)}`);if(name==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name
10
- ${str(snapshot)}`);if(args==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
11
- ${str(snapshot)}`);return{...toolRest,id:id2,type,function:{...fnRest,name,arguments:args}}})}};return{...choiceRest,message:{...messageRest,content,role,refusal:message.refusal??null},finish_reason,index,logprobs}}),created,model,object:"chat.completion",...system_fingerprint?{system_fingerprint}:{}};return maybeParseChatCompletion(completion,params)}function str(x){return JSON.stringify(x)}function assertIsEmpty(obj){return}function assertNever2(_x){}var __classPrivateFieldSet5=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet6=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_ChatCompletionStream_instances,_ChatCompletionStream_params,_ChatCompletionStream_choiceEventStates,_ChatCompletionStream_currentChatCompletionSnapshot,_ChatCompletionStream_beginRequest,_ChatCompletionStream_getChoiceEventState,_ChatCompletionStream_addChunk,_ChatCompletionStream_emitToolCallDoneEvent,_ChatCompletionStream_emitContentDoneEvents,_ChatCompletionStream_endRequest,_ChatCompletionStream_getAutoParseableResponseFormat,_ChatCompletionStream_accumulateChatCompletion,ChatCompletionStream;var init_ChatCompletionStream=__esm(()=>{init_error();init_AbstractChatCompletionRunner();init_streaming();init_parser();init_parser2();ChatCompletionStream=class ChatCompletionStream extends AbstractChatCompletionRunner{constructor(params){super();_ChatCompletionStream_instances.add(this),_ChatCompletionStream_params.set(this,void 0),_ChatCompletionStream_choiceEventStates.set(this,void 0),_ChatCompletionStream_currentChatCompletionSnapshot.set(this,void 0),__classPrivateFieldSet5(this,_ChatCompletionStream_params,params,"f"),__classPrivateFieldSet5(this,_ChatCompletionStream_choiceEventStates,[],"f")}get currentChatCompletionSnapshot(){return __classPrivateFieldGet6(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f")}static fromReadableStream(stream){let runner=new ChatCompletionStream(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}static createChatCompletion(client,params,options){let runner=new ChatCompletionStream(params);return runner._run(()=>runner._runChatCompletion(client,{...params,stream:!0},{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}async _createChatCompletion(client,params,options){super._createChatCompletion;let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this);let stream=await client.chat.completions.create({...params,stream:!0},{...options,signal:this.controller.signal});this._connected();for await(let chunk of stream)__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,chunk);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addChatCompletion(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}async _fromReadableStream(readableStream,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this),this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller),chatId;for await(let chunk of stream){if(chatId&&chatId!==chunk.id)this._addChatCompletion(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this));__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,chunk),chatId=chunk.id}if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addChatCompletion(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}[(_ChatCompletionStream_params=new WeakMap,_ChatCompletionStream_choiceEventStates=new WeakMap,_ChatCompletionStream_currentChatCompletionSnapshot=new WeakMap,_ChatCompletionStream_instances=new WeakSet,_ChatCompletionStream_beginRequest=function(){if(this.ended)return;__classPrivateFieldSet5(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f")},_ChatCompletionStream_getChoiceEventState=function(choice){let state=__classPrivateFieldGet6(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index];if(state)return state;return state={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},__classPrivateFieldGet6(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index]=state,state},_ChatCompletionStream_addChunk=function(chunk){if(this.ended)return;let completion=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_accumulateChatCompletion).call(this,chunk);this._emit("chunk",chunk,completion);for(let choice of chunk.choices){let choiceSnapshot=completion.choices[choice.index];if(choice.delta.content!=null&&choiceSnapshot.message?.role==="assistant"&&choiceSnapshot.message?.content)this._emit("content",choice.delta.content,choiceSnapshot.message.content),this._emit("content.delta",{delta:choice.delta.content,snapshot:choiceSnapshot.message.content,parsed:choiceSnapshot.message.parsed});if(choice.delta.refusal!=null&&choiceSnapshot.message?.role==="assistant"&&choiceSnapshot.message?.refusal)this._emit("refusal.delta",{delta:choice.delta.refusal,snapshot:choiceSnapshot.message.refusal});if(choice.logprobs?.content!=null&&choiceSnapshot.message?.role==="assistant")this._emit("logprobs.content.delta",{content:choice.logprobs?.content,snapshot:choiceSnapshot.logprobs?.content??[]});if(choice.logprobs?.refusal!=null&&choiceSnapshot.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:choice.logprobs?.refusal,snapshot:choiceSnapshot.logprobs?.refusal??[]});let state=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot);if(choiceSnapshot.finish_reason){if(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,choiceSnapshot),state.current_tool_call_index!=null)__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,choiceSnapshot,state.current_tool_call_index)}for(let toolCall of choice.delta.tool_calls??[]){if(state.current_tool_call_index!==toolCall.index){if(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,choiceSnapshot),state.current_tool_call_index!=null)__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,choiceSnapshot,state.current_tool_call_index)}state.current_tool_call_index=toolCall.index}for(let toolCallDelta of choice.delta.tool_calls??[]){let toolCallSnapshot=choiceSnapshot.message.tool_calls?.[toolCallDelta.index];if(!toolCallSnapshot?.type)continue;if(toolCallSnapshot?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:toolCallSnapshot.function?.name,index:toolCallDelta.index,arguments:toolCallSnapshot.function.arguments,parsed_arguments:toolCallSnapshot.function.parsed_arguments,arguments_delta:toolCallDelta.function?.arguments??""});else assertNever2(toolCallSnapshot?.type)}}},_ChatCompletionStream_emitToolCallDoneEvent=function(choiceSnapshot,toolCallIndex){if(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot).done_tool_calls.has(toolCallIndex))return;let toolCallSnapshot=choiceSnapshot.message.tool_calls?.[toolCallIndex];if(!toolCallSnapshot)throw Error("no tool call snapshot");if(!toolCallSnapshot.type)throw Error("tool call snapshot missing `type`");if(toolCallSnapshot.type==="function"){let inputTool=__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f")?.tools?.find((tool)=>tool.type==="function"&&tool.function.name===toolCallSnapshot.function.name);this._emit("tool_calls.function.arguments.done",{name:toolCallSnapshot.function.name,index:toolCallIndex,arguments:toolCallSnapshot.function.arguments,parsed_arguments:isAutoParsableTool(inputTool)?inputTool.$parseRaw(toolCallSnapshot.function.arguments):inputTool?.function.strict?JSON.parse(toolCallSnapshot.function.arguments):null})}else assertNever2(toolCallSnapshot.type)},_ChatCompletionStream_emitContentDoneEvents=function(choiceSnapshot){let state=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot);if(choiceSnapshot.message.content&&!state.content_done){state.content_done=!0;let responseFormat=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getAutoParseableResponseFormat).call(this);this._emit("content.done",{content:choiceSnapshot.message.content,parsed:responseFormat?responseFormat.$parseRaw(choiceSnapshot.message.content):null})}if(choiceSnapshot.message.refusal&&!state.refusal_done)state.refusal_done=!0,this._emit("refusal.done",{refusal:choiceSnapshot.message.refusal});if(choiceSnapshot.logprobs?.content&&!state.logprobs_content_done)state.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:choiceSnapshot.logprobs.content});if(choiceSnapshot.logprobs?.refusal&&!state.logprobs_refusal_done)state.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:choiceSnapshot.logprobs.refusal})},_ChatCompletionStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");let snapshot=__classPrivateFieldGet6(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f");if(!snapshot)throw new OpenAIError("request ended without sending any chunks");return __classPrivateFieldSet5(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f"),__classPrivateFieldSet5(this,_ChatCompletionStream_choiceEventStates,[],"f"),finalizeChatCompletion(snapshot,__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f"))},_ChatCompletionStream_getAutoParseableResponseFormat=function(){let responseFormat=__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f")?.response_format;if(isAutoParsableResponseFormat(responseFormat))return responseFormat;return null},_ChatCompletionStream_accumulateChatCompletion=function(chunk){var _a,_b,_c,_d;let snapshot=__classPrivateFieldGet6(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"),{choices,...rest}=chunk;if(!snapshot)snapshot=__classPrivateFieldSet5(this,_ChatCompletionStream_currentChatCompletionSnapshot,{...rest,choices:[]},"f");else Object.assign(snapshot,rest);for(let{delta,finish_reason,index,logprobs=null,...other}of chunk.choices){let choice=snapshot.choices[index];if(!choice)choice=snapshot.choices[index]={finish_reason,index,message:{},logprobs,...other};if(logprobs)if(!choice.logprobs)choice.logprobs=Object.assign({},logprobs);else{let{content:content2,refusal:refusal2,...rest3}=logprobs;if(assertIsEmpty(rest3),Object.assign(choice.logprobs,rest3),content2)(_a=choice.logprobs).content??(_a.content=[]),choice.logprobs.content.push(...content2);if(refusal2)(_b=choice.logprobs).refusal??(_b.refusal=[]),choice.logprobs.refusal.push(...refusal2)}if(finish_reason){if(choice.finish_reason=finish_reason,__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f")&&hasAutoParseableInput(__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f"))){if(finish_reason==="length")throw new LengthFinishReasonError;if(finish_reason==="content_filter")throw new ContentFilterFinishReasonError}}if(Object.assign(choice,other),!delta)continue;let{content,refusal,function_call,role,tool_calls,...rest2}=delta;if(assertIsEmpty(rest2),Object.assign(choice.message,rest2),refusal)choice.message.refusal=(choice.message.refusal||"")+refusal;if(role)choice.message.role=role;if(function_call)if(!choice.message.function_call)choice.message.function_call=function_call;else{if(function_call.name)choice.message.function_call.name=function_call.name;if(function_call.arguments)(_c=choice.message.function_call).arguments??(_c.arguments=""),choice.message.function_call.arguments+=function_call.arguments}if(content){if(choice.message.content=(choice.message.content||"")+content,!choice.message.refusal&&__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getAutoParseableResponseFormat).call(this))choice.message.parsed=partialParse(choice.message.content)}if(tool_calls){if(!choice.message.tool_calls)choice.message.tool_calls=[];for(let{index:index2,id,type,function:fn,...rest3}of tool_calls){let tool_call=(_d=choice.message.tool_calls)[index2]??(_d[index2]={});if(Object.assign(tool_call,rest3),id)tool_call.id=id;if(type)tool_call.type=type;if(fn)tool_call.function??(tool_call.function={name:fn.name??"",arguments:""});if(fn?.name)tool_call.function.name=fn.name;if(fn?.arguments){if(tool_call.function.arguments+=fn.arguments,shouldParseToolCall(__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f"),tool_call))tool_call.function.parsed_arguments=partialParse(tool_call.function.arguments)}}}}return snapshot},Symbol.asyncIterator)](){let pushQueue=[],readQueue=[],done=!1;return this.on("chunk",(chunk)=>{let reader=readQueue.shift();if(reader)reader.resolve(chunk);else pushQueue.push(chunk)}),this.on("end",()=>{done=!0;for(let reader of readQueue)reader.resolve(void 0);readQueue.length=0}),this.on("abort",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),this.on("error",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),{next:async()=>{if(!pushQueue.length){if(done)return{value:void 0,done:!0};return new Promise((resolve,reject)=>readQueue.push({resolve,reject})).then((chunk2)=>chunk2?{value:chunk2,done:!1}:{value:void 0,done:!0})}return{value:pushQueue.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var ChatCompletionStreamingRunner;var init_ChatCompletionStreamingRunner=__esm(()=>{init_ChatCompletionStream();ChatCompletionStreamingRunner=class ChatCompletionStreamingRunner extends ChatCompletionStream{static fromReadableStream(stream){let runner=new ChatCompletionStreamingRunner(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}static runFunctions(client,params,options){let runner=new ChatCompletionStreamingRunner(null),opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return runner._run(()=>runner._runFunctions(client,params,opts)),runner}static runTools(client,params,options){let runner=new ChatCompletionStreamingRunner(params),opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runTools"}};return runner._run(()=>runner._runTools(client,params,opts)),runner}}});var Completions2;var init_completions2=__esm(()=>{init_ChatCompletionRunner();init_ChatCompletionStreamingRunner();init_ChatCompletionStream();init_parser();Completions2=class Completions2 extends APIResource{parse(body,options){return validateInputTools(body.tools),this._client.chat.completions.create(body,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((completion)=>parseChatCompletion(completion,body))}runFunctions(body,options){if(body.stream)return ChatCompletionStreamingRunner.runFunctions(this._client,body,options);return ChatCompletionRunner.runFunctions(this._client,body,options)}runTools(body,options){if(body.stream)return ChatCompletionStreamingRunner.runTools(this._client,body,options);return ChatCompletionRunner.runTools(this._client,body,options)}stream(body,options){return ChatCompletionStream.createChatCompletion(this._client,body,options)}}});var Chat2;var init_chat3=__esm(()=>{init_completions2();Chat2=class Chat2 extends APIResource{constructor(){super(...arguments);this.completions=new Completions2(this._client)}};(function(Chat3){Chat3.Completions=Completions2})(Chat2||(Chat2={}))});var Sessions;var init_sessions=__esm(()=>{Sessions=class Sessions extends APIResource{create(body,options){return this._client.post("/realtime/sessions",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}}});var TranscriptionSessions;var init_transcription_sessions=__esm(()=>{TranscriptionSessions=class TranscriptionSessions extends APIResource{create(body,options){return this._client.post("/realtime/transcription_sessions",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}}});var Realtime;var init_realtime=__esm(()=>{init_sessions();init_sessions();init_transcription_sessions();init_transcription_sessions();Realtime=class Realtime extends APIResource{constructor(){super(...arguments);this.sessions=new Sessions(this._client),this.transcriptionSessions=new TranscriptionSessions(this._client)}};Realtime.Sessions=Sessions;Realtime.TranscriptionSessions=TranscriptionSessions});var Messages2,MessagesPage;var init_messages2=__esm(()=>{init_core();init_pagination();Messages2=class Messages2 extends APIResource{create(threadId,body,options){return this._client.post(`/threads/${threadId}/messages`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(threadId,messageId,options){return this._client.get(`/threads/${threadId}/messages/${messageId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(threadId,messageId,body,options){return this._client.post(`/threads/${threadId}/messages/${messageId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(threadId,query={},options){if(isRequestOptions(query))return this.list(threadId,{},query);return this._client.getAPIList(`/threads/${threadId}/messages`,MessagesPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(threadId,messageId,options){return this._client.delete(`/threads/${threadId}/messages/${messageId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};MessagesPage=class MessagesPage extends CursorPage{};Messages2.MessagesPage=MessagesPage});var Steps,RunStepsPage;var init_steps=__esm(()=>{init_core();init_pagination();Steps=class Steps extends APIResource{retrieve(threadId,runId,stepId,query={},options){if(isRequestOptions(query))return this.retrieve(threadId,runId,stepId,{},query);return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(threadId,runId,query={},options){if(isRequestOptions(query))return this.list(threadId,runId,{},query);return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`,RunStepsPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};RunStepsPage=class RunStepsPage extends CursorPage{};Steps.RunStepsPage=RunStepsPage});var Runs,RunsPage;var init_runs=__esm(()=>{init_core();init_AssistantStream();init_core();init_steps();init_steps();init_pagination();Runs=class Runs extends APIResource{constructor(){super(...arguments);this.steps=new Steps(this._client)}create(threadId,params,options){let{include,...body}=params;return this._client.post(`/threads/${threadId}/runs`,{query:{include},body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers},stream:params.stream??!1})}retrieve(threadId,runId,options){return this._client.get(`/threads/${threadId}/runs/${runId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(threadId,runId,body,options){return this._client.post(`/threads/${threadId}/runs/${runId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(threadId,query={},options){if(isRequestOptions(query))return this.list(threadId,{},query);return this._client.getAPIList(`/threads/${threadId}/runs`,RunsPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}cancel(threadId,runId,options){return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async createAndPoll(threadId,body,options){let run=await this.create(threadId,body,options);return await this.poll(threadId,run.id,options)}createAndStream(threadId,body,options){return AssistantStream.createAssistantStream(threadId,this._client.beta.threads.runs,body,options)}async poll(threadId,runId,options){let headers={...options?.headers,"X-Stainless-Poll-Helper":"true"};if(options?.pollIntervalMs)headers["X-Stainless-Custom-Poll-Interval"]=options.pollIntervalMs.toString();while(!0){let{data:run,response}=await this.retrieve(threadId,runId,{...options,headers:{...options?.headers,...headers}}).withResponse();switch(run.status){case"queued":case"in_progress":case"cancelling":let sleepInterval=5000;if(options?.pollIntervalMs)sleepInterval=options.pollIntervalMs;else{let headerInterval=response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=parseInt(headerInterval);if(!isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}await sleep(sleepInterval);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return run}}}stream(threadId,body,options){return AssistantStream.createAssistantStream(threadId,this._client.beta.threads.runs,body,options)}submitToolOutputs(threadId,runId,body,options){return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers},stream:body.stream??!1})}async submitToolOutputsAndPoll(threadId,runId,body,options){let run=await this.submitToolOutputs(threadId,runId,body,options);return await this.poll(threadId,run.id,options)}submitToolOutputsStream(threadId,runId,body,options){return AssistantStream.createToolAssistantStream(threadId,runId,this._client.beta.threads.runs,body,options)}};RunsPage=class RunsPage extends CursorPage{};Runs.RunsPage=RunsPage;Runs.Steps=Steps;Runs.RunStepsPage=RunStepsPage});var Threads;var init_threads=__esm(()=>{init_core();init_AssistantStream();init_messages2();init_messages2();init_runs();init_runs();Threads=class Threads extends APIResource{constructor(){super(...arguments);this.runs=new Runs(this._client),this.messages=new Messages2(this._client)}create(body={},options){if(isRequestOptions(body))return this.create({},body);return this._client.post("/threads",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(threadId,options){return this._client.get(`/threads/${threadId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(threadId,body,options){return this._client.post(`/threads/${threadId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(threadId,options){return this._client.delete(`/threads/${threadId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}createAndRun(body,options){return this._client.post("/threads/runs",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers},stream:body.stream??!1})}async createAndRunPoll(body,options){let run=await this.createAndRun(body,options);return await this.runs.poll(run.thread_id,run.id,options)}createAndRunStream(body,options){return AssistantStream.createThreadAssistantStream(body,this._client.beta.threads,options)}};Threads.Runs=Runs;Threads.RunsPage=RunsPage;Threads.Messages=Messages2;Threads.MessagesPage=MessagesPage});var Beta;var init_beta=__esm(()=>{init_assistants();init_chat3();init_assistants();init_realtime();init_realtime();init_threads();init_threads();Beta=class Beta extends APIResource{constructor(){super(...arguments);this.realtime=new Realtime(this._client),this.chat=new Chat2(this._client),this.assistants=new Assistants(this._client),this.threads=new Threads(this._client)}};Beta.Realtime=Realtime;Beta.Assistants=Assistants;Beta.AssistantsPage=AssistantsPage;Beta.Threads=Threads});var Completions3;var init_completions3=__esm(()=>{Completions3=class Completions3 extends APIResource{create(body,options){return this._client.post("/completions",{body,...options,stream:body.stream??!1})}}});var Content;var init_content=__esm(()=>{Content=class Content extends APIResource{retrieve(containerId,fileId,options){return this._client.get(`/containers/${containerId}/files/${fileId}/content`,{...options,headers:{Accept:"application/binary",...options?.headers},__binaryResponse:!0})}}});var Files,FileListResponsesPage;var init_files=__esm(()=>{init_core();init_core();init_content();init_content();init_pagination();Files=class Files extends APIResource{constructor(){super(...arguments);this.content=new Content(this._client)}create(containerId,body,options){return this._client.post(`/containers/${containerId}/files`,multipartFormRequestOptions({body,...options}))}retrieve(containerId,fileId,options){return this._client.get(`/containers/${containerId}/files/${fileId}`,options)}list(containerId,query={},options){if(isRequestOptions(query))return this.list(containerId,{},query);return this._client.getAPIList(`/containers/${containerId}/files`,FileListResponsesPage,{query,...options})}del(containerId,fileId,options){return this._client.delete(`/containers/${containerId}/files/${fileId}`,{...options,headers:{Accept:"*/*",...options?.headers}})}};FileListResponsesPage=class FileListResponsesPage extends CursorPage{};Files.FileListResponsesPage=FileListResponsesPage;Files.Content=Content});var Containers,ContainerListResponsesPage;var init_containers=__esm(()=>{init_core();init_files();init_files();init_pagination();Containers=class Containers extends APIResource{constructor(){super(...arguments);this.files=new Files(this._client)}create(body,options){return this._client.post("/containers",{body,...options})}retrieve(containerId,options){return this._client.get(`/containers/${containerId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/containers",ContainerListResponsesPage,{query,...options})}del(containerId,options){return this._client.delete(`/containers/${containerId}`,{...options,headers:{Accept:"*/*",...options?.headers}})}};ContainerListResponsesPage=class ContainerListResponsesPage extends CursorPage{};Containers.ContainerListResponsesPage=ContainerListResponsesPage;Containers.Files=Files;Containers.FileListResponsesPage=FileListResponsesPage});var Embeddings;var init_embeddings=__esm(()=>{init_core();Embeddings=class Embeddings extends APIResource{create(body,options){let hasUserProvidedEncodingFormat=!!body.encoding_format,encoding_format=hasUserProvidedEncodingFormat?body.encoding_format:"base64";if(hasUserProvidedEncodingFormat)debug("Request","User defined encoding_format:",body.encoding_format);let response=this._client.post("/embeddings",{body:{...body,encoding_format},...options});if(hasUserProvidedEncodingFormat)return response;return debug("response","Decoding base64 embeddings to float32 array"),response._thenUnwrap((response2)=>{if(response2&&response2.data)response2.data.forEach((embeddingBase64Obj)=>{let embeddingBase64Str=embeddingBase64Obj.embedding;embeddingBase64Obj.embedding=toFloat32Array(embeddingBase64Str)});return response2})}}});var OutputItems,OutputItemListResponsesPage;var init_output_items=__esm(()=>{init_core();init_pagination();OutputItems=class OutputItems extends APIResource{retrieve(evalId,runId,outputItemId,options){return this._client.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`,options)}list(evalId,runId,query={},options){if(isRequestOptions(query))return this.list(evalId,runId,{},query);return this._client.getAPIList(`/evals/${evalId}/runs/${runId}/output_items`,OutputItemListResponsesPage,{query,...options})}};OutputItemListResponsesPage=class OutputItemListResponsesPage extends CursorPage{};OutputItems.OutputItemListResponsesPage=OutputItemListResponsesPage});var Runs2,RunListResponsesPage;var init_runs2=__esm(()=>{init_core();init_output_items();init_output_items();init_pagination();Runs2=class Runs2 extends APIResource{constructor(){super(...arguments);this.outputItems=new OutputItems(this._client)}create(evalId,body,options){return this._client.post(`/evals/${evalId}/runs`,{body,...options})}retrieve(evalId,runId,options){return this._client.get(`/evals/${evalId}/runs/${runId}`,options)}list(evalId,query={},options){if(isRequestOptions(query))return this.list(evalId,{},query);return this._client.getAPIList(`/evals/${evalId}/runs`,RunListResponsesPage,{query,...options})}del(evalId,runId,options){return this._client.delete(`/evals/${evalId}/runs/${runId}`,options)}cancel(evalId,runId,options){return this._client.post(`/evals/${evalId}/runs/${runId}`,options)}};RunListResponsesPage=class RunListResponsesPage extends CursorPage{};Runs2.RunListResponsesPage=RunListResponsesPage;Runs2.OutputItems=OutputItems;Runs2.OutputItemListResponsesPage=OutputItemListResponsesPage});var Evals,EvalListResponsesPage;var init_evals=__esm(()=>{init_core();init_runs2();init_runs2();init_pagination();Evals=class Evals extends APIResource{constructor(){super(...arguments);this.runs=new Runs2(this._client)}create(body,options){return this._client.post("/evals",{body,...options})}retrieve(evalId,options){return this._client.get(`/evals/${evalId}`,options)}update(evalId,body,options){return this._client.post(`/evals/${evalId}`,{body,...options})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/evals",EvalListResponsesPage,{query,...options})}del(evalId,options){return this._client.delete(`/evals/${evalId}`,options)}};EvalListResponsesPage=class EvalListResponsesPage extends CursorPage{};Evals.EvalListResponsesPage=EvalListResponsesPage;Evals.Runs=Runs2;Evals.RunListResponsesPage=RunListResponsesPage});var Files2,FileObjectsPage;var init_files2=__esm(()=>{init_core();init_core();init_error();init_core();init_pagination();Files2=class Files2 extends APIResource{create(body,options){return this._client.post("/files",multipartFormRequestOptions({body,...options}))}retrieve(fileId,options){return this._client.get(`/files/${fileId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/files",FileObjectsPage,{query,...options})}del(fileId,options){return this._client.delete(`/files/${fileId}`,options)}content(fileId,options){return this._client.get(`/files/${fileId}/content`,{...options,headers:{Accept:"application/binary",...options?.headers},__binaryResponse:!0})}retrieveContent(fileId,options){return this._client.get(`/files/${fileId}/content`,options)}async waitForProcessing(id,{pollInterval=5000,maxWait=1800000}={}){let TERMINAL_STATES=new Set(["processed","error","deleted"]),start=Date.now(),file=await this.retrieve(id);while(!file.status||!TERMINAL_STATES.has(file.status))if(await sleep(pollInterval),file=await this.retrieve(id),Date.now()-start>maxWait)throw new APIConnectionTimeoutError({message:`Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`});return file}};FileObjectsPage=class FileObjectsPage extends CursorPage{};Files2.FileObjectsPage=FileObjectsPage});var Methods;var init_methods=__esm(()=>{Methods=class Methods extends APIResource{}});var Graders;var init_graders=__esm(()=>{Graders=class Graders extends APIResource{run(body,options){return this._client.post("/fine_tuning/alpha/graders/run",{body,...options})}validate(body,options){return this._client.post("/fine_tuning/alpha/graders/validate",{body,...options})}}});var Alpha;var init_alpha=__esm(()=>{init_graders();init_graders();Alpha=class Alpha extends APIResource{constructor(){super(...arguments);this.graders=new Graders(this._client)}};Alpha.Graders=Graders});var Permissions,PermissionCreateResponsesPage;var init_permissions=__esm(()=>{init_core();init_pagination();Permissions=class Permissions extends APIResource{create(fineTunedModelCheckpoint,body,options){return this._client.getAPIList(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,PermissionCreateResponsesPage,{body,method:"post",...options})}retrieve(fineTunedModelCheckpoint,query={},options){if(isRequestOptions(query))return this.retrieve(fineTunedModelCheckpoint,{},query);return this._client.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,{query,...options})}del(fineTunedModelCheckpoint,permissionId,options){return this._client.delete(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`,options)}};PermissionCreateResponsesPage=class PermissionCreateResponsesPage extends Page{};Permissions.PermissionCreateResponsesPage=PermissionCreateResponsesPage});var Checkpoints;var init_checkpoints=__esm(()=>{init_permissions();init_permissions();Checkpoints=class Checkpoints extends APIResource{constructor(){super(...arguments);this.permissions=new Permissions(this._client)}};Checkpoints.Permissions=Permissions;Checkpoints.PermissionCreateResponsesPage=PermissionCreateResponsesPage});var Checkpoints2,FineTuningJobCheckpointsPage;var init_checkpoints2=__esm(()=>{init_core();init_pagination();Checkpoints2=class Checkpoints2 extends APIResource{list(fineTuningJobId,query={},options){if(isRequestOptions(query))return this.list(fineTuningJobId,{},query);return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`,FineTuningJobCheckpointsPage,{query,...options})}};FineTuningJobCheckpointsPage=class FineTuningJobCheckpointsPage extends CursorPage{};Checkpoints2.FineTuningJobCheckpointsPage=FineTuningJobCheckpointsPage});var Jobs,FineTuningJobsPage,FineTuningJobEventsPage;var init_jobs=__esm(()=>{init_core();init_checkpoints2();init_checkpoints2();init_pagination();Jobs=class Jobs extends APIResource{constructor(){super(...arguments);this.checkpoints=new Checkpoints2(this._client)}create(body,options){return this._client.post("/fine_tuning/jobs",{body,...options})}retrieve(fineTuningJobId,options){return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/fine_tuning/jobs",FineTuningJobsPage,{query,...options})}cancel(fineTuningJobId,options){return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`,options)}listEvents(fineTuningJobId,query={},options){if(isRequestOptions(query))return this.listEvents(fineTuningJobId,{},query);return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`,FineTuningJobEventsPage,{query,...options})}pause(fineTuningJobId,options){return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`,options)}resume(fineTuningJobId,options){return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`,options)}};FineTuningJobsPage=class FineTuningJobsPage extends CursorPage{};FineTuningJobEventsPage=class FineTuningJobEventsPage extends CursorPage{};Jobs.FineTuningJobsPage=FineTuningJobsPage;Jobs.FineTuningJobEventsPage=FineTuningJobEventsPage;Jobs.Checkpoints=Checkpoints2;Jobs.FineTuningJobCheckpointsPage=FineTuningJobCheckpointsPage});var FineTuning;var init_fine_tuning=__esm(()=>{init_methods();init_methods();init_alpha();init_alpha();init_checkpoints();init_checkpoints();init_jobs();init_jobs();FineTuning=class FineTuning extends APIResource{constructor(){super(...arguments);this.methods=new Methods(this._client),this.jobs=new Jobs(this._client),this.checkpoints=new Checkpoints(this._client),this.alpha=new Alpha(this._client)}};FineTuning.Methods=Methods;FineTuning.Jobs=Jobs;FineTuning.FineTuningJobsPage=FineTuningJobsPage;FineTuning.FineTuningJobEventsPage=FineTuningJobEventsPage;FineTuning.Checkpoints=Checkpoints;FineTuning.Alpha=Alpha});var GraderModels;var init_grader_models=__esm(()=>{GraderModels=class GraderModels extends APIResource{}});var Graders2;var init_graders2=__esm(()=>{init_grader_models();init_grader_models();Graders2=class Graders2 extends APIResource{constructor(){super(...arguments);this.graderModels=new GraderModels(this._client)}};Graders2.GraderModels=GraderModels});var Images;var init_images=__esm(()=>{init_core();Images=class Images extends APIResource{createVariation(body,options){return this._client.post("/images/variations",multipartFormRequestOptions({body,...options}))}edit(body,options){return this._client.post("/images/edits",multipartFormRequestOptions({body,...options}))}generate(body,options){return this._client.post("/images/generations",{body,...options})}}});var Models,ModelsPage;var init_models=__esm(()=>{init_pagination();Models=class Models extends APIResource{retrieve(model,options){return this._client.get(`/models/${model}`,options)}list(options){return this._client.getAPIList("/models",ModelsPage,options)}del(model,options){return this._client.delete(`/models/${model}`,options)}};ModelsPage=class ModelsPage extends Page{};Models.ModelsPage=ModelsPage});var Moderations;var init_moderations=__esm(()=>{Moderations=class Moderations extends APIResource{create(body,options){return this._client.post("/moderations",{body,...options})}}});function maybeParseResponse(response,params){if(!params||!hasAutoParseableInput2(params))return{...response,output_parsed:null,output:response.output.map((item)=>{if(item.type==="function_call")return{...item,parsed_arguments:null};if(item.type==="message")return{...item,content:item.content.map((content)=>({...content,parsed:null}))};else return item})};return parseResponse(response,params)}function parseResponse(response,params){let output=response.output.map((item)=>{if(item.type==="function_call")return{...item,parsed_arguments:parseToolCall2(params,item)};if(item.type==="message"){let content=item.content.map((content2)=>{if(content2.type==="output_text")return{...content2,parsed:parseTextFormat(params,content2.text)};return content2});return{...item,content}}return item}),parsed=Object.assign({},response,{output});if(!Object.getOwnPropertyDescriptor(response,"output_text"))addOutputText(parsed);return Object.defineProperty(parsed,"output_parsed",{enumerable:!0,get(){for(let output2 of parsed.output){if(output2.type!=="message")continue;for(let content of output2.content)if(content.type==="output_text"&&content.parsed!==null)return content.parsed}return null}}),parsed}function parseTextFormat(params,content){if(params.text?.format?.type!=="json_schema")return null;if("$parseRaw"in params.text?.format)return(params.text?.format).$parseRaw(content);return JSON.parse(content)}function hasAutoParseableInput2(params){if(isAutoParsableResponseFormat(params.text?.format))return!0;return!1}function isAutoParsableTool2(tool){return tool?.$brand==="auto-parseable-tool"}function getInputToolByName(input_tools,name){return input_tools.find((tool)=>tool.type==="function"&&tool.name===name)}function parseToolCall2(params,toolCall){let inputTool=getInputToolByName(params.tools??[],toolCall.name);return{...toolCall,...toolCall,parsed_arguments:isAutoParsableTool2(inputTool)?inputTool.$parseRaw(toolCall.arguments):inputTool?.strict?JSON.parse(toolCall.arguments):null}}function addOutputText(rsp){let texts=[];for(let output of rsp.output){if(output.type!=="message")continue;for(let content of output.content)if(content.type==="output_text")texts.push(content.text)}rsp.output_text=texts.join("")}var init_ResponsesParser=__esm(()=>{init_parser()});var InputItems;var init_input_items=__esm(()=>{init_core();init_responses();InputItems=class InputItems extends APIResource{list(responseId,query={},options){if(isRequestOptions(query))return this.list(responseId,{},query);return this._client.getAPIList(`/responses/${responseId}/input_items`,ResponseItemsPage,{query,...options})}}});function finalizeResponse(snapshot,params){return maybeParseResponse(snapshot,params)}var __classPrivateFieldSet6=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet7=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_ResponseStream_instances,_ResponseStream_params,_ResponseStream_currentResponseSnapshot,_ResponseStream_finalResponse,_ResponseStream_beginRequest,_ResponseStream_addEvent,_ResponseStream_endRequest,_ResponseStream_accumulateResponse,ResponseStream;var init_ResponseStream=__esm(()=>{init_error();init_EventStream();init_ResponsesParser();ResponseStream=class ResponseStream extends EventStream{constructor(params){super();_ResponseStream_instances.add(this),_ResponseStream_params.set(this,void 0),_ResponseStream_currentResponseSnapshot.set(this,void 0),_ResponseStream_finalResponse.set(this,void 0),__classPrivateFieldSet6(this,_ResponseStream_params,params,"f")}static createResponse(client,params,options){let runner=new ResponseStream(params);return runner._run(()=>runner._createOrRetrieveResponse(client,params,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}async _createOrRetrieveResponse(client,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_beginRequest).call(this);let stream,starting_after=null;if("response_id"in params)stream=await client.responses.retrieve(params.response_id,{stream:!0},{...options,signal:this.controller.signal,stream:!0}),starting_after=params.starting_after??null;else stream=await client.responses.create({...params,stream:!0},{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_addEvent).call(this,event,starting_after);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return __classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_endRequest).call(this)}[(_ResponseStream_params=new WeakMap,_ResponseStream_currentResponseSnapshot=new WeakMap,_ResponseStream_finalResponse=new WeakMap,_ResponseStream_instances=new WeakSet,_ResponseStream_beginRequest=function(){if(this.ended)return;__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,void 0,"f")},_ResponseStream_addEvent=function(event,starting_after){if(this.ended)return;let maybeEmit=(name,event2)=>{if(starting_after==null||event2.sequence_number>starting_after)this._emit(name,event2)},response=__classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_accumulateResponse).call(this,event);switch(maybeEmit("event",event),event.type){case"response.output_text.delta":{let output=response.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="message"){let content=output.content[event.content_index];if(!content)throw new OpenAIError(`missing content at index ${event.content_index}`);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);maybeEmit("response.output_text.delta",{...event,snapshot:content.text})}break}case"response.function_call_arguments.delta":{let output=response.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="function_call")maybeEmit("response.function_call_arguments.delta",{...event,snapshot:output.arguments});break}default:maybeEmit(event.type,event);break}},_ResponseStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");let snapshot=__classPrivateFieldGet7(this,_ResponseStream_currentResponseSnapshot,"f");if(!snapshot)throw new OpenAIError("request ended without sending any events");__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,void 0,"f");let parsedResponse=finalizeResponse(snapshot,__classPrivateFieldGet7(this,_ResponseStream_params,"f"));return __classPrivateFieldSet6(this,_ResponseStream_finalResponse,parsedResponse,"f"),parsedResponse},_ResponseStream_accumulateResponse=function(event){let snapshot=__classPrivateFieldGet7(this,_ResponseStream_currentResponseSnapshot,"f");if(!snapshot){if(event.type!=="response.created")throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);return snapshot=__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,event.response,"f"),snapshot}switch(event.type){case"response.output_item.added":{snapshot.output.push(event.item);break}case"response.content_part.added":{let output=snapshot.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="message")output.content.push(event.part);break}case"response.output_text.delta":{let output=snapshot.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="message"){let content=output.content[event.content_index];if(!content)throw new OpenAIError(`missing content at index ${event.content_index}`);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);content.text+=event.delta}break}case"response.function_call_arguments.delta":{let output=snapshot.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="function_call")output.arguments+=event.delta;break}case"response.completed":{__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,event.response,"f");break}}return snapshot},Symbol.asyncIterator)](){let pushQueue=[],readQueue=[],done=!1;return this.on("event",(event)=>{let reader=readQueue.shift();if(reader)reader.resolve(event);else pushQueue.push(event)}),this.on("end",()=>{done=!0;for(let reader of readQueue)reader.resolve(void 0);readQueue.length=0}),this.on("abort",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),this.on("error",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),{next:async()=>{if(!pushQueue.length){if(done)return{value:void 0,done:!0};return new Promise((resolve,reject)=>readQueue.push({resolve,reject})).then((event2)=>event2?{value:event2,done:!1}:{value:void 0,done:!0})}return{value:pushQueue.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let response=__classPrivateFieldGet7(this,_ResponseStream_finalResponse,"f");if(!response)throw new OpenAIError("stream ended without producing a ChatCompletion");return response}}});var Responses,ResponseItemsPage;var init_responses=__esm(()=>{init_ResponsesParser();init_input_items();init_input_items();init_ResponseStream();init_pagination();Responses=class Responses extends APIResource{constructor(){super(...arguments);this.inputItems=new InputItems(this._client)}create(body,options){return this._client.post("/responses",{body,...options,stream:body.stream??!1})._thenUnwrap((rsp)=>{if("object"in rsp&&rsp.object==="response")addOutputText(rsp);return rsp})}retrieve(responseId,query={},options){return this._client.get(`/responses/${responseId}`,{query,...options,stream:query?.stream??!1})}del(responseId,options){return this._client.delete(`/responses/${responseId}`,{...options,headers:{Accept:"*/*",...options?.headers}})}parse(body,options){return this._client.responses.create(body,options)._thenUnwrap((response)=>parseResponse(response,body))}stream(body,options){return ResponseStream.createResponse(this._client,body,options)}cancel(responseId,options){return this._client.post(`/responses/${responseId}/cancel`,{...options,headers:{Accept:"*/*",...options?.headers}})}};ResponseItemsPage=class ResponseItemsPage extends CursorPage{};Responses.InputItems=InputItems});var Parts;var init_parts=__esm(()=>{init_core();Parts=class Parts extends APIResource{create(uploadId,body,options){return this._client.post(`/uploads/${uploadId}/parts`,multipartFormRequestOptions({body,...options}))}}});var Uploads;var init_uploads2=__esm(()=>{init_parts();init_parts();Uploads=class Uploads extends APIResource{constructor(){super(...arguments);this.parts=new Parts(this._client)}create(body,options){return this._client.post("/uploads",{body,...options})}cancel(uploadId,options){return this._client.post(`/uploads/${uploadId}/cancel`,options)}complete(uploadId,body,options){return this._client.post(`/uploads/${uploadId}/complete`,{body,...options})}};Uploads.Parts=Parts});var allSettledWithThrow=async(promises)=>{let results=await Promise.allSettled(promises),rejected=results.filter((result)=>result.status==="rejected");if(rejected.length){for(let result of rejected)console.error(result.reason);throw Error(`${rejected.length} promise(s) failed - see the above errors`)}let values=[];for(let result of results)if(result.status==="fulfilled")values.push(result.value);return values};var Files3,VectorStoreFilesPage,FileContentResponsesPage;var init_files3=__esm(()=>{init_core();init_pagination();Files3=class Files3 extends APIResource{create(vectorStoreId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}/files`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(vectorStoreId,fileId,options){return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(vectorStoreId,fileId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(vectorStoreId,query={},options){if(isRequestOptions(query))return this.list(vectorStoreId,{},query);return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`,VectorStoreFilesPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(vectorStoreId,fileId,options){return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async createAndPoll(vectorStoreId,body,options){let file=await this.create(vectorStoreId,body,options);return await this.poll(vectorStoreId,file.id,options)}async poll(vectorStoreId,fileId,options){let headers={...options?.headers,"X-Stainless-Poll-Helper":"true"};if(options?.pollIntervalMs)headers["X-Stainless-Custom-Poll-Interval"]=options.pollIntervalMs.toString();while(!0){let fileResponse=await this.retrieve(vectorStoreId,fileId,{...options,headers}).withResponse(),file=fileResponse.data;switch(file.status){case"in_progress":let sleepInterval=5000;if(options?.pollIntervalMs)sleepInterval=options.pollIntervalMs;else{let headerInterval=fileResponse.response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=parseInt(headerInterval);if(!isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}await sleep(sleepInterval);break;case"failed":case"completed":return file}}}async upload(vectorStoreId,file,options){let fileInfo=await this._client.files.create({file,purpose:"assistants"},options);return this.create(vectorStoreId,{file_id:fileInfo.id},options)}async uploadAndPoll(vectorStoreId,file,options){let fileInfo=await this.upload(vectorStoreId,file,options);return await this.poll(vectorStoreId,fileInfo.id,options)}content(vectorStoreId,fileId,options){return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files/${fileId}/content`,FileContentResponsesPage,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};VectorStoreFilesPage=class VectorStoreFilesPage extends CursorPage{};FileContentResponsesPage=class FileContentResponsesPage extends Page{};Files3.VectorStoreFilesPage=VectorStoreFilesPage;Files3.FileContentResponsesPage=FileContentResponsesPage});var FileBatches;var init_file_batches=__esm(()=>{init_core();init_core();init_files3();FileBatches=class FileBatches extends APIResource{create(vectorStoreId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(vectorStoreId,batchId,options){return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}cancel(vectorStoreId,batchId,options){return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async createAndPoll(vectorStoreId,body,options){let batch=await this.create(vectorStoreId,body);return await this.poll(vectorStoreId,batch.id,options)}listFiles(vectorStoreId,batchId,query={},options){if(isRequestOptions(query))return this.listFiles(vectorStoreId,batchId,{},query);return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`,VectorStoreFilesPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async poll(vectorStoreId,batchId,options){let headers={...options?.headers,"X-Stainless-Poll-Helper":"true"};if(options?.pollIntervalMs)headers["X-Stainless-Custom-Poll-Interval"]=options.pollIntervalMs.toString();while(!0){let{data:batch,response}=await this.retrieve(vectorStoreId,batchId,{...options,headers}).withResponse();switch(batch.status){case"in_progress":let sleepInterval=5000;if(options?.pollIntervalMs)sleepInterval=options.pollIntervalMs;else{let headerInterval=response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=parseInt(headerInterval);if(!isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}await sleep(sleepInterval);break;case"failed":case"cancelled":case"completed":return batch}}}async uploadAndPoll(vectorStoreId,{files,fileIds=[]},options){if(files==null||files.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let configuredConcurrency=options?.maxConcurrency??5,concurrencyLimit=Math.min(configuredConcurrency,files.length),client=this._client,fileIterator=files.values(),allFileIds=[...fileIds];async function processFiles(iterator){for(let item of iterator){let fileObj=await client.files.create({file:item,purpose:"assistants"},options);allFileIds.push(fileObj.id)}}let workers=Array(concurrencyLimit).fill(fileIterator).map(processFiles);return await allSettledWithThrow(workers),await this.createAndPoll(vectorStoreId,{file_ids:allFileIds})}}});var VectorStores,VectorStoresPage,VectorStoreSearchResponsesPage;var init_vector_stores=__esm(()=>{init_core();init_file_batches();init_file_batches();init_files3();init_files3();init_pagination();VectorStores=class VectorStores extends APIResource{constructor(){super(...arguments);this.files=new Files3(this._client),this.fileBatches=new FileBatches(this._client)}create(body,options){return this._client.post("/vector_stores",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(vectorStoreId,options){return this._client.get(`/vector_stores/${vectorStoreId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(vectorStoreId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/vector_stores",VectorStoresPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(vectorStoreId,options){return this._client.delete(`/vector_stores/${vectorStoreId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}search(vectorStoreId,body,options){return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`,VectorStoreSearchResponsesPage,{body,method:"post",...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};VectorStoresPage=class VectorStoresPage extends CursorPage{};VectorStoreSearchResponsesPage=class VectorStoreSearchResponsesPage extends Page{};VectorStores.VectorStoresPage=VectorStoresPage;VectorStores.VectorStoreSearchResponsesPage=VectorStoreSearchResponsesPage;VectorStores.Files=Files3;VectorStores.VectorStoreFilesPage=VectorStoreFilesPage;VectorStores.FileContentResponsesPage=FileContentResponsesPage;VectorStores.FileBatches=FileBatches});var init_resources=__esm(()=>{init_audio();init_batches();init_beta();init_completions3();init_containers();init_embeddings();init_evals();init_files2();init_fine_tuning();init_graders2();init_images();init_models();init_moderations();init_responses();init_uploads2();init_vector_stores();init_chat2();init_shared()});var exports_openai={};__export(exports_openai,{toFile:()=>toFile,fileFromPath:()=>fileFromPath,default:()=>openai_default,UnprocessableEntityError:()=>UnprocessableEntityError,RateLimitError:()=>RateLimitError,PermissionDeniedError:()=>PermissionDeniedError,OpenAIError:()=>OpenAIError,OpenAI:()=>OpenAI,NotFoundError:()=>NotFoundError,InternalServerError:()=>InternalServerError,ConflictError:()=>ConflictError,BadRequestError:()=>BadRequestError,AzureOpenAI:()=>AzureOpenAI,AuthenticationError:()=>AuthenticationError,APIUserAbortError:()=>APIUserAbortError,APIError:()=>APIError,APIConnectionTimeoutError:()=>APIConnectionTimeoutError,APIConnectionError:()=>APIConnectionError});var _a,OpenAI,AzureOpenAI,_deployments_endpoints,API_KEY_SENTINEL="<Missing Key>",openai_default;var init_openai=__esm(()=>{init_qs();init_core();init_error();init_uploads();init_resources();init_batches();init_completions3();init_embeddings();init_files2();init_images();init_models();init_moderations();init_audio();init_beta();init_chat();init_containers();init_evals();init_fine_tuning();init_graders2();init_responses();init_uploads2();init_vector_stores();init_completions();init_uploads();init_error();OpenAI=class OpenAI extends APIClient{constructor({baseURL=readEnv("OPENAI_BASE_URL"),apiKey=readEnv("OPENAI_API_KEY"),organization=readEnv("OPENAI_ORG_ID")??null,project=readEnv("OPENAI_PROJECT_ID")??null,...opts}={}){if(apiKey===void 0)throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let options={apiKey,organization,project,...opts,baseURL:baseURL||"https://api.openai.com/v1"};if(!options.dangerouslyAllowBrowser&&isRunningInBrowser())throw new OpenAIError(`It looks like you're running in a browser-like environment.
2
+ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function __classPrivateFieldSet(receiver,state,value,kind,f){if(kind==="m")throw TypeError("Private method is not writable");if(kind==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value}function __classPrivateFieldGet(receiver,state,kind,f){if(kind==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)}var init_tslib=()=>{};var uuid4=function(){let{crypto:crypto2}=globalThis;if(crypto2?.randomUUID)return uuid4=crypto2.randomUUID.bind(crypto2),crypto2.randomUUID();let u8=new Uint8Array(1),randomByte=crypto2?()=>crypto2.getRandomValues(u8)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(c)=>(+c^randomByte()&15>>+c/4).toString(16))};function isAbortError(err){return typeof err==="object"&&err!==null&&(("name"in err)&&err.name==="AbortError"||("message"in err)&&String(err.message).includes("FetchRequestCanceledException"))}var castToError=(err)=>{if(err instanceof Error)return err;if(typeof err==="object"&&err!==null){try{if(Object.prototype.toString.call(err)==="[object Error]"){let hasCause="cause"in err,error=Error(err.message,hasCause?{cause:err.cause}:{});if(err.stack)error.stack=err.stack;if(hasCause&&!Object.prototype.hasOwnProperty.call(error,"cause"))error.cause=err.cause;if(err.name)error.name=err.name;return error}}catch{}try{return Error(JSON.stringify(err))}catch{}}return Error(err)};var OpenAIError,APIError,APIUserAbortError,APIConnectionError,APIConnectionTimeoutError,BadRequestError,AuthenticationError,PermissionDeniedError,NotFoundError,ConflictError,UnprocessableEntityError,RateLimitError,InternalServerError,LengthFinishReasonError,ContentFilterFinishReasonError,InvalidWebhookSignatureError,OAuthError,SubjectTokenProviderError;var init_error=__esm(()=>{OpenAIError=class OpenAIError extends Error{};APIError=class APIError extends OpenAIError{constructor(status,error,message,headers){super(`${APIError.makeMessage(status,error,message)}`);this.status=status,this.headers=headers,this.requestID=headers?.get("x-request-id"),this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message==="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;if(status&&msg)return`${status} ${msg}`;if(status)return`${status} status code (no body)`;if(msg)return msg;return"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;if(status===400)return new BadRequestError(status,error,message,headers);if(status===401)return new AuthenticationError(status,error,message,headers);if(status===403)return new PermissionDeniedError(status,error,message,headers);if(status===404)return new NotFoundError(status,error,message,headers);if(status===409)return new ConflictError(status,error,message,headers);if(status===422)return new UnprocessableEntityError(status,error,message,headers);if(status===429)return new RateLimitError(status,error,message,headers);if(status>=500)return new InternalServerError(status,error,message,headers);return new APIError(status,error,message,headers)}};APIUserAbortError=class APIUserAbortError extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}};APIConnectionError=class APIConnectionError extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0);if(cause)this.cause=cause}};APIConnectionTimeoutError=class APIConnectionTimeoutError extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}};BadRequestError=class BadRequestError extends APIError{};AuthenticationError=class AuthenticationError extends APIError{};PermissionDeniedError=class PermissionDeniedError extends APIError{};NotFoundError=class NotFoundError extends APIError{};ConflictError=class ConflictError extends APIError{};UnprocessableEntityError=class UnprocessableEntityError extends APIError{};RateLimitError=class RateLimitError extends APIError{};InternalServerError=class InternalServerError extends APIError{};LengthFinishReasonError=class LengthFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}};ContentFilterFinishReasonError=class ContentFilterFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};InvalidWebhookSignatureError=class InvalidWebhookSignatureError extends Error{constructor(message){super(message)}};OAuthError=class OAuthError extends APIError{constructor(status,error,headers){let finalMessage="OAuth2 authentication error",error_code=void 0;if(error&&typeof error==="object"){let errorData=error;error_code=errorData.error;let description=errorData.error_description;if(description&&typeof description==="string")finalMessage=description;else if(error_code)finalMessage=error_code}super(status,error,finalMessage,headers);this.error_code=error_code}};SubjectTokenProviderError=class SubjectTokenProviderError extends OpenAIError{constructor(message,provider,cause){super(message);this.provider=provider,this.cause=cause}}});function maybeObj(x){if(typeof x!=="object")return{};return x??{}}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function isObj(obj){return obj!=null&&typeof obj==="object"&&!Array.isArray(obj)}var startsWithSchemeRegexp,isAbsoluteURL=(url)=>startsWithSchemeRegexp.test(url),isArray=(val)=>(isArray=Array.isArray,isArray(val)),isReadonlyArray,validatePositiveInteger=(name,n)=>{if(typeof n!=="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n},safeJSON=(text)=>{try{return JSON.parse(text)}catch(err){return}};var init_values=__esm(()=>{init_error();startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isReadonlyArray=isArray});var sleep=(ms,...signals)=>new Promise((resolve,reject)=>{let activeSignals=[...new Set(signals.filter((signal)=>signal!=null))],timeout,settled=!1,cleanup=()=>{for(let signal of activeSignals)try{signal.removeEventListener("abort",abort)}catch{}},settle=(callback)=>{if(settled)return;if(settled=!0,timeout!==void 0)clearTimeout(timeout),timeout=void 0;cleanup(),callback()},abort=()=>{settle(()=>reject())};if(activeSignals.some((signal)=>signal.aborted)){abort();return}timeout=setTimeout(()=>{settle(resolve)},ms);for(let signal of activeSignals){if(settled)break;try{signal.addEventListener("abort",abort,{once:!0})}catch(error){settle(()=>reject(error))}}if(activeSignals.some((signal)=>signal.aborted))abort()});function subscribeWeakly(signal,reference,registry){let subscription=subscriptions.get(signal);if(!subscription){let callbacks=new Set,abort=()=>{subscriptions.delete(signal);for(let callback of callbacks)registry.unregister(callback),callback.deref()?.();callbacks.clear()};subscription={callbacks,abort},signal.addEventListener("abort",abort,{once:!0}),subscriptions.set(signal,subscription)}let owner=subscription;return owner.callbacks.add(reference),()=>{if(owner.callbacks.delete(reference),registry.unregister(reference),owner.callbacks.size===0){if(subscriptions.get(signal)===owner)subscriptions.delete(signal);signal.removeEventListener("abort",owner.abort)}}}function releaseOnAbort(signal,callbacks,abort){signal.addEventListener("abort",()=>callbacks.deref()?.delete(abort),{once:!0})}function retainRequestAbortCallback(owner,abort,requestSignal){if(typeof weakGlobals.WeakRef==="function"&&finalizer&&!requestSignal.aborted){let callbacks=callbackOwners.get(owner);if(!callbacks)callbacks=new Set,callbackOwners.set(owner,callbacks);callbacks.add(abort),releaseOnAbort(requestSignal,new weakGlobals.WeakRef(callbacks),abort)}}function addRequestAbortListener(signal,abort,requestSignal){if(signal.aborted)return abort(),()=>{};if(typeof weakGlobals.WeakRef!=="function"||!finalizer)return signal.addEventListener("abort",abort,{once:!0}),()=>signal.removeEventListener("abort",abort);let reference=new weakGlobals.WeakRef(abort),cleanup=subscribeWeakly(signal,reference,finalizer);return finalizer.register(abort,cleanup,reference),retainRequestAbortCallback(requestSignal,abort,requestSignal),cleanup}var weakGlobals,finalizer,callbackOwners,subscriptions;var init_abort=__esm(()=>{weakGlobals=globalThis,finalizer=typeof weakGlobals.FinalizationRegistry==="function"?new weakGlobals.FinalizationRegistry((cleanup)=>{try{cleanup()}catch{}}):void 0,callbackOwners=new WeakMap,subscriptions=new WeakMap});function getDefaultFetch(){if(typeof fetch<"u")return fetch;throw 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 makeReadableStream(...args){let ReadableStream2=globalThis.ReadableStream;if(typeof ReadableStream2>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new ReadableStream2(...args)}function ReadableStreamFrom(iterable,strategy){let iter=Symbol.asyncIterator in iterable?iterable[Symbol.asyncIterator]():iterable[Symbol.iterator]();return makeReadableStream({start(){},async pull(controller){let{done,value}=await iter.next();if(done)controller.close();else controller.enqueue(value)},async cancel(){await iter.return?.()}},strategy)}function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();if(result?.done)reader.releaseLock();return result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CancelReadableStream(stream){if(stream===null||typeof stream!=="object")return;if(stream[Symbol.asyncIterator]){await stream[Symbol.asyncIterator]().return?.();return}let reader=stream.getReader(),cancelPromise=reader.cancel();reader.releaseLock(),await cancelPromise}function encodeUTF8(str){let encoder;return(encodeUTF8_??(encoder=new globalThis.TextEncoder,encodeUTF8_=encoder.encode.bind(encoder)))(str)}function decodeUTF8(bytes){let decoder;return(decodeUTF8_??(decoder=new globalThis.TextDecoder,decodeUTF8_=decoder.decode.bind(decoder)))(bytes)}var encodeUTF8_,decodeUTF8_;class LineDecoder{constructor(){_LineDecoder_instances.add(this),_LineDecoder_buffer.set(this,void 0),_LineDecoder_start.set(this,void 0),_LineDecoder_end.set(this,void 0),_LineDecoder_searchIndex.set(this,void 0),_LineDecoder_skipLeadingLF.set(this,void 0),__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk;if(chunk instanceof ArrayBuffer)binaryChunk=new Uint8Array(chunk);else if(typeof chunk==="string")binaryChunk=encodeUTF8(chunk);else binaryChunk=chunk;if(binaryChunk.length===0)return[];if(__classPrivateFieldGet(this,_LineDecoder_skipLeadingLF,"f")){if(__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),binaryChunk[0]===10)binaryChunk=binaryChunk.subarray(1);if(binaryChunk.length===0)return[]}__classPrivateFieldGet(this,_LineDecoder_instances,"m",_LineDecoder_append).call(this,binaryChunk);let lines=[],patternIndex;while((patternIndex=findNewlineIndex(__classPrivateFieldGet(this,_LineDecoder_buffer,"f"),__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f")))!=null){let line=decodeUTF8(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),patternIndex.preceding));if(lines.push(line),__classPrivateFieldSet(this,_LineDecoder_start,patternIndex.index,"f"),patternIndex.carriage){if(__classPrivateFieldGet(this,_LineDecoder_start,"f")<__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f")[__classPrivateFieldGet(this,_LineDecoder_start,"f")]===10)__classPrivateFieldSet(this,_LineDecoder_start,__classPrivateFieldGet(this,_LineDecoder_start,"f")+1,"f");else if(__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f"))__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!0,"f")}__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f")}if(__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_end,"f"),"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")){if(__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES)__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f")}else if(lines.length>0&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(length<=MAX_RETAINED_BUFFER_BYTES||__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>length*4){let capacity=length<=MAX_RETAINED_BUFFER_BYTES?Math.min(Math.max(length*2,256),MAX_RETAINED_BUFFER_BYTES):length*2,buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,length,"f")}}return lines}flush(){if(__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f"))return[];return this.decode(`
3
+ `)}}function findNewlineIndex(buffer,start,end){for(let i=start;i<end;i++){if(buffer[i]===10)return{preceding:i,index:i+1,carriage:!1};if(buffer[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function findDoubleNewlineIndex(buffer){for(let i=0;i<buffer.length-1;i++){let firstEndingLength=lineEndingLength(buffer,i);if(firstEndingLength>0){let secondEndingIndex=i+firstEndingLength,secondEndingLength=lineEndingLength(buffer,secondEndingIndex);if(secondEndingLength>0)return secondEndingIndex+secondEndingLength}}return-1}function lineEndingLength(buffer,index){if(buffer[index]===10)return 1;if(buffer[index]===13)return buffer[index+1]===10?2:1;return 0}var _LineDecoder_instances,_LineDecoder_buffer,_LineDecoder_start,_LineDecoder_end,_LineDecoder_searchIndex,_LineDecoder_skipLeadingLF,_LineDecoder_append,MAX_RETAINED_BUFFER_BYTES=65536;var init_line=__esm(()=>{init_tslib();_LineDecoder_buffer=new WeakMap,_LineDecoder_start=new WeakMap,_LineDecoder_end=new WeakMap,_LineDecoder_searchIndex=new WeakMap,_LineDecoder_skipLeadingLF=new WeakMap,_LineDecoder_instances=new WeakSet,_LineDecoder_append=function(chunk){if(__classPrivateFieldGet(this,_LineDecoder_end,"f")+chunk.length>__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(__classPrivateFieldGet(this,_LineDecoder_start,"f")>=__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length/2&&length+chunk.length<=__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length)__classPrivateFieldGet(this,_LineDecoder_buffer,"f").copyWithin(0,__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"));else{let capacity=Math.max(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length*2,length+chunk.length,256),buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f")}__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f")}__classPrivateFieldGet(this,_LineDecoder_buffer,"f").set(chunk,__classPrivateFieldGet(this,_LineDecoder_end,"f")),__classPrivateFieldSet(this,_LineDecoder_end,__classPrivateFieldGet(this,_LineDecoder_end,"f")+chunk.length,"f")};LineDecoder.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);LineDecoder.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function noop(){}function makeLogFn(fnLevel,logger,logLevel){if(!logger||levelNumbers[fnLevel]>levelNumbers[logLevel])return noop;else return logger[fnLevel].bind(logger)}function loggerFor(client){let logger=client.logger,logLevel=client.logLevel??"off";if(!logger)return noopLogger;let cachedLogger=cachedLoggers.get(logger);if(cachedLogger&&cachedLogger[0]===logLevel)return cachedLogger[1];let levelLogger={error:makeLogFn("error",logger,logLevel),warn:makeLogFn("warn",logger,logLevel),info:makeLogFn("info",logger,logLevel),debug:makeLogFn("debug",logger,logLevel)};return cachedLoggers.set(logger,[logLevel,levelLogger]),levelLogger}function isSensitiveQueryParameter(name){let normalized=name.toLowerCase().replace(/[-_]/gu,"");return sensitiveQueryNames.has(normalized)||sensitiveQueryNames.has(normalized.replace(/^x/u,""))}function isSensitiveHeader(name){return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu,"-"))||isSensitiveQueryParameter(name)}function redactURL(value){let url=new URL(value);url.username="",url.password="",url.hash="";for(let name of url.searchParams.keys())if(isSensitiveQueryParameter(name))url.searchParams.set(name,"***");return url.href}var levelNumbers,parseLogLevel=(maybeLevel,sourceName,client)=>{if(!maybeLevel)return;if(hasOwn(levelNumbers,maybeLevel))return maybeLevel;loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);return},noopLogger,cachedLoggers,sensitiveQueryNames,sensitiveHeaderNames,formatRequestDetails=(details)=>{if(details.options){if(details.options={...details.options},delete details.options.headers,details.options.path){let path=details.options.path,redacted=new URL(redactURL(new URL(path,"https://redacted.invalid").href));details.options.path=redacted.origin==="https://redacted.invalid"?`${path.startsWith("/")?"/":""}${redacted.pathname.slice(1)}${redacted.search}`:redacted.href}if(details.options.query)details.options.query=Object.fromEntries(Object.entries(details.options.query).map(([name,value])=>[name,isSensitiveQueryParameter(name)?"***":value]))}if(details.url)details.url=redactURL(details.url);if(details.headers)details.headers=Object.fromEntries((details.headers instanceof Headers?[...details.headers]:Object.entries(details.headers)).map(([name,value])=>[name,isSensitiveHeader(name)?"***":value]));if("retryOfRequestLogID"in details){if(details.retryOfRequestLogID)details.retryOf=details.retryOfRequestLogID;delete details.retryOfRequestLogID}return details};var init_log=__esm(()=>{init_values();levelNumbers={off:0,error:200,warn:300,info:400,debug:500};noopLogger={error:noop,warn:noop,info:noop,debug:noop},cachedLoggers=new WeakMap;sensitiveQueryNames=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","signingsecret","sig","signature","xgoogsignature","xgoogcredential","xamzsecuritytoken","xamzsignature","xamzcredential"]);sensitiveHeaderNames=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"])});function isTransportAbortError(error){return!(error instanceof APIError)&&isAbortError(error)}function createStreamTeeQueue(){let entries=[],head=0,canceled=!1;return{get length(){return entries.length-head},get canceled(){return canceled},enqueue(value){if(!canceled)entries.push(value)},dequeue(){if(head===entries.length)return;let value=entries[head];if(entries[head]=void 0,head+=1,head===entries.length)entries=[],head=0;else if(head>=1024&&head*2>=entries.length)entries=entries.slice(head),head=0;return value},cancel(){canceled=!0,entries.length=0,head=0}}}function createAbortableSSESource(body,signal){let reader=typeof body.getReader==="function"?body.getReader():void 0,source=reader?{next:()=>reader.read(),return:()=>reader.cancel()}:ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator](),ended={value:void 0,done:!0},closed=!1,canceled=!1,cancellation,interrupt,waitForAbort=()=>new Promise((resolve)=>{interrupt=resolve}),cancel=()=>{if(canceled||closed)return cancellation;canceled=!0;try{cancellation=Promise.resolve(source.return?.())}catch(error){cancellation=Promise.reject(error)}return cancellation.catch(()=>{return}),cancellation},abort=()=>{queueMicrotask(()=>{interrupt?.(),cancel()})};return{iterator:{async next(){if(signal.aborted)return ended;let aborted=waitForAbort().then(()=>ended);try{let result=await Promise.race([source.next(),aborted]);if(signal.aborted)return ended;if(result.done)return closed=!0,ended;return{value:result.value,done:!1}}catch(error){if(signal.aborted&&(isAbortError(error)||error===signal.reason))return ended;throw error}finally{interrupt=void 0}},async return(){let pending=cancel();if(pending&&!signal.aborted){let aborted=waitForAbort();try{if(!signal.aborted)await Promise.race([pending,aborted])}finally{interrupt=void 0}}return ended},[Symbol.asyncIterator](){return this}},start(){if(signal.addEventListener("abort",abort,{once:!0}),signal.aborted)abort()},async cleanup(failed){let cleanupError;try{signal.removeEventListener("abort",abort)}catch(error){cleanupError=error}if(!closed){let pending=cancel();if(pending&&!failed&&!signal.aborted)try{await pending}catch(error){cleanupError??(cleanupError=error)}}if(reader)try{reader.releaseLock()}catch(error){cleanupError??(cleanupError=error)}if(cleanupError!==void 0&&!failed&&!signal.aborted)throw cleanupError}}}async function*_iterSSEMessages(response,controller){if(!response.body){if(controller.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative")throw new OpenAIError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new OpenAIError("Attempted to iterate over a response with no body")}let sseDecoder=new SSEDecoder,lineDecoder=new LineDecoder,{signal}=controller,source=createAbortableSSESource(response.body,signal),failed=!1;try{source.start();for await(let sseChunk of iterSSEChunks(source.iterator)){if(signal.aborted)return;for(let line of lineDecoder.decode(sseChunk)){if(signal.aborted)return;let sse=sseDecoder.decode(line);if(sse)yield sse}}if(signal.aborted)return;for(let line of lineDecoder.flush()){if(signal.aborted)return;let sse=sseDecoder.decode(line);if(sse)yield sse}if(signal.aborted)return;let pending=sseDecoder.flush();if(pending)yield pending}catch(error){if(failed=!0,!signal.aborted||!isAbortError(error)&&error!==signal.reason)throw error}finally{await source.cleanup(failed)}}async function*iterSSEChunks(iterator){let data=new Uint8Array,dataStart=0,dataEnd=0,searchStartIndex=0;for await(let chunk of iterator){if(chunk==null)continue;let binaryChunk;if(chunk instanceof ArrayBuffer)binaryChunk=new Uint8Array(chunk);else if(typeof chunk==="string")binaryChunk=encodeUTF8(chunk);else binaryChunk=chunk;if(dataEnd+binaryChunk.length>data.length){let bufferedLength=dataEnd-dataStart;if(dataStart>=data.length/2&&bufferedLength+binaryChunk.length<=data.length)data.copyWithin(0,dataStart,dataEnd);else{let newData=new Uint8Array(Math.max(data.length*2,bufferedLength+binaryChunk.length));newData.set(data.subarray(dataStart,dataEnd)),data=newData}searchStartIndex-=dataStart,dataStart=0,dataEnd=bufferedLength}data.set(binaryChunk,dataEnd),dataEnd+=binaryChunk.length;let patternIndex;while((patternIndex=findDoubleNewlineIndex(data.subarray(searchStartIndex,dataEnd)))!==-1)patternIndex+=searchStartIndex,yield data.slice(dataStart,patternIndex),dataStart=patternIndex,searchStartIndex=dataStart;searchStartIndex=Math.max(dataStart,dataEnd-DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES)}if(dataEnd>dataStart)yield data.slice(dataStart,dataEnd)}class SSEDecoder{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(line){if(line.endsWith("\r"))line=line.slice(0,-1);if(!line){if(!this.event&&!this.data.length)return null;let sse={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],sse}if(this.chunks.push(line),line.startsWith(":"))return null;let[fieldname,,initialValue]=partition(line,":"),value=initialValue;if(value.startsWith(" "))value=value.slice(1);if(fieldname==="event")this.event=value;else if(fieldname==="data")this.data.push(value);return null}flush(){return this.decode("")}}function partition(str,delimiter){let index=str.indexOf(delimiter);if(index!==-1)return[str.slice(0,index),delimiter,str.slice(index+delimiter.length)];return[str,"",""]}var _Stream_instances,_Stream_client,_Stream_isTeeBranch,_Stream_cancelIterator,Stream,DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES=3;var init_streaming=__esm(()=>{init_tslib();init_error();init_line();init_log();Stream=class Stream{constructor(iterator,controller,client){_Stream_instances.add(this),_Stream_client.set(this,void 0),_Stream_isTeeBranch.set(this,!1),this.iterator=iterator,this.controller=controller,__classPrivateFieldSet(this,_Stream_client,client,"f")}static fromSSEResponse(response,controller,client,synthesizeEventData){let consumed=!1,logger=client?loggerFor(client):console;async function*iterator(){if(consumed)throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1,receivedCompletionSentinel=!1,messages=_iterSSEMessages(response,controller),closeMessages=messages.return.bind(messages);messages.return=(value)=>{if(!receivedCompletionSentinel)controller.abort();return closeMessages(value)};try{for await(let sse of messages){if(sse.data==="[DONE]"){receivedCompletionSentinel=!0;break}if(sse.event===null||!sse.event.startsWith("thread.")){let data;try{data=JSON.parse(sse.data)}catch{throw logger.error("Could not parse message into JSON:"),logger.error("From chunk:"),SyntaxError("Error reading response: malformed server-sent event JSON.")}if(sse.event==="error")throw new APIError(void 0,data?.error??data,void 0,response.headers);if(data&&data.error)throw new APIError(void 0,data.error,void 0,response.headers);yield synthesizeEventData?{event:sse.event,data}:data}else{let data;try{data=JSON.parse(sse.data)}catch{throw logger.error("Could not parse message into JSON:"),logger.error("From chunk:"),SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:sse.event,data}}}done=!0}catch(e){if(receivedCompletionSentinel||isTransportAbortError(e)||controller.signal.aborted&&e===controller.signal.reason)return;throw e}finally{if(!done)controller.abort()}}return new Stream(iterator,controller,client)}static fromReadableStream(readableStream,controller,client){let consumed=!1;async function*iterLines(){let lineDecoder=new LineDecoder,reader=readableStream.getReader(),closed=!1,cancelPromise,cancel=()=>{cancelPromise??(cancelPromise=reader.cancel()),cancelPromise.catch(()=>{return})};controller.signal.addEventListener("abort",cancel,{once:!0});try{if(controller.signal.aborted){cancel();return}while(!0){let{value:chunk,done}=await reader.read();if(done){closed=!0;break}if(controller.signal.aborted)return;for(let line of lineDecoder.decode(chunk)){if(controller.signal.aborted)return;yield line}}if(controller.signal.aborted)return;for(let line of lineDecoder.flush()){if(controller.signal.aborted)return;yield line}}finally{if(controller.signal.removeEventListener("abort",cancel),!closed)cancel();reader.releaseLock()}}async function*iterator(){if(consumed)throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let line of iterLines())if(line){let data;try{data=JSON.parse(line)}catch(error){if(error instanceof SyntaxError)throw SyntaxError("Error reading response: malformed newline-delimited JSON.");throw error}yield data}done=!0}catch(e){if(controller.signal.aborted||isAbortError(e))return;throw e}finally{if(!done)controller.abort()}}return new Stream(iterator,controller,client)}[(_Stream_client=new WeakMap,_Stream_isTeeBranch=new WeakMap,_Stream_instances=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}__betaTransformIterator(transform){this.iterator=transform(this.iterator.bind(this))}tee(){let{controller}=this,left=createStreamTeeQueue(),right=createStreamTeeQueue(),iterator=this.iterator(),teeIterator=(queue)=>({next:()=>{if(queue.canceled)return Promise.resolve({value:void 0,done:!0});if(queue.length===0){let result=iterator.next();left.enqueue(result),right.enqueue(result)}return queue.dequeue()},return:async()=>{if(!queue.canceled){if(queue.cancel(),left.canceled&&right.canceled)await __classPrivateFieldGet(this,_Stream_instances,"m",_Stream_cancelIterator).call(this,iterator,controller)}return{value:void 0,done:!0}}}),branch=(queue)=>{let stream=new Stream(()=>teeIterator(queue),controller,__classPrivateFieldGet(this,_Stream_client,"f"));return __classPrivateFieldSet(stream,_Stream_isTeeBranch,!0,"f"),stream};return[branch(left),branch(right)]}toReadableStream(){let{controller}=this,iter,cancellation,cancel=()=>cancellation??(cancellation=__classPrivateFieldGet(this,_Stream_instances,"m",_Stream_cancelIterator).call(this,iter,controller));return makeReadableStream({start:async()=>{iter=this[Symbol.asyncIterator]()},async pull(ctrl){try{let{value,done}=await iter.next();if(done)return ctrl.close();let bytes=encodeUTF8(JSON.stringify(value)+`
6
+ `);ctrl.enqueue(bytes)}catch(err){ctrl.error(err),cancel().catch(()=>{return})}},cancel})}};_Stream_cancelIterator=async function(iterator,controller){let returnMethod=iterator.return;if(returnMethod){if(!__classPrivateFieldGet(this,_Stream_isTeeBranch,"f"))controller.abort();await Reflect.apply(returnMethod,iterator,[])}}});async function defaultParseResponse(client,props){let{response,requestLogID,retryOfRequestLogID,startTime}=props,jsonBodyLength,body=await(async()=>{if(props.options.stream){if(loggerFor(client).debug("response",response.status,response.url,response.headers,response.body),props.options.__streamClass)return props.options.__streamClass.fromSSEResponse(response,props.controller,client,props.options.__synthesizeEventData);return Stream.fromSSEResponse(response,props.controller,client,props.options.__synthesizeEventData)}if(response.status===204)return null;if(props.options.__binaryResponse)return response;let mediaType=response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(mediaType?.includes("application/json")||mediaType?.endsWith("+json")){if(response.headers.get("content-length")==="0")return;let bodyText=await response.text();if(!bodyText)return;let json=JSON.parse(bodyText);return jsonBodyLength=bodyText.length,addRequestID(json,response)}return await response.text()})().catch((error)=>{throw asAbortError(error,props.controller.signal)});if(client.logLevel==="debug")loggerFor(client).debug(`[${requestLogID}] response parsed`,formatRequestDetails({retryOfRequestLogID,url:response.url,status:response.status,body:jsonBodyLength===void 0?body:{type:"json",length:jsonBodyLength},durationMs:Date.now()-startTime}));return body}function asAbortError(error,signal){if(!signal.aborted||error!==signal.reason||isAbortError(error))return error;let message="This operation was aborted",DOMExceptionConstructor=globalThis.DOMException;return typeof DOMExceptionConstructor==="function"?new DOMExceptionConstructor(message,"AbortError"):Object.assign(Error(message),{name:"AbortError"})}function addRequestID(value,response){if(!value||typeof value!=="object"||Array.isArray(value))return value;return Object.defineProperty(value,"_request_id",{value:response.headers.get("x-request-id"),enumerable:!1})}var init_parse=__esm(()=>{init_streaming();init_log()});var VERSION="7.47.0";function getDetectedPlatform(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function getBrowserInfo(){if(typeof navigator>"u"||!navigator)return null;let browserPatterns=[{key:"edge",pattern:/\bEdg(?:e|A|iOS)?\b(?:\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,pattern}of browserPatterns){let match=pattern.exec(navigator.userAgent);if(match){let major=match[1]||0,minor=match[2]||0,patch=match[3]||0;return{browser:key,version:`${major}.${minor}.${patch}`}}}return null}var isRunningInBrowser=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",getPlatformProperties=()=>{let detectedPlatform=getDetectedPlatform();if(detectedPlatform==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(Deno.build.os),"X-Stainless-Arch":normalizeArch(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":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(detectedPlatform==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(globalThis.process.platform??"unknown"),"X-Stainless-Arch":normalizeArch(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let browserInfo=getBrowserInfo();if(browserInfo)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${browserInfo.browser}`,"X-Stainless-Runtime-Version":browserInfo.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},normalizeArch=(arch)=>{if(arch==="x32")return"x32";if(arch==="x86_64"||arch==="x64")return"x64";if(arch==="arm")return"arm";if(arch==="aarch64"||arch==="arm64")return"arm64";if(arch)return`other:${arch}`;return"unknown"},normalizePlatform=(platform)=>{if(platform=platform.toLowerCase(),platform.includes("ios"))return"iOS";if(platform==="android")return"Android";if(platform==="darwin")return"MacOS";if(platform==="win32")return"Windows";if(platform==="freebsd")return"FreeBSD";if(platform==="openbsd")return"OpenBSD";if(platform==="linux")return"Linux";if(platform)return`Other:${platform}`;return"Unknown"},_platformHeaders,getPlatformHeaders=()=>_platformHeaders??(_platformHeaders=getPlatformProperties());var init_detect_platform=()=>{};function observeJSONRequestBody(body,observer){let observers=jsonRequestBodyObservers.get(body);if(!observers)observers=new Set,jsonRequestBodyObservers.set(body,observers);return observers.add(observer),()=>{let active=jsonRequestBodyObservers.get(body);if(!active)return;if(active.delete(observer),active.size===0)jsonRequestBodyObservers.delete(body)}}var jsonRequestBodyObservers,FallbackEncoder=({headers,body})=>{let observers=typeof body==="object"&&body!==null?jsonRequestBodyObservers.get(body):void 0,encoded;if(!observers||observers.size===0)encoded=JSON.stringify(body);else{let active=[...observers];encoded=JSON.stringify(body,function(key,value){let observed=value;for(let observer of active){let replacement=observer.value(this,key,observed);if(replacement!==void 0)observed=replacement}return observed});for(let observer of active)observer.complete()}return{bodyHeaders:{"content-type":"application/json"},body:encoded}};var init_request_options=__esm(()=>{jsonRequestBodyObservers=new WeakMap});var default_format="RFC3986",default_formatter,formatters,RFC1738="RFC1738";var init_formats=__esm(()=>{default_formatter=String,formatters={RFC1738:(v)=>String(v).replace(/%20/g,"+"),RFC3986:default_formatter}});function is_buffer(obj){if(!obj||typeof obj!=="object")return!1;return!!(obj.constructor&&obj.constructor.isBuffer&&obj.constructor.isBuffer(obj))}function maybe_map(val,fn){if(isArray(val)){let mapped=[];for(let item of val)mapped.push(fn(item));return mapped}return fn(val)}var cachedHas,has=(obj,key)=>{let resolvedHas=cachedHas??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return cachedHas=resolvedHas,resolvedHas(obj,key)},hex_table,limit=1024,encode=(str,_defaultEncoder,charset,_kind,format)=>{if(str.length===0)return str;let string=str;if(typeof str==="symbol")string=Symbol.prototype.toString.call(str);else if(typeof str!=="string")string=String(str);if(charset==="iso-8859-1")return escape(string).replace(/%u[0-9a-f]{4}/gi,($0)=>"%26%23"+Number.parseInt($0.slice(2),16)+"%3B");let out="";for(let j=0;j<string.length;){let segmentEnd=Math.min((Math.floor(j/limit)+1)*limit,string.length);if(segmentEnd<string.length&&string.codePointAt(segmentEnd-1)>65535)segmentEnd+=1;let segment=string.length>=limit?string.slice(j,segmentEnd):string,arr=[];for(let i=0;i<segment.length;++i){let c=segment.charCodeAt(i);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||format===RFC1738&&(c===40||c===41)){arr[arr.length]=segment.charAt(i);continue}if(c<128){arr[arr.length]=hex_table[c];continue}if(c<2048){arr[arr.length]=hex_table[192|c>>6]+hex_table[128|c&63];continue}if(c<55296||c>=57344){arr[arr.length]=hex_table[224|c>>12]+hex_table[128|c>>6&63]+hex_table[128|c&63];continue}i+=1,c=65536+((c&1023)<<10|segment.charCodeAt(i)&1023),arr[arr.length]=hex_table[240|c>>18]+hex_table[128|c>>12&63]+hex_table[128|c>>6&63]+hex_table[128|c&63]}out+=arr.join(""),j=segmentEnd}return out};var init_utils=__esm(()=>{init_formats();init_values();hex_table=(()=>{let array=[];for(let i=0;i<256;++i)array.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase());return array})()});function is_non_nullish_primitive(v){return typeof v==="string"||typeof v==="number"||typeof v==="boolean"||typeof v==="symbol"||typeof v==="bigint"}function inner_stringify(object,prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,sideChannel){let obj=object,tmp_sc=sideChannel,step=0,find_flag=!1;while((tmp_sc=tmp_sc.get(sentinel))!==void 0&&!find_flag){let pos=tmp_sc.get(object);if(step+=1,pos!==void 0)if(pos===step)throw RangeError("Cyclic object value");else find_flag=!0;if(tmp_sc.get(sentinel)===void 0)step=0}if(typeof filter==="function")obj=filter(prefix,obj);else if(obj instanceof Date)obj=serializeDate?.(obj);else if(generateArrayPrefix==="comma"&&isArray(obj))obj=maybe_map(obj,(value)=>{if(value instanceof Date)return serializeDate?.(value);return value});if(obj===null){if(strictNullHandling)return encoder&&!encodeValuesOnly?encoder(prefix,defaults.encoder,charset,"key",format):prefix;obj=""}if(is_non_nullish_primitive(obj)||is_buffer(obj)){if(encoder){let key_value=encodeValuesOnly?prefix:encoder(prefix,defaults.encoder,charset,"key",format);return[formatter?.(key_value)+"="+formatter?.(encoder(obj,defaults.encoder,charset,"value",format))]}return[formatter?.(prefix)+"="+formatter?.(String(obj))]}let values=[];if(obj===void 0)return values;let obj_keys;if(generateArrayPrefix==="comma"&&isArray(obj)){if(encodeValuesOnly&&encoder)obj=maybe_map(obj,encoder);obj_keys=[{value:obj.length>0?obj.join(",")||null:void 0}]}else if(isArray(filter))obj_keys=filter;else{let keys=Object.keys(obj);if(sort)keys.sort(sort);obj_keys=keys}let encoded_prefix=encodeDotInKeys?String(prefix).replace(/\./g,"%2E"):String(prefix),adjusted_prefix=commaRoundTrip&&isArray(obj)&&obj.length===1?encoded_prefix+"[]":encoded_prefix;if(allowEmptyArrays&&isArray(obj)&&obj.length===0)return adjusted_prefix+"[]";for(let key of obj_keys){let value=typeof key==="object"&&key.value!==void 0?key.value:obj[key];if(skipNulls&&value===null)continue;let encoded_key=allowDots&&encodeDotInKeys?key.replace(/\./g,"%2E"):key,key_prefix;if(isArray(obj))key_prefix=typeof generateArrayPrefix==="function"?generateArrayPrefix(adjusted_prefix,encoded_key):adjusted_prefix;else key_prefix=adjusted_prefix+(allowDots?"."+encoded_key:"["+encoded_key+"]");sideChannel.set(object,step);let valueSideChannel=new WeakMap([[sentinel,sideChannel]]);push_to_array(values,inner_stringify(value,key_prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,generateArrayPrefix==="comma"&&encodeValuesOnly&&isArray(obj)?null:encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,valueSideChannel))}return values}function normalize_stringify_options(opts=defaults){if(opts.allowEmptyArrays!==void 0&&typeof opts.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(opts.encodeDotInKeys!==void 0&&typeof opts.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(opts.encoder!==null&&opts.encoder!==void 0&&typeof opts.encoder!=="function")throw TypeError("Encoder has to be a function.");let charset=opts.charset||defaults.charset;if(opts.charset!==void 0&&opts.charset!=="utf-8"&&opts.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let format=default_format;if(opts.format!==void 0){if(!has(formatters,opts.format))throw TypeError("Unknown format option provided.");format=opts.format}let formatter=formatters[format],filter=defaults.filter;if(typeof opts.filter==="function"||isArray(opts.filter))filter=opts.filter;let arrayFormat;if(opts.arrayFormat&&opts.arrayFormat in array_prefix_generators)arrayFormat=opts.arrayFormat;else if("indices"in opts)arrayFormat=opts.indices?"indices":"repeat";else arrayFormat=defaults.arrayFormat;if("commaRoundTrip"in opts&&typeof opts.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let allowDots;if(opts.allowDots===void 0)allowDots=!!opts.encodeDotInKeys===!0?!0:defaults.allowDots;else allowDots=!!opts.allowDots;return{addQueryPrefix:typeof opts.addQueryPrefix==="boolean"?opts.addQueryPrefix:defaults.addQueryPrefix,allowDots,allowEmptyArrays:typeof opts.allowEmptyArrays==="boolean"?!!opts.allowEmptyArrays:defaults.allowEmptyArrays,arrayFormat,charset,charsetSentinel:typeof opts.charsetSentinel==="boolean"?opts.charsetSentinel:defaults.charsetSentinel,commaRoundTrip:!!opts.commaRoundTrip,delimiter:opts.delimiter===void 0?defaults.delimiter:opts.delimiter,encode:typeof opts.encode==="boolean"?opts.encode:defaults.encode,encodeDotInKeys:typeof opts.encodeDotInKeys==="boolean"?opts.encodeDotInKeys:defaults.encodeDotInKeys,encoder:typeof opts.encoder==="function"?opts.encoder:defaults.encoder,encodeValuesOnly:typeof opts.encodeValuesOnly==="boolean"?opts.encodeValuesOnly:defaults.encodeValuesOnly,filter,format,formatter,serializeDate:typeof opts.serializeDate==="function"?opts.serializeDate:defaults.serializeDate,skipNulls:typeof opts.skipNulls==="boolean"?opts.skipNulls:defaults.skipNulls,sort:typeof opts.sort==="function"?opts.sort:null,strictNullHandling:typeof opts.strictNullHandling==="boolean"?opts.strictNullHandling:defaults.strictNullHandling}}function stringify(object,opts={}){let obj=object,options=normalize_stringify_options(opts),obj_keys,filter;if(typeof options.filter==="function")filter=options.filter,obj=filter("",obj);else if(isArray(options.filter))filter=options.filter,obj_keys=filter;let keys=[];if(typeof obj!=="object"||obj===null)return"";let generateArrayPrefix=array_prefix_generators[options.arrayFormat],commaRoundTrip=generateArrayPrefix==="comma"&&options.commaRoundTrip;if(!obj_keys)obj_keys=Object.keys(obj);if(options.sort)obj_keys.sort(options.sort);let sideChannel=new WeakMap;for(let key of obj_keys){if(options.skipNulls&&obj[key]===null)continue;push_to_array(keys,inner_stringify(obj[key],key,generateArrayPrefix,commaRoundTrip,options.allowEmptyArrays,options.strictNullHandling,options.skipNulls,options.encodeDotInKeys,options.encode?options.encoder:null,options.filter,options.sort,options.allowDots,options.serializeDate,options.format,options.formatter,options.encodeValuesOnly,options.charset,sideChannel))}let joined=keys.join(options.delimiter),prefix=options.addQueryPrefix===!0?"?":"";if(options.charsetSentinel)prefix+=options.charset==="iso-8859-1"?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&";return joined.length>0?prefix+joined:""}var array_prefix_generators,push_to_array=function(arr,value_or_array){Array.prototype.push.apply(arr,isArray(value_or_array)?value_or_array:[value_or_array])},toISOString,defaults,sentinel;var init_stringify=__esm(()=>{init_utils();init_formats();init_values();array_prefix_generators={brackets(prefix){return String(prefix)+"[]"},comma:"comma",indices(prefix,key){return String(prefix)+"["+key+"]"},repeat(prefix){return String(prefix)}},defaults={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:encode,encodeValuesOnly:!1,format:default_format,formatter:default_formatter,indices:!1,serializeDate(date){return(toISOString??(toISOString=Function.prototype.call.bind(Date.prototype.toISOString)))(date)},skipNulls:!1,strictNullHandling:!1};sentinel={}});function stringifyQuery(query){return stringify(query,{arrayFormat:"brackets"})}var init_query=__esm(()=>{init_stringify()});function resolveDataResidency(options){if(options.dataResidency===null||options.dataResidency===void 0)return;if(hasOwn(options,"baseURL"))throw new OpenAIError("The `dataResidency` and `baseURL` options are mutually exclusive.");let endpoint=endpoints.get(options.dataResidency);if(endpoint===void 0)throw new OpenAIError("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return endpoint}function assertNoDataResidency(dataResidency,clientName){if(dataResidency!==null&&dataResidency!==void 0)throw new OpenAIError(`${clientName} does not support \`dataResidency\`.`)}var endpoints;var init_data_residency=__esm(()=>{init_error();init_values();endpoints=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"]])});var _APIPromise_client,APIPromise;var init_api_promise=__esm(()=>{init_tslib();init_parse();APIPromise=class APIPromise extends Promise{constructor(client,responsePromise,parseResponse=defaultParseResponse){super((resolve)=>{resolve(null)});this.responsePromise=responsePromise,this.parseResponse=parseResponse,_APIPromise_client.set(this,void 0),__classPrivateFieldSet(this,_APIPromise_client,client,"f")}_thenUnwrap(transform){return new APIPromise(__classPrivateFieldGet(this,_APIPromise_client,"f"),this.responsePromise,async(client,props)=>addRequestID(transform(await this.parseResponse(client,props),props),props.response))}asResponse(){return this.responsePromise.then((p)=>p.response)}async withResponse(){let[data,response]=await Promise.all([this.parse(),this.asResponse()]);return{data,response,request_id:response.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((data)=>this.parseResponse(__classPrivateFieldGet(this,_APIPromise_client,"f"),data));return this.parsedPromise}then(onfulfilled,onrejected){return this.parse().then(onfulfilled,onrejected)}catch(onrejected){return this.parse().catch(onrejected)}finally(onfinally){return this.parse().finally(onfinally)}};_APIPromise_client=new WeakMap});var _AbstractPage_client,AbstractPage,PagePromise,Page,CursorPage,ConversationCursorPage,NextCursorPage,TokenPage;var init_pagination=__esm(()=>{init_tslib();init_error();init_parse();init_api_promise();init_values();AbstractPage=class AbstractPage{constructor(client,response,body,options){_AbstractPage_client.set(this,void 0),__classPrivateFieldSet(this,_AbstractPage_client,client,"f"),this.options=options,this.response=response,this.body=body}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let nextOptions=this.nextPageRequestOptions();if(!nextOptions)throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await __classPrivateFieldGet(this,_AbstractPage_client,"f").requestAPIList(this.constructor,nextOptions)}async*iterPages(){let page=this;yield page;while(page.hasNextPage())page=await page.getNextPage(),yield page}async*[(_AbstractPage_client=new WeakMap,Symbol.asyncIterator)](){for await(let page of this.iterPages())for(let item of page.getPaginatedItems())yield item}};PagePromise=class PagePromise extends APIPromise{constructor(client,request,Page){super(client,request,async(client,props)=>new Page(client,props.response,await defaultParseResponse(client,props),props.options))}async*[Symbol.asyncIterator](){let page=await this;for await(let item of page)yield item}};Page=class Page extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.object=body.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}};CursorPage=class CursorPage extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.has_more=body.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let data=this.getPaginatedItems(),id=data[data.length-1]?.id;if(!id)return null;return{...this.options,query:{...maybeObj(this.options.query),after:id}}}};ConversationCursorPage=class ConversationCursorPage extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.has_more=body.has_more||!1,this.last_id=body.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let cursor=this.last_id;if(!cursor)return null;return{...this.options,query:{...maybeObj(this.options.query),after:cursor}}}};NextCursorPage=class NextCursorPage extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.has_more=body.has_more||!1,this.next=body.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let cursor=this.next;if(!cursor)return null;return{...this.options,query:{...maybeObj(this.options.query),after:cursor}}}};TokenPage=class TokenPage extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.has_more=body.has_more||!1,this.next=body.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let cursor=this.next;if(!cursor)return null;return{...this.options,query:{...maybeObj(this.options.query),page:cursor}}}}});function calculateExpiresAt(expiresIn,exchangeStartedAt){if(typeof expiresIn!=="number"||!Number.isFinite(expiresIn)||expiresIn<=0)throw new OpenAIError("Token exchange response has invalid 'expires_in' field");let now=Date.now(),fullLifetimeDeadline=now+expiresIn*1000;if(!Number.isSafeInteger(fullLifetimeDeadline)||fullLifetimeDeadline<=now)throw new OpenAIError("Token exchange response has invalid 'expires_in' field");let expiresAt=fullLifetimeDeadline-(performance.now()-exchangeStartedAt);if(expiresAt<=now)throw new OpenAIError("Workload identity token expired before its exchange completed.");return expiresAt}function calculateRefreshAt(expiresAt,lifetimeSeconds,refreshBufferSeconds){let configuredBufferMs=(refreshBufferSeconds??1200)*1000,effectiveBufferMs=Math.min(configuredBufferMs,lifetimeSeconds*1000*MAX_REFRESH_BUFFER_FRACTION);return expiresAt-effectiveBufferMs}function isResponsePrototype(response,prototype){let constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;if(prototype===response||typeof constructor!=="function"||Object.getOwnPropertyDescriptor(constructor,"name")?.value!=="Response"||Object.getOwnPropertyDescriptor(constructor,"prototype")?.value!==prototype)return!1;let tag=Object.getOwnPropertyDescriptor(prototype,Symbol.toStringTag);return(tag?.value==="Response"||typeof tag?.get==="function")&&typeof Object.getOwnPropertyDescriptor(prototype,"headers")?.get==="function"&&typeof Object.getOwnPropertyDescriptor(prototype,"ok")?.get==="function"&&typeof Object.getOwnPropertyDescriptor(prototype,"status")?.get==="function"}function isResponseBodyPrototype(prototype,responsePrototype){if(prototype===responsePrototype)return!0;let constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;return responsePrototype!==null&&Object.getPrototypeOf(responsePrototype)===prototype&&typeof constructor==="function"&&Object.getOwnPropertyDescriptor(constructor,"name")?.value==="Body"&&Object.getOwnPropertyDescriptor(constructor,"prototype")?.value===prototype}function decodeNativeResponseBody(body){return new TextDecoder("utf-8",{ignoreBOM:typeof globalThis.Bun?.version==="string"}).decode(body)}async function parseOAuthTokenResponse(response){let readText,responsePrototype=null;for(let depth=0,prototype=response;prototype!==null&&depth<16;prototype=Object.getPrototypeOf(prototype),depth+=1){if(prototype===NATIVE_RESPONSE_PROTOTYPE)break;if(isResponsePrototype(response,prototype))responsePrototype=prototype;let parser=Object.getOwnPropertyDescriptor(prototype,"json");if(!parser)continue;if(typeof parser.value!=="function")break;let bodyReader=Object.getOwnPropertyDescriptor(prototype,"text")?.value;if(typeof bodyReader==="function"&&isResponseBodyPrototype(prototype,responsePrototype)){readText=bodyReader;break}return parser.value.call(response)}let body=readText===void 0?decodeNativeResponseBody(await READ_NATIVE_RESPONSE_BODY.call(response)):await readText.call(response);try{return JSON.parse(body)}catch{throw SyntaxError("Token exchange response contains invalid JSON")}}function isUnsafeAccessToken(accessToken){if(typeof globalThis.Bun?.version==="string")return/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(accessToken);return/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(accessToken)}class WorkloadIdentityAuth{constructor(config,fetch2){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl="https://auth.openai.com/oauth/token";let{identityProviderId,serviceAccountId,clientId,refreshBufferSeconds,provider}=config;this.config={identityProviderId,serviceAccountId,...clientId===void 0?{}:{clientId},...refreshBufferSeconds===void 0?{}:{refreshBufferSeconds},provider:{tokenType:provider.tokenType,getToken:provider.getToken.bind(provider)}},this.fetch=fetch2??getDefaultFetch()}async getToken(){if(!this.cachedToken||WorkloadIdentityAuth.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let refreshPromise=this.refreshToken(this.tokenGeneration);this.refreshPromise=refreshPromise;try{return await refreshPromise}finally{if(this.refreshPromise===refreshPromise)this.refreshPromise=null}}if(WorkloadIdentityAuth.needsRefresh(this.cachedToken)&&!this.refreshPromise){let refreshPromise=this.refreshToken(this.tokenGeneration).finally(()=>{if(this.refreshPromise===refreshPromise)this.refreshPromise=null});this.refreshPromise=refreshPromise,refreshPromise.catch(()=>null)}return this.cachedToken.token}async refreshToken(generation){let subjectToken=await this.config.provider.getToken(),body={grant_type:TOKEN_EXCHANGE_GRANT_TYPE,subject_token:subjectToken,subject_token_type:SUBJECT_TOKEN_TYPES[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};if(this.config.clientId)body.client_id=this.config.clientId;let exchangeStartedAt=performance.now(),response=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body),redirect:"manual"});if(!response.ok){let errorText=await response.text(),body=void 0;try{body=JSON.parse(errorText)}catch{}if(response.status===400||response.status===401||response.status===403)throw new OAuthError(response.status,body,response.headers);throw APIError.generate(response.status,body,`Token exchange failed with status ${response.status}`,response.headers)}let tokenResponse=await parseOAuthTokenResponse(response),accessToken=typeof tokenResponse==="object"&&tokenResponse!==null&&"access_token"in tokenResponse?tokenResponse.access_token:void 0;if(typeof accessToken!=="string"||accessToken.trim().length===0||isUnsafeAccessToken(accessToken))throw new OpenAIError("Token exchange response missing 'access_token' field");let expiresIn=tokenResponse.expires_in??3600,expiresAt=calculateExpiresAt(expiresIn,exchangeStartedAt);if(this.tokenGeneration===generation)this.cachedToken={token:accessToken,expiresAt,refreshAt:calculateRefreshAt(expiresAt,expiresIn,this.config.refreshBufferSeconds)};return accessToken}static isTokenExpired(cachedToken){return Date.now()>=cachedToken.expiresAt}static needsRefresh(cachedToken){return Date.now()>=cachedToken.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}}var SUBJECT_TOKEN_TYPES,TOKEN_EXCHANGE_GRANT_TYPE="urn:ietf:params:oauth:grant-type:token-exchange",MAX_REFRESH_BUFFER_FRACTION=0.5,NATIVE_RESPONSE_PROTOTYPE,READ_NATIVE_RESPONSE_BODY;var init_workload_identity_auth=__esm(()=>{init_error();SUBJECT_TOKEN_TYPES={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"};NATIVE_RESPONSE_PROTOTYPE=Response.prototype,READ_NATIVE_RESPONSE_BODY=NATIVE_RESPONSE_PROTOTYPE.arrayBuffer});function assertX509APIOrigin(value){let target;try{target=new URL(value)}catch{throw new OpenAIError("X.509 workload identity requires the approved global mTLS API origin.")}if(target.origin!=="https://mtls.api.openai.com"||target.username||target.password)throw new OpenAIError("X.509 workload identity requires the approved global mTLS API origin.");for(let name of target.searchParams.keys())if(isSensitiveQueryParameter(name))throw new OpenAIError("X.509 workload identity cannot send conflicting query authentication credentials.");return target}var X509_API_BASE_URL="https://mtls.api.openai.com/v1";var init_x509_api_origin=__esm(()=>{init_error();init_log()});function*iterateHeaders(headers){if(!headers)return;if(brand_privateNullableHeaders in headers){let{values,nulls}=headers;yield*values.entries();for(let name of nulls)yield[name,null];return}let shouldClear=!1,iter,iterator=Symbol.iterator in headers?headers[Symbol.iterator]:void 0;if(typeof iterator==="function")iter={[Symbol.iterator]:()=>iterator.call(headers)};else shouldClear=!0,iter=Object.entries(headers??{});for(let row of iter){let name=row[0];if(typeof name!=="string")throw TypeError("expected header name to be a string");let values=isReadonlyArray(row[1])?row[1]:[row[1]],didClear=!1;for(let value of values){if(value===void 0)continue;if(shouldClear&&!didClear)didClear=!0,yield[name,null];yield[name,value]}}}var brand_privateNullableHeaders,httpTokenHeaderName,buildHeaders=(newHeaders)=>{let targetHeaders=new Headers,nullHeaders=new Set;for(let headers of newHeaders){let seenHeaders=new Set;for(let[name,value]of iterateHeaders(headers)){if(!httpTokenHeaderName.test(name))throw TypeError(`Header name must be a valid HTTP token ["${name}"]`);let lowerName=name.toLowerCase();if(!seenHeaders.has(lowerName))targetHeaders.delete(lowerName),seenHeaders.add(lowerName);if(value===null)targetHeaders.delete(lowerName),nullHeaders.add(lowerName);else targetHeaders.append(lowerName,value),nullHeaders.delete(lowerName)}}return{[brand_privateNullableHeaders]:!0,values:targetHeaders,nulls:nullHeaders}};var init_headers=__esm(()=>{init_values();brand_privateNullableHeaders=Symbol("brand.privateNullableHeaders"),httpTokenHeaderName=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/});var exports_x509_transport_state_browser={};__export(exports_x509_transport_state_browser,{findRegisteredX509Transport:()=>findRegisteredX509Transport,findX509Credential:()=>findX509Credential,findX509OAuthError:()=>findX509OAuthError,isApprovedX509Client:()=>isApprovedX509Client,isRetryableX509IssuerError:()=>isRetryableX509IssuerError,isTransientX509ConnectionError:()=>isTransientX509ConnectionError,markApprovedX509Client:()=>markApprovedX509Client,markRetryableX509IssuerError:()=>markRetryableX509IssuerError,markTransientX509ConnectionError:()=>markTransientX509ConnectionError,rememberRegisteredX509Transport:()=>rememberRegisteredX509Transport,rememberX509Credential:()=>rememberX509Credential,rememberX509OAuthError:()=>rememberX509OAuthError});var registeredX509Transports,transientX509ConnectionErrors,retryableX509IssuerErrors,approvedX509Clients,approvedX509OAuthErrors,approvedX509Credentials,findRegisteredX509Transport,rememberRegisteredX509Transport,markTransientX509ConnectionError,isTransientX509ConnectionError,markRetryableX509IssuerError,isRetryableX509IssuerError,markApprovedX509Client,isApprovedX509Client,rememberX509OAuthError,findX509OAuthError,rememberX509Credential,findX509Credential;var init_x509_transport_state_browser=__esm(()=>{registeredX509Transports=new WeakMap,transientX509ConnectionErrors=new WeakSet,retryableX509IssuerErrors=new WeakSet,approvedX509Clients=new WeakSet,approvedX509OAuthErrors=new WeakMap,approvedX509Credentials=new WeakMap,findRegisteredX509Transport=WeakMap.prototype.get.bind(registeredX509Transports),rememberRegisteredX509Transport=WeakMap.prototype.set.bind(registeredX509Transports),markTransientX509ConnectionError=WeakSet.prototype.add.bind(transientX509ConnectionErrors),isTransientX509ConnectionError=WeakSet.prototype.has.bind(transientX509ConnectionErrors),markRetryableX509IssuerError=WeakSet.prototype.add.bind(retryableX509IssuerErrors),isRetryableX509IssuerError=WeakSet.prototype.has.bind(retryableX509IssuerErrors),markApprovedX509Client=WeakSet.prototype.add.bind(approvedX509Clients),isApprovedX509Client=WeakSet.prototype.has.bind(approvedX509Clients),rememberX509OAuthError=WeakMap.prototype.set.bind(approvedX509OAuthErrors),findX509OAuthError=WeakMap.prototype.get.bind(approvedX509OAuthErrors),rememberX509Credential=WeakMap.prototype.set.bind(approvedX509Credentials),findX509Credential=WeakMap.prototype.get.bind(approvedX509Credentials)});var require_x509_transport_state=__commonJS(function(exports,module){if(typeof module<"u"&&module!==globalThis.module&&typeof exports<"u"&&exports===exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.findX509Credential=exports.rememberX509Credential=exports.findX509OAuthError=exports.rememberX509OAuthError=exports.isApprovedX509Client=exports.markApprovedX509Client=exports.isRetryableX509IssuerError=exports.markRetryableX509IssuerError=exports.isTransientX509ConnectionError=exports.markTransientX509ConnectionError=exports.rememberRegisteredX509Transport=exports.findRegisteredX509Transport=void 0;let registeredX509Transports=new WeakMap,transientX509ConnectionErrors=new WeakSet,retryableX509IssuerErrors=new WeakSet,approvedX509Clients=new WeakSet,approvedX509OAuthErrors=new WeakMap,approvedX509Credentials=new WeakMap;exports.findRegisteredX509Transport=WeakMap.prototype.get.bind(registeredX509Transports),exports.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(registeredX509Transports),exports.markTransientX509ConnectionError=WeakSet.prototype.add.bind(transientX509ConnectionErrors),exports.isTransientX509ConnectionError=WeakSet.prototype.has.bind(transientX509ConnectionErrors),exports.markRetryableX509IssuerError=WeakSet.prototype.add.bind(retryableX509IssuerErrors),exports.isRetryableX509IssuerError=WeakSet.prototype.has.bind(retryableX509IssuerErrors),exports.markApprovedX509Client=WeakSet.prototype.add.bind(approvedX509Clients),exports.isApprovedX509Client=WeakSet.prototype.has.bind(approvedX509Clients),exports.rememberX509OAuthError=WeakMap.prototype.set.bind(approvedX509OAuthErrors),exports.findX509OAuthError=WeakMap.prototype.get.bind(approvedX509OAuthErrors),exports.rememberX509Credential=WeakMap.prototype.set.bind(approvedX509Credentials),exports.findX509Credential=WeakMap.prototype.get.bind(approvedX509Credentials)}});var nodeState,state,findRegisteredX509Transport3,rememberRegisteredX509Transport2,markTransientX509ConnectionError2,isTransientX509ConnectionError2,markRetryableX509IssuerError2,isRetryableX509IssuerError2,markApprovedX509Client2,isApprovedX509Client2,rememberX509OAuthError2,findX509OAuthError2,rememberX509Credential2,findX509Credential2;var init_x509_transport_state=__esm(()=>{init_x509_transport_state_browser();nodeState=__toESM(require_x509_transport_state(),1),state=typeof nodeState.findRegisteredX509Transport==="function"?nodeState:exports_x509_transport_state_browser,{findRegisteredX509Transport:findRegisteredX509Transport3,rememberRegisteredX509Transport:rememberRegisteredX509Transport2,markTransientX509ConnectionError:markTransientX509ConnectionError2,isTransientX509ConnectionError:isTransientX509ConnectionError2,markRetryableX509IssuerError:markRetryableX509IssuerError2,isRetryableX509IssuerError:isRetryableX509IssuerError2,markApprovedX509Client:markApprovedX509Client2,isApprovedX509Client:isApprovedX509Client2,rememberX509OAuthError:rememberX509OAuthError2,findX509OAuthError:findX509OAuthError2,rememberX509Credential:rememberX509Credential2,findX509Credential:findX509Credential2}=state});function resolveX509Transport(value){if(!value||typeof value!=="object")throw new OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");let registered=findRegisteredX509Transport3(value);if(!registered)throw new OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");return registered}var x509TransportBrand;var init_x509_transport_registry=__esm(()=>{init_error();init_x509_transport_state();x509TransportBrand=Symbol("X.509 transport capability")});function assertSafeHeaders(headers){for(let name of Headers.prototype.keys.call(headers)){let canonical=name.toLowerCase().split("_").join("-");if(canonical!=="authorization"&&isSensitiveHeader(canonical)||canonical==="host")throw new OpenAIError("X.509 workload identity cannot send conflicting authentication credentials.")}}function exchangeDeadline(timeout,callerSignal){let deadline=new AbortController,timer=timeout===void 0?void 0:setTimeout(()=>deadline.abort(new APIConnectionTimeoutError),timeout),timerHandle=timer;if(typeof timerHandle==="object"&&timerHandle!==null&&"unref"in timerHandle&&typeof timerHandle.unref==="function")timerHandle.unref();let cancel=()=>deadline.abort(callerSignal?.reason);if(callerSignal?.addEventListener("abort",cancel,{once:!0}),callerSignal?.aborted)cancel();return{signal:deadline.signal,dispose:()=>{if(callerSignal?.removeEventListener("abort",cancel),timer)clearTimeout(timer)}}}function waitForRefresh(attempt,signal){let abort,canceled=new Promise((_resolve,reject)=>{if(abort=()=>reject(signal.reason),signal.addEventListener("abort",abort,{once:!0}),signal.aborted)abort()});return{result:Promise.race([attempt.promise,canceled]),dispose:()=>{if(abort)signal.removeEventListener("abort",abort)}}}function isX509WorkloadIdentity(identity){if(!identity||typeof identity!=="object")return!1;let providerOwner=identity;while(providerOwner!==null&&providerOwner!==Object.prototype){let provider=Object.getOwnPropertyDescriptor(providerOwner,"provider");if(provider){if(!("value"in provider)||provider.value!==void 0)return!1;break}providerOwner=Object.getPrototypeOf(providerOwner)}let current=identity;while(current!==null&&current!==Object.prototype){let discriminator=Object.getOwnPropertyDescriptor(current,"type");if(discriminator){if(!("value"in discriminator))throw new OpenAIError("X.509 workload identity type must be a plain data property.");return discriminator.value==="x509"}current=Object.getPrototypeOf(current)}return!1}function assertX509FetchOptions(options){if(!options)return;for(let name of FORBIDDEN_TRANSPORT_OPTIONS)if(hasOwn(options,name))throw new OpenAIError("X.509 workload identity cannot override its approved transport capability.");let redirect=Object.getOwnPropertyDescriptor(options,"redirect")?.value;if(redirect!==void 0&&redirect!=="manual")throw new OpenAIError("X.509 workload identity requests require manual redirects.")}function assertX509RequestOptions(options){if(assertX509FetchOptions(options),options&&["body","headers","method","signal"].some((name)=>hasOwn(options,name)))throw new OpenAIError("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}function snapshotX509RequestOptions(options){assertX509RequestOptions(options);let snapshot={...options};return assertX509RequestOptions(snapshot),snapshot}class X509WorkloadIdentityAuth{constructor(identity,transport,organization,project){if(_X509WorkloadIdentityAuth_instances.add(this),_X509WorkloadIdentityAuth_identityProviderId.set(this,void 0),_X509WorkloadIdentityAuth_serviceAccountId.set(this,void 0),_X509WorkloadIdentityAuth_configuredRefreshBufferMs.set(this,void 0),_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds.set(this,void 0),_X509WorkloadIdentityAuth_organization.set(this,void 0),_X509WorkloadIdentityAuth_project.set(this,void 0),_X509WorkloadIdentityAuth_transport.set(this,void 0),_X509WorkloadIdentityAuth_refreshBufferMs.set(this,void 0),_X509WorkloadIdentityAuth_cachedToken.set(this,void 0),_X509WorkloadIdentityAuth_refresh.set(this,void 0),_X509WorkloadIdentityAuth_tokenGeneration.set(this,0),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_transport,resolveX509Transport(transport),"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_identityProviderId,identity.identityProviderId,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_serviceAccountId,identity.serviceAccountId,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,identity.refreshBufferMs,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,identity.refreshBufferSeconds,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_organization,organization,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_project,project,"f"),__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f")!==void 0&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")!==void 0)throw new OpenAIError("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f")!==void 0&&(!Number.isSafeInteger(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f"))||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f")<0))throw new OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")!==void 0&&(!Number.isSafeInteger(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f"))||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")<0||!Number.isSafeInteger(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")*1000)))throw new OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_refreshBufferMs,__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")===void 0?__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f")??DEFAULT_REFRESH_BUFFER_MS:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")*1000,"f")}identitySnapshot(){return{type:"x509",identityProviderId:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_identityProviderId,"f"),serviceAccountId:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_serviceAccountId,"f"),...__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f")===void 0?{}:{refreshBufferMs:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,"f")},...__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")===void 0?{}:{refreshBufferSeconds:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,"f")}}}static shouldAuthenticate(options,defaultHeaders,requestHeaders=options.headers){return!buildHeaders([defaultHeaders,requestHeaders]).nulls.has("authorization")}snapshotHeaders(defaultHeaders,requestHeaders){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);return scope.defaultHeaders??(scope.defaultHeaders=buildHeaders([defaultHeaders])),scope.requestHeaders??(scope.requestHeaders=buildHeaders([requestHeaders])),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders,requestHeaders}=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(!defaultHeaders||!requestHeaders)throw new OpenAIError("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders,requestHeaders}}snapshotTenant(organization,project){if(organization!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_organization,"f")||project!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_project,"f"))throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);return scope.tenant={organization,project},scope.tenant}tenantSnapshot(){let{tenant}=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(!tenant)throw new OpenAIError("X.509 workload identity requires snapshotted tenant selectors.");return tenant}snapshotAPIURL(value){assertX509APIOrigin(value),__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this).apiURL=value}requestAPIURL(){let{apiURL}=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(apiURL===void 0)throw new OpenAIError("X.509 workload identity requires a snapshotted API destination.");return apiURL}snapshotRequest(signal,timeout,fetchOptions){var _b;(_b=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this)).request??(_b.request={signal,timeout,fetchOptions})}requestSnapshot(){let{request}=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(!request)throw new OpenAIError("X.509 workload identity requires snapshotted request settings.");return request}beginRequestPreparation(){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(scope.deadlineArmed&&scope.preparationStartedAt===void 0)scope.preparationStartedAt=performance.now(),scope.preparationWallStartedAt=Date.now()}beginRequestPlanning(){__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this).phase="planning"}beginRequestNetwork(){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(!scope.deadlineArmed)scope.wallStartedAt=Date.now(),scope.monotonicStartedAt=performance.now(),scope.deadlineArmed=!0;else if(scope.preparationStartedAt!==void 0)scope.monotonicStartedAt+=performance.now()-scope.preparationStartedAt,scope.wallStartedAt+=Date.now()-(scope.preparationWallStartedAt??Date.now()),delete scope.preparationStartedAt,delete scope.preparationWallStartedAt}isPlanningRequest(){return __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this).phase==="planning"}authorizePlannedRequest(url,request,timeout,allowHookSignal=!1){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this),headers=Object.getOwnPropertyDescriptor(request,"headers"),body=Object.getOwnPropertyDescriptor(request,"body"),signal=Object.getOwnPropertyDescriptor(request,"signal"),redirect=Object.getOwnPropertyDescriptor(request,"redirect");if(scope.phase!=="planning"||!headers||!(headers.value instanceof Headers)||!body&&"body"in request||[body,signal,redirect].some((descriptor)=>descriptor&&!("value"in descriptor)))throw new OpenAIError("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(url),assertX509FetchOptions(request);try{assertSafeHeaders(headers.value)}catch{throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(headerValue(headers.value,"Authorization")!==null)throw new OpenAIError("X.509 workload identity cannot use caller-supplied authorization credentials.");if(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_assertTenantHeaders).call(this,headers.value),!allowHookSignal&&(signal?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new OpenAIError("X.509 workload identity must preserve its approved request signal.");let approved=this.requestSnapshot();scope.request={...approved,timeout:Math.min(approved.timeout,timeout)},scope.phase="authorizing"}ownRequestBody(body,source){if(body instanceof ReadableStream&&body!==source)__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this).materializedBody=body}static isStreamingRequestBody(body){return globalThis.ReadableStream!==void 0&&body instanceof globalThis.ReadableStream||typeof body==="object"&&body!==null&&((Symbol.asyncIterator in body)||(Symbol.iterator in body)&&("next"in body)&&typeof body.next==="function")}retireRequestBody(){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this),body=scope.materializedBody;if(delete scope.materializedBody,body)__classPrivateFieldGet(_a,_a,"m",_X509WorkloadIdentityAuth_cancelRequestBody).call(_a,body)}releaseRequestBody(body){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);if(scope.materializedBody===body)delete scope.materializedBody;else this.retireRequestBody()}setEffectiveSignal(signal){if(signal)__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this).effectiveSignal=signal;else delete __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this).effectiveSignal}effectiveSignal(){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);return scope.effectiveSignal??scope.request?.signal}runRequest(operation,requestOwner){return __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").run(async()=>{let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current();if(!scope)throw new OpenAIError("X.509 workload identity requires an active certificate request scope.");scope.owner=this,scope.requestOwner=requestOwner;try{return await operation()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete scope.requestOwner,delete scope.owner}})}inRequest(requestOwner){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current();return scope?.owner===this&&scope.requestOwner===requestOwner&&scope.phase!=="authorizing"}matches(other){return __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f")===__classPrivateFieldGet(other,_X509WorkloadIdentityAuth_transport,"f")&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_identityProviderId,"f")===__classPrivateFieldGet(other,_X509WorkloadIdentityAuth_identityProviderId,"f")&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_serviceAccountId,"f")===__classPrivateFieldGet(other,_X509WorkloadIdentityAuth_serviceAccountId,"f")&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_organization,"f")===__classPrivateFieldGet(other,_X509WorkloadIdentityAuth_organization,"f")&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_project,"f")===__classPrivateFieldGet(other,_X509WorkloadIdentityAuth_project,"f")&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refreshBufferMs,"f")===__classPrivateFieldGet(other,_X509WorkloadIdentityAuth_refreshBufferMs,"f")}continuation(){let{wallStartedAt,monotonicStartedAt,deadlineArmed,request,requestOwner,effectiveSignal}=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this),scope={wallStartedAt,monotonicStartedAt,owner:this,...deadlineArmed?{deadlineArmed}:{},...request?{request}:{},...effectiveSignal?{effectiveSignal}:{},...requestOwner?{requestOwner}:{}};return(operation)=>__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").resume(scope,async()=>{try{return await operation()}finally{this.releaseRequestCredentials(),delete scope.requestOwner,delete scope.owner}})}releaseRequestCredentials(){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this);delete scope.request,delete scope.phase,delete scope.deadlineArmed,delete scope.preparationStartedAt,delete scope.preparationWallStartedAt,delete scope.effectiveSignal,delete scope.materializedBody,delete scope.apiURL,delete scope.tenant,delete scope.token,delete scope.defaultHeaders,delete scope.requestHeaders,delete scope.tokenGeneration,delete scope.headers,delete scope.authorization}requestStartedAt(_options){return __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current()?.wallStartedAt}usedWorkloadToken(_options){return __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current()?.token!==void 0}remainingTimeout(_options,timeout){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current();if(scope===void 0)return timeout;let remaining=timeout-(performance.now()-scope.monotonicStartedAt);if(remaining<=0)throw new APIConnectionTimeoutError;return remaining}async waitForRetry(duration,signal){try{await __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").sleep(duration,signal)}catch(error){if(signal?.aborted)throw userAbortError(signal);throw error}}static isRetryableFailure(error){return typeof error==="object"&&error!==null&&(isTransientX509ConnectionError2(error)||isRetryableX509IssuerError2(error))}static retryHeaders(error){if(!error||typeof error!=="object"||!isRetryableX509IssuerError2(error))return;let headers=Object.getOwnPropertyDescriptor(error,"headers")?.value;return headers instanceof Headers?headers:void 0}async getToken(options,context){let callerSignal=context?context.signal:options?.signal;if(callerSignal?.aborted)throw userAbortError(callerSignal);if(options)assertX509RequestOptions(context?context.fetchOptions:options.fetchOptions);__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_preflight).call(this,context);let scope=options?__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this):void 0,cached=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_cachedToken,"f");if(cached&&performance.now()<cached.refreshAt&&Date.now()<cached.wallRefreshAt)return __classPrivateFieldGet(_a,_a,"m",_X509WorkloadIdentityAuth_assignToken).call(_a,scope,cached);let remaining=context&&options?this.remainingTimeout(options,context.timeout):context?.timeout,{signal,dispose}=exchangeDeadline(remaining,callerSignal);if(callerSignal?.aborted)throw dispose(),userAbortError(callerSignal);let attempt=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refresh,"f")??__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_beginRefresh).call(this);attempt.waiters+=1;let waiter=waitForRefresh(attempt,signal);try{let exchanged=await waiter.result,refreshed=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_cachedToken,"f");if(!refreshed||refreshed.accessToken!==exchanged.accessToken)throw new APIUserAbortError;return __classPrivateFieldGet(_a,_a,"m",_X509WorkloadIdentityAuth_assignToken).call(_a,scope,refreshed)}catch(error){return await __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_recoverRefreshFailure).call(this,error,attempt,cached,scope,options,context)}finally{waiter.dispose(),dispose(),attempt.waiters-=1,__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_retireRefresh).call(this,attempt)}}invalidateToken(){let rejected=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current();if(!rejected?.token||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_cachedToken,"f")?.accessToken!==rejected.token||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_cachedToken,"f").generation!==rejected.tokenGeneration)return;__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_tokenGeneration,__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f")+1,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_cachedToken,void 0,"f");let refresh=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refresh,"f");__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_refresh,void 0,"f"),refresh?.controller.abort(new APIUserAbortError)}bindRequest(options,request,adminAPIKey){if(!(request.headers instanceof Headers))throw new OpenAIError("X.509 workload identity requires the original workload authorization headers.");let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this),{token}=scope,security=options.__security??{bearerAuth:!0},approvedAuthorization=token?`Bearer ${token}`:null;if(!token&&security.adminAPIKeyAuth&&adminAPIKey!==null&&headerValue(request.headers,"Authorization")!==null)approvedAuthorization=new Headers({Authorization:`Bearer ${adminAPIKey}`}).get("Authorization");scope.headers=request.headers,scope.authorization=approvedAuthorization,this.assertRequest(request)}adoptRequestHeaders(request){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_scope).call(this),original=scope.headers;if(!(original instanceof Headers)||!(request.headers instanceof Headers))throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");scope.headers=request.headers;try{this.assertRequest(request)}catch(error){throw scope.headers=original,error}}assertRequest(request){let{headers}=request;if(!(headers instanceof Headers))throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current();if(!scope||scope.headers!==headers||scope.authorization===void 0||headerValue(headers,"Authorization")!==scope.authorization)throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_assertTenantHeaders).call(this,headers),assertSafeHeaders(headers)}fetch(){return async(input,init={})=>{let target=assertX509APIOrigin(typeof input==="string"||input instanceof URL?input:input.url);assertX509FetchOptions(init),this.assertRequest(init);let approved=init.headers;if(!(approved instanceof Headers))throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");let headers=new Headers([...Headers.prototype.entries.call(approved)]);return assertSafeHeaders(headers),init.headers=headers,init.redirect="manual",await __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").dispatch(target,init)}}}var _X509WorkloadIdentityAuth_instances,_a,_X509WorkloadIdentityAuth_identityProviderId,_X509WorkloadIdentityAuth_serviceAccountId,_X509WorkloadIdentityAuth_configuredRefreshBufferMs,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds,_X509WorkloadIdentityAuth_organization,_X509WorkloadIdentityAuth_project,_X509WorkloadIdentityAuth_transport,_X509WorkloadIdentityAuth_refreshBufferMs,_X509WorkloadIdentityAuth_cachedToken,_X509WorkloadIdentityAuth_refresh,_X509WorkloadIdentityAuth_tokenGeneration,_X509WorkloadIdentityAuth_cancelRequestBody,_X509WorkloadIdentityAuth_assignToken,_X509WorkloadIdentityAuth_recoverRefreshFailure,_X509WorkloadIdentityAuth_fallbackToken,_X509WorkloadIdentityAuth_retireRefresh,_X509WorkloadIdentityAuth_beginRefresh,_X509WorkloadIdentityAuth_refreshToken,_X509WorkloadIdentityAuth_preflight,_X509WorkloadIdentityAuth_scope,_X509WorkloadIdentityAuth_assertTenantHeaders,FORBIDDEN_TRANSPORT_OPTIONS,headerValue=(headers,name)=>Headers.prototype.get.call(headers,name),DEFAULT_REFRESH_BUFFER_MS=1200000,FAILED_REFRESH_COOLDOWN_MS=1000,userAbortError=(signal)=>{let error=new APIUserAbortError;return Object.defineProperty(error,"cause",{value:signal.reason,writable:!0,configurable:!0}),error};var init_x509_workload_identity_auth=__esm(()=>{init_tslib();init_error();init_headers();init_log();init_values();init_x509_api_origin();init_x509_transport_registry();init_x509_transport_state();FORBIDDEN_TRANSPORT_OPTIONS=["dispatcher","agent","client","tls","proxy"];_a=X509WorkloadIdentityAuth,_X509WorkloadIdentityAuth_identityProviderId=new WeakMap,_X509WorkloadIdentityAuth_serviceAccountId=new WeakMap,_X509WorkloadIdentityAuth_configuredRefreshBufferMs=new WeakMap,_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds=new WeakMap,_X509WorkloadIdentityAuth_organization=new WeakMap,_X509WorkloadIdentityAuth_project=new WeakMap,_X509WorkloadIdentityAuth_transport=new WeakMap,_X509WorkloadIdentityAuth_refreshBufferMs=new WeakMap,_X509WorkloadIdentityAuth_cachedToken=new WeakMap,_X509WorkloadIdentityAuth_refresh=new WeakMap,_X509WorkloadIdentityAuth_tokenGeneration=new WeakMap,_X509WorkloadIdentityAuth_instances=new WeakSet,_X509WorkloadIdentityAuth_cancelRequestBody=async function(body){try{await CancelReadableStream(body)}catch{}},_X509WorkloadIdentityAuth_assignToken=function(scope,token){if(scope)scope.token=token.accessToken,scope.tokenGeneration=token.generation;return token.accessToken},_X509WorkloadIdentityAuth_recoverRefreshFailure=async function(error,attempt,cached,scope,options,context){let callerSignal=context?context.signal:options?.signal;if(callerSignal?.aborted)throw userAbortError(callerSignal);if(attempt.controller.signal.aborted&&attempt.generation!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f"))return await this.getToken(options,context);let fallback=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_fallbackToken).call(this,error,cached,scope);if(fallback!==void 0)return fallback;if(error&&typeof error==="object"&&!(error instanceof OAuthError)){let oauth=findX509OAuthError2(error);if(oauth)throw new OAuthError(oauth.status,oauth.error,oauth.headers)}throw error},_X509WorkloadIdentityAuth_fallbackToken=function(error,cached,scope){if(!cached||cached!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_cachedToken,"f")||performance.now()>=cached.expiresAt||Date.now()>=cached.wallExpiresAt||!_a.isRetryableFailure(error))return;let headers=_a.retryHeaders(error),milliseconds=headers?.get("retry-after-ms"),requested=milliseconds?Number(milliseconds):void 0,retryAfter=headers?.get("retry-after");if(retryAfter&&(requested===void 0||Number.isNaN(requested))){let seconds=Number(retryAfter);requested=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1000}let cooldown=requested!==void 0&&Number.isFinite(requested)&&requested>=0&&requested<=60000?Math.max(FAILED_REFRESH_COOLDOWN_MS,requested):FAILED_REFRESH_COOLDOWN_MS;return cached.refreshAt=Math.min(cached.expiresAt,performance.now()+cooldown),cached.wallRefreshAt=Math.min(cached.wallExpiresAt,Date.now()+cooldown),__classPrivateFieldGet(_a,_a,"m",_X509WorkloadIdentityAuth_assignToken).call(_a,scope,cached)},_X509WorkloadIdentityAuth_retireRefresh=function(attempt){if(attempt.waiters!==0||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refresh,"f")!==attempt)return;queueMicrotask(()=>{if(attempt.waiters===0&&__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refresh,"f")===attempt)__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_refresh,void 0,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_tokenGeneration,__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f")+1,"f"),attempt.controller.abort(new APIUserAbortError)})},_X509WorkloadIdentityAuth_beginRefresh=function(){let controller=new AbortController,generation=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f"),attempt={controller,generation,waiters:0,promise:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_instances,"m",_X509WorkloadIdentityAuth_refreshToken).call(this,controller,generation)};return __classPrivateFieldSet(this,_X509WorkloadIdentityAuth_refresh,attempt,"f"),attempt},_X509WorkloadIdentityAuth_refreshToken=async function(controller,generation){let startedAt=performance.now(),wallStartedAt=Date.now();try{let token=await __classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").exchange(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_identityProviderId,"f"),__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_serviceAccountId,"f"),controller.signal),lifetime=token.expiresIn*1000,expiresAt=startedAt+lifetime,wallExpiresAt=wallStartedAt+lifetime;if(performance.now()>=expiresAt||Date.now()>=wallExpiresAt)throw new OpenAIError("X.509 workload identity token expired before its exchange completed.");if(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f")!==generation||controller.signal.aborted||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refresh,"f")?.controller!==controller)throw new APIUserAbortError;return __classPrivateFieldSet(this,_X509WorkloadIdentityAuth_tokenGeneration,__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f")+1,"f"),__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_cachedToken,{accessToken:token.accessToken,generation:__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_tokenGeneration,"f"),expiresAt,refreshAt:expiresAt-Math.min(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refreshBufferMs,"f"),lifetime/2),wallExpiresAt,wallRefreshAt:wallExpiresAt-Math.min(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refreshBufferMs,"f"),lifetime/2)},"f"),token}finally{if(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_refresh,"f")?.controller===controller)__classPrivateFieldSet(this,_X509WorkloadIdentityAuth_refresh,void 0,"f")}},_X509WorkloadIdentityAuth_preflight=function(context){if(!context)return;if(context.organization!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_organization,"f")||context.project!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_project,"f"))throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");assertX509APIOrigin(context.apiURL);let supplied=buildHeaders([context.defaultHeaders,context.requestHeaders]);if(__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_organization,"f")!==null&&supplied.nulls.has("openai-organization")||__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_project,"f")!==null&&supplied.nulls.has("openai-project"))throw new OpenAIError("X.509 workload identity cannot omit its enrolled organization or project.");for(let name of supplied.values.keys()){let canonical=name.toLowerCase().split("_").join("-");if((canonical==="openai-organization"||canonical==="openai-project")&&(name!==canonical||headerValue(supplied.values,name)!==(canonical==="openai-organization"?context.organization:context.project)))throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");if(isSensitiveHeader(canonical)||canonical==="host")throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.")}},_X509WorkloadIdentityAuth_scope=function(){let scope=__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_transport,"f").current();if(!scope||scope.owner!==this)throw new OpenAIError("X.509 workload identity requires an active certificate request scope.");return scope},_X509WorkloadIdentityAuth_assertTenantHeaders=function(headers){if(headerValue(headers,"OpenAI-Organization")!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_organization,"f")||headerValue(headers,"OpenAI-Project")!==__classPrivateFieldGet(this,_X509WorkloadIdentityAuth_project,"f"))throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");for(let name of Headers.prototype.keys.call(headers)){let canonical=name.toLowerCase().split("_").join("-");if((canonical==="openai-organization"||canonical==="openai-project")&&name!==canonical)throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.")}}});function normalizeX509CredentialOptions(options){let{credential}=options;if(credential===void 0)return{credential,options};let registered=findX509Credential2(credential);if(!registered)throw new OpenAIError("An X.509 credential must be created by the SDK authentication helper.");let conflicting=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter((name)=>{let value=options[name];return value!==null&&value!==void 0});if(conflicting.length>0)throw new OpenAIError(`The \`credential\` option cannot be combined with ${conflicting.map((name)=>`\`${name}\``).join(", ")}.`);return{credential,options:{...options,apiKey:null,adminAPIKey:null,baseURL:options.baseURL??null,organization:options.organization??null,project:options.project??null,workloadIdentity:registered.identity,x509Transport:registered.transport}}}function overridesOrdinaryAuthentication({apiKey,adminAPIKey}){return apiKey!==null&&apiKey!==void 0||adminAPIKey!==null&&adminAPIKey!==void 0}function prepareProviderClone(inherited,overrides){let inheritedProvider=inherited.provider,replacingProvider=overrides.credential??overrides.workloadIdentity,provider=overrides.provider??(replacingProvider?void 0:inheritedProvider);if(provider!==inheritedProvider)delete inherited.baseURL,delete inherited.organization,delete inherited.project,delete inherited.defaultHeaders,delete inherited.defaultQuery,delete inherited.fetchOptions,delete inherited.fetch;if(provider)delete inherited.apiKey,delete inherited.adminAPIKey,delete inherited.credential,delete inherited.workloadIdentity,delete inherited.x509Transport,delete inherited.baseURL;return provider}function prepareX509ClientClone(inherited,overrides,credential,currentlyX509){let nextIdentity=hasOwn(overrides,"workloadIdentity")?overrides.workloadIdentity:inherited.workloadIdentity,dropping=credential!==void 0&&(overridesOrdinaryAuthentication(overrides)&&overrides.workloadIdentity===void 0||overrides.provider!==void 0);if(credential!==void 0&&hasOwn(overrides,"workloadIdentity"))delete inherited.x509Transport;let inheritedCredential=credential!==void 0&&!dropping&&overrides.credential===void 0&&!hasOwn(overrides,"workloadIdentity")&&!hasOwn(overrides,"x509Transport")?credential:void 0,nextCredential=overrides.credential===void 0?inheritedCredential:overrides.credential,nextX509=nextCredential!==void 0||!dropping&&isX509WorkloadIdentity(nextIdentity);if(currentlyX509!==nextX509){if(delete inherited.fetch,delete inherited.baseURL,delete inherited.organization,delete inherited.project,delete inherited.defaultHeaders,delete inherited.defaultQuery,delete inherited.fetchOptions,nextX509)inherited.apiKey=null;else if(delete inherited.x509Transport,dropping)delete inherited.workloadIdentity}if(nextCredential!==void 0){if(delete inherited.apiKey,delete inherited.adminAPIKey,delete inherited.workloadIdentity,delete inherited.x509Transport,inherited.credential=nextCredential,overrides.credential!==void 0)delete inherited.organization,delete inherited.project,delete inherited.defaultHeaders,delete inherited.defaultQuery,delete inherited.fetchOptions}return{credential:nextCredential,provider:prepareProviderClone(inherited,overrides)}}var init_x509_credential_options=__esm(()=>{init_error();init_values();init_x509_workload_identity_auth();init_x509_transport_state()});function toStreamingFile(data,name,options){if(typeof name!=="string"||!name)throw TypeError("toStreamingFile requires a non-empty file name");let type=options?.type;if(type)validateStreamingFileType(type);return{[brand_privateStreamingFile]:!0,data,name,...type?{type}:{}}}function makeFile(fileBits,fileName,options){return checkFileSupport(),new File(fileBits,fileName??"unknown_file",options)}function getName(value,options){if(typeof value!=="object"||value===null)return;let name="name"in value?value.name:void 0,explicitName=name&&String(name)||"filename"in value&&value.filename&&String(value.filename);if(explicitName)return options?.stripFilename===!1?normalizeFilenamePath(explicitName):basename(explicitName);let url="url"in value&&value.url&&String(value.url);if(url)try{let filename=basename(new URL(url).pathname);return filename===void 0?void 0:basename(decodeURLFilename(filename))}catch{return basename(url)}let path="path"in value&&value.path&&String(value.path);return path?basename(path):void 0}function basename(value){return value.split(/[\\/]/).pop()||void 0}function decodeURLFilename(filename){try{let decodedFilename=decodeURIComponent(filename);if(/%(?:0[AD]|22)/i.test(decodedFilename))return filename;return decodedFilename.replace(/[\u0000-\u001F\u007F]/gu,encodeURIComponent)}catch{return filename}}function normalizeFilenamePath(value){let normalized=value.replace(/\\/g,"/");if(normalized.startsWith("/")||/^[A-Za-z]:/.test(normalized)||normalized.split("/").includes(".."))throw TypeError("Upload file name must be a safe relative path without parent directory segments");return normalized}function isArrayBuffer(value){try{return arrayBufferByteLengthGetter?.call(value)!==void 0}catch{return!1}}function supportsFormData(fetchObject){let fetch2=typeof fetchObject==="function"?fetchObject:fetchObject.fetch,cached=supportsFormDataMap.get(fetch2);if(cached)return cached;let promise=(async()=>{try{let FetchResponse;if("Response"in fetch2)FetchResponse=fetch2.Response;else{let response=await fetch2("data:,");await response.arrayBuffer(),FetchResponse=response.constructor}let data=new FormData;if(data.toString()===await new FetchResponse(data).text())return!1;return!0}catch{return!0}})();return supportsFormDataMap.set(fetch2,promise),promise}async function*iterateMultipartBody(entries,boundary,options,preservedFilenames){for await(let{key,value}of entries){if(isUploadable(value)){let filename=preservedFilenames?.get(value)??getStreamingFileName(value,options),type=getStreamingFileType(value);yield encodeUTF8(`--${boundary}\r
7
+ `),yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"; filename="${escapeHeaderValue(filename)}"\r
8
+ Content-Type: ${type}\r
9
+ \r
10
+ `),yield*iterateBytes(getStreamingFileData(value))}else yield encodeUTF8(`--${boundary}\r
11
+ `),yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"\r
12
+ \r
13
+ ${String(value)}`);yield encodeUTF8(`\r
14
+ `)}yield encodeUTF8(`--${boundary}--\r
15
+ `)}function*iterateFormEntries(body){if(!body||typeof body!=="object")return;for(let[key,value]of Object.entries(body))yield*iterateFormValue(key,value)}function*iterateFormValue(key,value){if(value===void 0)return;if(value==null)throw TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"||isUploadable(value))yield{key,value};else if(Array.isArray(value))for(let entry of value)yield*iterateFormValue(key+"[]",entry);else if(typeof value==="object")for(let[name,prop]of Object.entries(value))yield*iterateFormValue(`${key}[${name}]`,prop);else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`)}function getStreamingFileName(value,options){if(isStreamingFile(value)){let{name}=value;if(typeof name!=="string"||!name)throw TypeError("Streaming upload file name must be a non-empty string");return options.stripFilenames===!1?normalizeFilenamePath(name):basename(name)??"unknown_file"}return getName(value,{stripFilename:options.stripFilenames})??"unknown_file"}function getStreamingFileType(value){let type;if(isStreamingFile(value)||isBlob(value))({type}=value);else if(value instanceof Response)type=value.headers.get("content-type")??void 0;return validateStreamingFileType(type||"application/octet-stream")}function validateStreamingFileType(type){if(typeof type!=="string")throw TypeError("Streaming upload content type must be a string");for(let index=0;index<type.length;index+=1){let character=type.codePointAt(index)??0;if(character<=31||character===127)throw TypeError("Streaming upload content type must not contain control characters")}return type}function getStreamingFileData(value){if(isStreamingFile(value))return value.data;return value}async function*iterateBytes(value){if(typeof value==="string")yield encodeUTF8(value);else if(ArrayBuffer.isView(value))yield new Uint8Array(value.buffer,value.byteOffset,value.byteLength);else if(isArrayBuffer(value))yield new Uint8Array(value);else if(value instanceof Response)yield*iterateBytes(value.body||await value.blob());else if(value instanceof Blob)if(typeof value.stream==="function")yield*iterateBytes(value.stream());else yield new Uint8Array(await value.arrayBuffer());else if(isReadableStream(value))for await(let chunk of ReadableStreamToAsyncIterable(value))yield*iterateBytes(chunk);else if(isAsyncIterable(value))for await(let chunk of value)yield*iterateBytes(chunk);else throw TypeError(`Invalid streaming file chunk: ${String(value)}`)}function escapeHeaderValue(value){return Array.from(value,(character)=>{let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127||character==='"'||character==="\\"?encodeURIComponent(character):character}).join("")}var brand_privateStreamingFile,checkFileSupport=()=>{if(typeof File>"u"){let{process:process2}=globalThis,isOldNode=typeof process2?.versions?.node==="string"&&Number.parseInt(process2.versions.node.split("."),10)<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(isOldNode?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":""))}},arrayBufferByteLengthGetter,isAsyncIterable=(value)=>value!=null&&typeof value==="object"&&typeof value[Symbol.asyncIterator]==="function",maybeMultipartFormRequestOptions=async(opts,fetch2,formOptions)=>{if(!hasUploadableValue(opts.body))return opts.__metadata?.finalizeMultipart===!0&&formOptions?.stripFilenames===!1?{...opts,__metadata:{...opts.__metadata,preserveMultipartFilenames:!0}}:opts;let finalizedOptions=opts.__metadata?.finalizeMultipart===!0?{...opts,__metadata:{...opts.__metadata,finalizeMultipart:!1}}:opts;if(hasStreamingUploadableValue(opts.body))return createStreamingFormRequestOptions(finalizedOptions,formOptions);return{...finalizedOptions,body:await createForm(finalizedOptions.body,fetch2,formOptions)}},multipartFormRequestOptions=async(opts,fetch2,formOptions)=>{if(hasStreamingUploadableValue(opts.body))return createStreamingFormRequestOptions(opts,formOptions);return{...opts,body:await createForm(opts.body,fetch2,formOptions)}},supportsFormDataMap,createForm=async(body,fetch2,options={})=>{if(!await supportsFormData(fetch2))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let form=new FormData;return await Promise.all(Object.entries(body||{}).map(([key,value])=>addFormValue(form,key,value,options))),form},isBlob=(value)=>value instanceof Blob,isReadableStream=(value)=>typeof value==="object"&&value!==null&&("getReader"in value)&&typeof value.getReader==="function",isStreamingFile=(value)=>typeof value==="object"&&value!==null&&(brand_privateStreamingFile in value),isUploadable=(value)=>typeof value==="object"&&value!==null&&(value instanceof Response||isAsyncIterable(value)||isReadableStream(value)||isStreamingFile(value)||isBlob(value)),hasStreamingUploadableValue=(value)=>{if(isStreamingFile(value)||isAsyncIterable(value)||isReadableStream(value))return!0;if(Array.isArray(value))return value.some(hasStreamingUploadableValue);if(value&&typeof value==="object"&&!isBlob(value)&&!(value instanceof Response)){for(let k of Object.keys(value))if(hasStreamingUploadableValue(value[k]))return!0}return!1},hasUploadableValue=(value)=>{if(isUploadable(value))return!0;if(Array.isArray(value))return value.some(hasUploadableValue);if(value&&typeof value==="object"){for(let k of Object.keys(value))if(hasUploadableValue(value[k]))return!0}return!1},snapshotPreservedUploadEntries=(entries,filenames)=>{let snapshot=[];for(let entry of entries){if(isUploadable(entry.value)&&!filenames.has(entry.value))filenames.set(entry.value,getStreamingFileName(entry.value,{stripFilenames:!1}));snapshot.push(entry)}return snapshot},streamingFormFinalizers,finalizeStreamingFormRequestOptions=(opts)=>{if(typeof opts.body!=="object"||opts.body===null)return;let finalize=streamingFormFinalizers.get(opts.body);if(finalize)opts.stream=finalize(),streamingFormFinalizers.delete(opts.body)},createStreamingFormRequestOptions=(opts,options={})=>{let entries=iterateFormEntries(opts.body),preservedFilenames=options.stripFilenames===!1?new WeakMap:void 0,multipartEntries=preservedFilenames?snapshotPreservedUploadEntries(entries,preservedFilenames):entries,boundary=`openai-${Math.random().toString(36).slice(2)}`;async function*multipartBody(){yield*iterateMultipartBody(multipartEntries,boundary,options,preservedFilenames)}let body=ReadableStreamFrom(multipartBody(),opts.__metadata?.streamFromBody===!0?{highWaterMark:0}:void 0),originalBody=opts.body;if(opts.__metadata?.streamFromBody===!0&&typeof originalBody==="object"&&originalBody!==null)streamingFormFinalizers.set(body,()=>{let capturedBody={...originalBody},capturedEntries=iterateFormEntries(capturedBody);multipartEntries=preservedFilenames?snapshotPreservedUploadEntries(capturedEntries,preservedFilenames):capturedEntries;let stream=Object.getOwnPropertyDescriptor(capturedBody,"stream")?.value;return stream===!0||stream==="true"});return{...opts,body,headers:buildHeaders([{"content-type":`multipart/form-data; boundary=${boundary}`},opts.headers])}},addFormValue=async(form,key,value,options)=>{if(value===void 0)return;if(value==null)throw TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);if(typeof value==="string"||typeof value==="number"||typeof value==="boolean")form.append(key,String(value));else if(value instanceof Response){let blob=await value.blob();form.append(key,makeFile([blob],getName(value,{stripFilename:options.stripFilenames}),{type:blob.type}))}else if(isAsyncIterable(value))form.append(key,makeFile([await new Response(ReadableStreamFrom(value)).blob()],getName(value,{stripFilename:options.stripFilenames})));else if(isBlob(value)){let filename=getName(value,{stripFilename:options.stripFilenames});if(filename===void 0)form.append(key,value);else form.append(key,value,filename)}else if(Array.isArray(value)){let entries=await Promise.all(value.map(async(entry)=>{let entryForm=new FormData;return await addFormValue(entryForm,key+"[]",entry,options),entryForm}));for(let entryForm of entries){if(!entryForm)continue;for(let[entryKey,entryValue]of entryForm.entries())form.append(entryKey,entryValue)}}else if(typeof value==="object")await Promise.all(Object.entries(value).map(([name,prop])=>addFormValue(form,`${key}[${name}]`,prop,options)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`)};var init_uploads=__esm(()=>{init_headers();brand_privateStreamingFile=Symbol("brand.privateStreamingFile");arrayBufferByteLengthGetter=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;supportsFormDataMap=new WeakMap;streamingFormFinalizers=new WeakMap});async function toFile(value,name,options){if(checkFileSupport(),value=await value,isFileLike(value)){let fileOptions={...options,type:options?.type??value.type,lastModified:options?.lastModified??value.lastModified};if(value instanceof File){if(canReuseNativeFile(value,name,options))return value;return makeFile([value],name??value.name,fileOptions)}return makeFile([await value.arrayBuffer()],name??value.name,fileOptions)}if(isResponseLike(value)){let blob=await value.blob();name??(name=getName(value));let responseOptions=options?.type===void 0&&blob.type?{...options,type:blob.type}:options;return makeFile(await getBytes(blob),name,responseOptions)}let parts=await getBytes(value);if(name??(name=getName(value)),options?.type===void 0){let typedPart=parts.find((part)=>typeof part==="object"&&("type"in part)&&!!part.type);if(typedPart)options={...options,type:typedPart.type}}return makeFile(parts,name,options)}async function getBytes(value){let parts=[];if(typeof value==="string"||ArrayBuffer.isView(value)||isArrayBuffer(value))parts.push(value);else if(isBlobLike(value))parts.push(value instanceof Blob?value:new Blob([await value.arrayBuffer()],{type:value.type}));else if(isAsyncIterable(value))for await(let chunk of value)parts.push(...await getBytes(chunk));else{let constructor=value?.constructor?.name;throw Error(`Unexpected data type: ${typeof value}${constructor?`; constructor: ${constructor}`:""}${propsForError(value)}`)}return parts}function propsForError(value){if(typeof value!=="object"||value===null)return"";return`; props: [${Object.getOwnPropertyNames(value).map((p)=>`"${p}"`).join(", ")}]`}var isBlobLike=(value)=>value!=null&&typeof value==="object"&&typeof value.size==="number"&&typeof value.type==="string"&&typeof value.text==="function"&&typeof value.slice==="function"&&typeof value.arrayBuffer==="function",isFileLike=(value)=>value!=null&&typeof value==="object"&&typeof value.name==="string"&&typeof value.lastModified==="number"&&isBlobLike(value),isResponseLike=(value)=>value!=null&&typeof value==="object"&&typeof value.url==="string"&&typeof value.blob==="function",hasFilePropertyOverrides=(value,options)=>options?.type!=null&&options.type!==value.type||options?.lastModified!=null&&options.lastModified!==value.lastModified||options?.endings!=null,canReuseNativeFile=(value,name,options)=>(name==null||name===value.name)&&!hasFilePropertyOverrides(value,options);var init_to_file=__esm(()=>{init_uploads()});var init_uploads2=__esm(()=>{init_uploads();init_to_file()});class APIResource{constructor(client){this._client=client}}function encodeURIPath(str){return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var EMPTY,createPathTagFunction=(pathEncoder=encodeURIPath)=>function(statics,...params){if(statics.length===1)return statics[0];let postPath=!1,invalidSegments=[],path="";for(let index=0;index<statics.length;index+=1)if(index in statics){let currentValue=statics[index];if(/[?#]/.test(currentValue))postPath=!0;let value=params[index],encoded=(postPath?encodeURIComponent:pathEncoder)(""+value);if(index!==params.length&&(value==null||typeof value==="object"&&value.toString===Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty??EMPTY)??EMPTY)?.toString))encoded=value+"",invalidSegments.push({start:path.length+currentValue.length,length:encoded.length,error:`Value of type ${Object.prototype.toString.call(value).slice(8,-1)} is not a valid path parameter`});path+=currentValue+(index===params.length?"":encoded)}let pathOnly=path.split(/[?#]/,1)[0],invalidSegmentPattern=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,match;while((match=invalidSegmentPattern.exec(pathOnly))!==null)invalidSegments.push({start:match.index,length:match[0].length,error:`Value "${match[0]}" can't be safely passed as a path parameter`});if(invalidSegments.sort((a,b)=>a.start-b.start),invalidSegments.length>0){let lastEnd=0,underline="";for(let segment of invalidSegments){let spaces=" ".repeat(segment.start-lastEnd),arrows="^".repeat(segment.length);lastEnd=segment.start+segment.length,underline+=spaces+arrows}throw new OpenAIError(`Path parameters result in path with invalid segments:
16
+ ${invalidSegments.map((e)=>e.error).join(`
17
+ `)}
18
+ ${path}
19
+ ${underline}`)}return path},path;var init_path=__esm(()=>{init_error();EMPTY=Object.freeze(Object.create(null)),path=createPathTagFunction(encodeURIPath)});function resolveResourceRequestOptions(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys,Messages;var init_messages=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Messages=class Messages extends APIResource{list(completionID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/chat/completions/${completionID}/messages`,CursorPage,resolveResourceRequestOptions(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}}});var init_error2=__esm(()=>{init_error()});function isChatCompletionFunctionTool(tool){return tool!==void 0&&"function"in tool&&tool.function!==void 0}function isAutoParsableResponseFormat(response_format){return response_format?.$brand==="auto-parseable-response-format"}function isParseableResponseFormat(format){return isAutoParsableResponseFormat(format)||format?.type==="json_schema"}function parseResponseFormatContent(format,content){if(!isParseableResponseFormat(format))return null;if(typeof format==="object"&&format!==null&&"$parseRaw"in format&&typeof format.$parseRaw==="function")return format.$parseRaw(content);try{return JSON.parse(content)}catch(error){if(error instanceof SyntaxError)throw SyntaxError("Error reading response: invalid structured output JSON.");throw error}}function isAutoParsableTool(tool){return tool?.$brand==="auto-parseable-tool"}function maybeParseChatCompletion(completion,params){if(!params||!hasAutoParseableInput(params))return{...completion,choices:completion.choices.map((choice)=>({...choice,message:{...choice.message,parsed:null,...choice.message.tool_calls?{tool_calls:choice.message.tool_calls}:void 0}}))};return parseChatCompletion(completion,params)}function parseChatCompletion(completion,params){let choices=completion.choices.map((choice)=>{if(choice.finish_reason==="length")throw new LengthFinishReasonError;if(choice.finish_reason==="content_filter")throw new ContentFilterFinishReasonError;return{...choice,message:{...choice.message,...choice.message.tool_calls?{tool_calls:choice.message.tool_calls?.map((toolCall)=>parseToolCall(params,toolCall))??void 0}:void 0,parsed:choice.message.content!==null&&choice.message.content!==void 0&&!choice.message.refusal&&(choice.message.content!==""||!choice.message.tool_calls?.length&&!choice.message.function_call)?parseResponseFormat(params,choice.message.content):null}}});return{...completion,choices}}function parseResponseFormat(params,content){return parseResponseFormatContent(params.response_format,content)}function parseToolCall(params,toolCall){if(toolCall.type==="custom")return toolCall;if(toolCall.type!=="function"){let unsupportedType=toolCall.type;throw new OpenAIError(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${unsupportedType}\``)}let inputTool=params.tools?.find((inputTool)=>isChatCompletionFunctionTool(inputTool)&&inputTool.function?.name===toolCall.function.name),parsedArguments=null;if(isAutoParsableTool(inputTool))parsedArguments=inputTool.$parseRaw(toolCall.function.arguments);else if(inputTool?.function.strict)parsedArguments=parseResponseFormatContent({type:"json_schema",$parseRaw:void 0},toolCall.function.arguments);return{...toolCall,function:{...toolCall.function,parsed_arguments:parsedArguments}}}function shouldParseToolCall(params,toolCall){if(!params||!("tools"in params)||!params.tools||toolCall.type!=="function")return!1;let inputTool=params.tools?.find((inputTool)=>isChatCompletionFunctionTool(inputTool)&&inputTool.function?.name===toolCall.function?.name);return isChatCompletionFunctionTool(inputTool)&&(isAutoParsableTool(inputTool)||inputTool?.function.strict||!1)}function hasAutoParseableInput(params){if(isParseableResponseFormat(params.response_format))return!0;return params.tools?.some((t)=>isAutoParsableTool(t)||t.type==="function"&&t.function.strict===!0)??!1}function validateInputTools(tools){for(let tool of tools??[]){if(tool.type==="custom")continue;if(tool.type!=="function"){let unsupportedType=tool.type;throw new OpenAIError(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${unsupportedType}\``)}if(tool.function.strict!==!0)throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var init_parser=__esm(()=>{init_error2()});var isAssistantMessage=(message)=>message?.role==="assistant",isToolMessage=(message)=>message?.role==="tool";function captureNativeProxyDetector(){if(typeof process>"u")return;try{let loader=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!loader||!("value"in loader)||typeof loader.value!=="function")return;let util=Reflect.apply(loader.value,process,["node:util"]);if(typeof util!=="object"||util===null)return;let types=Object.getOwnPropertyDescriptor(util,"types");if(!types||!("value"in types)||typeof types.value!=="object"||types.value===null)return;let detector=Object.getOwnPropertyDescriptor(types.value,"isProxy");if(!detector||!("value"in detector)||typeof detector.value!=="function")return;return detector.value}catch{return}}function rememberTrustedIntrinsic(constructor){if(typeof constructor!=="function")return;let prototypeDescriptor=Object.getOwnPropertyDescriptor(constructor,"prototype");if(!prototypeDescriptor||!("value"in prototypeDescriptor)||typeof prototypeDescriptor.value!=="object"&&typeof prototypeDescriptor.value!=="function")return;trustedIntrinsicPrototypes.add(prototypeDescriptor.value);let source=functionToString.call(constructor);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(source)&&prototypeDescriptor.configurable===!1&&prototypeDescriptor.writable===!1){trustedNativeConstructorSources.add(source);let descriptors=new Map;for(let key of Reflect.ownKeys(prototypeDescriptor.value)){let descriptor=Object.getOwnPropertyDescriptor(prototypeDescriptor.value,key);if(descriptor)descriptors.set(key,descriptor)}canonicalIntrinsicDescriptors.set(source,descriptors)}}function getTrustedForeignIntrinsic(prototype){let descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(!descriptor||!("value"in descriptor)||typeof descriptor.value!=="function")return;let constructor=descriptor.value,source=functionToString.call(constructor),descriptors=canonicalIntrinsicDescriptors.get(source);if(!trustedNativeConstructorSources.has(source)||!descriptors)return;let constructorPrototype=Object.getOwnPropertyDescriptor(constructor,"prototype");if(!constructorPrototype||!("value"in constructorPrototype)||constructorPrototype.value!==prototype||constructorPrototype.configurable!==!1||constructorPrototype.writable!==!1)return;return{constructor,descriptors,functionPrototype:Object.getPrototypeOf(constructor)}}function isTrustedIntrinsicPrototype(prototype){return trustedIntrinsicPrototypes.has(prototype)||getTrustedForeignIntrinsic(prototype)!==void 0}function isCanonicalIntrinsicFunction(value,canonical,functionPrototype){if(canonical===void 0)return value===void 0;if(typeof value!=="function"||typeof canonical!=="function")return!1;let source=functionToString.call(canonical);if(functionToString.call(value)!==source)return!1;let actualFunctionPrototype=Object.getPrototypeOf(value);if(actualFunctionPrototype===functionPrototype)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(source))return!1;let intrinsic=getTrustedForeignIntrinsic(actualFunctionPrototype);return intrinsic!==void 0&&functionToString.call(intrinsic.constructor)===nativeFunctionConstructorSource}function isCanonicalIntrinsicDescriptor(descriptor,canonical,functionPrototype){if(!canonical||descriptor.configurable!==canonical.configurable||descriptor.enumerable!==canonical.enumerable||"value"in descriptor!=="value"in canonical)return!1;if("value"in descriptor&&"value"in canonical){if(descriptor.writable!==canonical.writable)return!1;if(typeof canonical.value==="function")return isCanonicalIntrinsicFunction(descriptor.value,canonical.value,functionPrototype);if(canonical.value!==null&&typeof canonical.value==="object")return!1;return Object.is(descriptor.value,canonical.value)}return isCanonicalIntrinsicFunction(descriptor.get,canonical.get,functionPrototype)&&isCanonicalIntrinsicFunction(descriptor.set,canonical.set,functionPrototype)}function hasNativeErrorBrand(current){if(nativeErrorBrand)return nativeErrorBrand.call(Error,current);let prototype=current;for(let depth=0;prototype!==null&&depth<MAX_BUFFERED_EVENT_DEPTH;depth+=1){if(Object.getOwnPropertyDescriptor(prototype,Symbol.toStringTag))return!1;prototype=Object.getPrototypeOf(prototype)}return prototype===null&&objectToString.call(current)==="[object Error]"}function getVerifiedForeignErrorConstructor(current,stackDescriptor){if(typeof stackDescriptor.get!=="function"||typeof stackDescriptor.set!=="function")return;let prototype=Object.getPrototypeOf(current);for(let depth=0;prototype!==null&&depth<MAX_BUFFERED_EVENT_DEPTH;depth+=1){let descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(descriptor&&"value"in descriptor&&typeof descriptor.value==="function"){let constructor=descriptor.value;if(functionToString.call(constructor)===nativeErrorConstructorSource&&isTrustedIntrinsicPrototype(prototype)){let functionPrototype=Object.getPrototypeOf(constructor);if(Object.getPrototypeOf(stackDescriptor.get)===functionPrototype&&Object.getPrototypeOf(stackDescriptor.set)===functionPrototype)return{constructor,prototype};return}}prototype=Object.getPrototypeOf(prototype)}return}function isTrustedNativeErrorStack(current,descriptor){if(!hasNativeErrorBrand(current))return!1;if(errorStackDescriptor&&!("value"in errorStackDescriptor)&&typeof errorStackDescriptor.get==="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,current)&&descriptor.get===errorStackDescriptor.get&&descriptor.set===errorStackDescriptor.set)return!0;let verified=getVerifiedForeignErrorConstructor(current,descriptor);if(!verified)return!1;let canonicalDescriptor=foreignErrorStackDescriptors.get(verified.prototype);if(!canonicalDescriptor){let canonical=Reflect.construct(verified.constructor,[]);if(typeof canonical!=="object"||canonical===null||!hasNativeErrorBrand(canonical)||Object.getPrototypeOf(canonical)!==verified.prototype)return!1;if(canonicalDescriptor=Object.getOwnPropertyDescriptor(canonical,"stack"),!canonicalDescriptor||"value"in canonicalDescriptor||typeof canonicalDescriptor.get!=="function"||typeof canonicalDescriptor.set!=="function")return!1;foreignErrorStackDescriptors.set(verified.prototype,canonicalDescriptor)}return descriptor.get===canonicalDescriptor.get&&descriptor.set===canonicalDescriptor.set}function createEventQueue(){let entries=[],head=0;return{get length(){return entries.length-head},enqueue(value){entries.push(value)},dequeue(){if(head===entries.length)return;let value=entries[head];if(entries[head]=void 0,head+=1,head===entries.length)entries=[],head=0;else if(head>=1024&&head*2>=entries.length)entries=entries.slice(head),head=0;return value},clear(){entries=[],head=0}}}function getRetainedStorageBrand(current){let prototype=Object.getPrototypeOf(current);for(let depth=0;prototype!==null&&depth<MAX_BUFFERED_EVENT_DEPTH;depth+=1){if(prototype===Date.prototype)return"Date";if(!trustedIntrinsicPrototypes.has(prototype)){let constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(constructor&&"value"in constructor&&typeof constructor.value==="function"&&functionToString.call(constructor.value)===nativeDateConstructorSource&&getTrustedForeignIntrinsic(prototype))return"Date"}let descriptor=Object.getOwnPropertyDescriptor(prototype,Symbol.toStringTag);if(descriptor&&"value"in descriptor&&typeof descriptor.value==="string"&&retainedStorageBrands.has(descriptor.value))return descriptor.value;prototype=Object.getPrototypeOf(prototype)}return}function estimateRetainedBufferBytes(current,visit,depth){if(ArrayBuffer.isView(current)){let buffer,kind="typed-array";try{buffer=typedArrayBufferGetter?.call(current)}catch{kind="data-view",buffer=dataViewBufferGetter?.call(current)}if(typeof buffer!=="object"||buffer===null)return{bytes:Number.POSITIVE_INFINITY,kind};return visit(buffer,depth+1),{bytes:0,kind}}let brand=getRetainedStorageBrand(current);if(!brand)return;let getter,kind="buffer";switch(brand){case"ArrayBuffer":{getter=arrayBufferByteLengthGetter2;break}case"SharedArrayBuffer":{getter=sharedArrayBufferByteLengthGetter;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(dateTimestampGetter,current,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let bytes=getter?.call(current);return{bytes:typeof bytes==="number"&&Number.isSafeInteger(bytes)&&bytes>=0?bytes:Number.POSITIVE_INFINITY,kind}}function visitHiddenEventValues(current,kind,visit){if(kind==="map"){for(let[key,entry]of mapEntries.call(current))if(!visit(key,8)||!visit(entry,8))return!1}if(kind==="set"){for(let entry of setValues.call(current))if(!visit(entry,8))return!1}if(kind==="headers"){if(!headersEntries)return!1;for(let[name,value]of headersEntries.call(current))if(!visit(name,8)||!visit(value,8))return!1}return!0}function getInspectableEventKeys(current,kind,availableBytes){if(Array.isArray(current)){let descriptor=Object.getOwnPropertyDescriptor(current,"length"),length=descriptor&&"value"in descriptor?descriptor.value:void 0;if(typeof length!=="number"||!Number.isSafeInteger(length)||length<0||length>Math.floor(availableBytes/16))return}if(kind!=="typed-array")return Reflect.ownKeys(current);let length=typedArrayLengthGetter?.call(current);if(typeof length!=="number"||!Number.isSafeInteger(length)||length<0||length>MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS)return;return Reflect.ownKeys(current).filter((key)=>{if(typeof key!=="string")return!0;let index=Number(key);return!Number.isInteger(index)||index<0||index>=length||String(index)!==key})}function visitInspectableEventProperties(current,kind,depth,availableBytes,charge,visit){let keys=getInspectableEventKeys(current,kind,availableBytes());if(keys===void 0)return!1;for(let key of keys){if(!charge(typeof key==="string"?key.length*2+8:8))return!1;if(typeof key==="symbol")visit(key,depth+1);let descriptor=Object.getOwnPropertyDescriptor(current,key);if(!descriptor)return!1;if(!("value"in descriptor)){if(key==="stack"&&isTrustedNativeErrorStack(current,descriptor))continue;return!1}visit(descriptor.value,depth+1,kind==="blob")}return!0}function visitRetainedEventPrototypes(current,depth,isBlobInternalHandle,visited,availableBytes,charge,visit,retainPrototype){let prototype=Object.getPrototypeOf(current);for(let prototypeDepth=depth+1;prototype!==null;prototypeDepth+=1){if(prototypeDepth>=MAX_BUFFERED_EVENT_DEPTH)return!1;if(trustedIntrinsicPrototypes.has(prototype)||isBlobInternalHandle&&prototype===blobInternalHandlePrototype)return!0;if(visited.has(prototype))return visit(prototype,prototypeDepth),availableBytes()>=0;visited.add(prototype);let retainedPrototype=prototype;if(!retainPrototype(retainedPrototype,()=>{if(!charge(16))return!1;let intrinsic=getTrustedForeignIntrinsic(retainedPrototype);if(!intrinsic)return visitInspectableEventProperties(retainedPrototype,void 0,prototypeDepth,availableBytes,charge,visit);for(let key of Reflect.ownKeys(retainedPrototype)){let descriptor=Object.getOwnPropertyDescriptor(retainedPrototype,key);if(!descriptor)return!1;if(isCanonicalIntrinsicDescriptor(descriptor,intrinsic.descriptors.get(key),intrinsic.functionPrototype))continue;if(!charge(typeof key==="string"?key.length*2+8:8)||!("value"in descriptor))return!1;if(typeof key==="symbol")visit(key,prototypeDepth+1);visit(descriptor.value,prototypeDepth+1)}return availableBytes()>=0}))return!1;prototype=Object.getPrototypeOf(retainedPrototype)}return!0}function inspectBufferedEventGraph(value,remainingBytes){let bytes=0,scalarBytes=0,visited=new WeakSet,visitedSymbols=new Set,roots=new Set,nodes=new Map,activeNode,availableBytes=()=>remainingBytes-bytes,charge=(amount)=>{if(!Number.isSafeInteger(amount)||amount<0)return bytes=remainingBytes+1,!1;if(bytes+=amount,activeNode)activeNode.bytes+=amount;else scalarBytes+=amount;return bytes<=remainingBytes},addIdentity=(identity)=>{if(activeNode)activeNode.edges.add(identity);else roots.add(identity)},retainIdentity=(identity,inspect)=>{addIdentity(identity);let node={bytes:0,edges:new Set};nodes.set(identity,node);let previous=activeNode;activeNode=node;try{return inspect()}finally{activeNode=previous}},visitSymbol=(current)=>{if(visitedSymbols.has(current)){addIdentity(current),charge(8);return}if(visitedSymbols.add(current),!retainIdentity(current,()=>{if(!symbolDescriptionGetter)return!1;let description=Reflect.apply(symbolDescriptionGetter,current,[]);return charge(8+(description?.length??0)*2)}))bytes=remainingBytes+1},visit=(current,depth,isBlobInternalHandle=!1)=>{if(bytes>remainingBytes)return;if(typeof current==="string"){charge(current.length*2);return}if(typeof current==="symbol"){visitSymbol(current);return}if(typeof current==="function"){bytes=remainingBytes+1;return}if(current===null||typeof current!=="object"){charge(8);return}if(nativeProxyDetector?.(current)){bytes=remainingBytes+1;return}if(depth>=MAX_BUFFERED_EVENT_DEPTH){bytes=remainingBytes+1;return}if(visited.has(current)){addIdentity(current),charge(8);return}if(visited.add(current),!retainIdentity(current,()=>{if(!charge(16))return!1;let retainedStorage=estimateRetainedBufferBytes(current,visit,depth);if(!visitRetainedEventPrototypes(current,depth,isBlobInternalHandle,visited,availableBytes,charge,visit,retainIdentity))return!1;if(retainedStorage!==void 0&&!charge(retainedStorage.bytes))return!1;if(!visitHiddenEventValues(current,retainedStorage?.kind,(hiddenValue,overhead)=>{if(!charge(overhead))return!1;return visit(hiddenValue,depth+1),bytes<=remainingBytes}))return!1;return visitInspectableEventProperties(current,retainedStorage?.kind,depth,availableBytes,charge,visit)}))bytes=remainingBytes+1};try{visit(value,0)}catch{return}return bytes<=remainingBytes?{scalarBytes,roots,nodes}:void 0}function areBufferedRetainedEdgesEqual(first,second){if(first.size!==second.size)return!1;for(let identity of first)if(!second.has(identity))return!1;return!0}function getBufferedLedgerNodeBytes(node,owners){return node.bytes+BUFFERED_LEDGER_NODE_BYTES+node.edges.size*BUFFERED_LEDGER_EDGE_BYTES+owners*BUFFERED_LEDGER_OWNER_BYTES}function getBufferedLedgerEntryBytes(entry){return BUFFERED_LEDGER_ENTRY_BYTES+entry.scalarBytes+entry.roots.size*BUFFERED_LEDGER_EDGE_BYTES}function collectBufferedLedgerIdentities(roots,candidate,records,work){let identities=new Set,pending=[...roots];while(pending.length){if(work.remaining-=1,work.remaining<0)return;let identity=pending.pop();if(identities.has(identity))continue;let node=candidate.get(identity)??records.get(identity);if(!node)return;identities.add(identity);for(let edge of node.edges)pending.push(edge)}return identities}function getBufferedLedgerChange(identity,graph,records,changes,node){let existing=changes.get(identity);if(existing){if(node)existing.node=node;return existing}let current=node??graph.nodes.get(identity)??records.get(identity);if(!current)return;let update={node:current,ownerDelta:0};return changes.set(identity,update),update}function findBufferedLedgerAffectedOwners(entry,graph,records,changes,work){let affected=new Set([entry]);for(let[identity,node]of graph.nodes){if(work.remaining-=1,work.remaining<0)return;let previous=records.get(identity);if(!previous)continue;let changedEdges=!areBufferedRetainedEdgesEqual(previous.edges,node.edges);if(previous.bytes!==node.bytes||changedEdges)getBufferedLedgerChange(identity,graph,records,changes,node);if(!changedEdges)continue;for(let owner of previous.owners){if(work.remaining-=1,work.remaining<0)return;affected.add(owner)}}return affected}function updateBufferedLedgerMembershipChanges(owner,next,graph,records,changes,work){for(let identity of owner.identities){if(work.remaining-=1,work.remaining<0)return!1;if(!next.has(identity)){let update=getBufferedLedgerChange(identity,graph,records,changes);if(!update)return!1;update.ownerDelta-=1}}for(let identity of next){if(work.remaining-=1,work.remaining<0)return!1;if(!owner.identities.has(identity)){let update=getBufferedLedgerChange(identity,graph,records,changes);if(!update)return!1;update.ownerDelta+=1}}return!0}function collectBufferedLedgerMemberships(entry,graph,affected,records,changes,work){let memberships=new Map;for(let owner of affected){let roots=owner===entry?graph.roots:owner.roots,next=collectBufferedLedgerIdentities(roots,graph.nodes,records,work);if(!next||!updateBufferedLedgerMembershipChanges(owner,next,graph,records,changes,work))return;memberships.set(owner,next)}return memberships}function projectBufferedLedgerBytes(currentBytes,entry,graph,isNew,changes,records){let projected=currentBytes-(isNew?0:getBufferedLedgerEntryBytes(entry))+getBufferedLedgerEntryBytes(graph);for(let[identity,update]of changes){let previous=records.get(identity),owners=(previous?.owners.size??0)+update.ownerDelta;if(owners<0)return;if(previous)projected-=getBufferedLedgerNodeBytes(previous,previous.owners.size);if(owners)projected+=getBufferedLedgerNodeBytes(update.node,owners)}return Number.isSafeInteger(projected)&&projected>=0&&projected<=MAX_BUFFERED_ITERATOR_BYTES?projected:void 0}function applyBufferedLedgerChanges(records,changes,memberships){for(let[identity,update]of changes){let previous=records.get(identity);if(!((previous?.owners.size??0)+update.ownerDelta))continue;if(previous)previous.bytes=update.node.bytes,previous.edges=update.node.edges;else records.set(identity,{bytes:update.node.bytes,edges:update.node.edges,owners:new Set})}for(let[owner,next]of memberships){for(let identity of owner.identities)if(!next.has(identity))records.get(identity)?.owners.delete(owner);for(let identity of next)if(!owner.identities.has(identity))records.get(identity).owners.add(owner);owner.identities=next}for(let identity of changes.keys())if(records.get(identity)?.owners.size===0)records.delete(identity)}function createBufferedEventLedger(){let records=new Map,bytes=0,reconcile=(entry,graph,isNew)=>{let work={remaining:MAX_BUFFERED_LEDGER_RECONCILIATION_WORK},changes=new Map,affected=findBufferedLedgerAffectedOwners(entry,graph,records,changes,work);if(!affected)return!1;let memberships=collectBufferedLedgerMemberships(entry,graph,affected,records,changes,work);if(!memberships)return!1;let projectedBytes=projectBufferedLedgerBytes(bytes,entry,graph,isNew,changes,records);if(projectedBytes===void 0)return!1;return applyBufferedLedgerChanges(records,changes,memberships),entry.scalarBytes=graph.scalarBytes,entry.roots=graph.roots,bytes=projectedBytes,!0};return{retain(graph){let entry={scalarBytes:0,roots:new Set,identities:new Set};return reconcile(entry,graph,!0)?entry:void 0},refresh(entry,graph){return reconcile(entry,graph,!1)},release:(entry)=>{bytes-=getBufferedLedgerEntryBytes(entry);for(let identity of entry.identities){let record=records.get(identity);if(!record?.owners.delete(entry))continue;if(bytes-=BUFFERED_LEDGER_OWNER_BYTES,record.owners.size===0)bytes-=getBufferedLedgerNodeBytes(record,0),records.delete(identity)}entry.identities.clear()},clear(){records.clear(),bytes=0}}}class EventStream{constructor(){_EventStream_instances.add(this),this.controller=new AbortController,_EventStream_connectedPromise.set(this,void 0),_EventStream_resolveConnectedPromise.set(this,()=>{return}),_EventStream_rejectConnectedPromise.set(this,()=>{return}),_EventStream_endPromise.set(this,void 0),_EventStream_resolveEndPromise.set(this,()=>{return}),_EventStream_rejectEndPromise.set(this,()=>{return}),_EventStream_listeners.set(this,Object.create(null)),_EventStream_abortListeners.set(this,[]),_EventStream_emittedListenerRegistrations.set(this,new WeakMap),_EventStream_pendingListenerCleanup.set(this,new Set),_EventStream_pendingBufferedEventChecks.set(this,new Set),_EventStream_listenerDispatchDepth.set(this,0),_EventStream_ended.set(this,!1),_EventStream_errored.set(this,!1),_EventStream_aborted.set(this,!1),_EventStream_catchingPromiseCreated.set(this,!1),_EventStream_terminalFailure.set(this,void 0),__classPrivateFieldSet(this,_EventStream_connectedPromise,new Promise((resolve,reject)=>{__classPrivateFieldSet(this,_EventStream_resolveConnectedPromise,resolve,"f"),__classPrivateFieldSet(this,_EventStream_rejectConnectedPromise,reject,"f")}),"f"),__classPrivateFieldSet(this,_EventStream_endPromise,new Promise((resolve,reject)=>{__classPrivateFieldSet(this,_EventStream_resolveEndPromise,resolve,"f"),__classPrivateFieldSet(this,_EventStream_rejectEndPromise,reject,"f")}),"f"),__classPrivateFieldGet(this,_EventStream_connectedPromise,"f").catch(()=>{return}),__classPrivateFieldGet(this,_EventStream_endPromise,"f").catch(()=>{return})}_run(executor){setTimeout(()=>{let failed=!1;Promise.resolve().then(executor).catch((error)=>{failed=!0,__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_handleError).call(this,error)}).then(()=>{if(failed)return;try{this._emitFinal()}catch(error){__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_handleError).call(this,error);return}this._emit("end")})},0)}_connected(){if(this.ended)return;__classPrivateFieldGet(this,_EventStream_resolveConnectedPromise,"f").call(this),this._emit("connect")}get ended(){return __classPrivateFieldGet(this,_EventStream_ended,"f")}get errored(){return __classPrivateFieldGet(this,_EventStream_errored,"f")}get aborted(){return __classPrivateFieldGet(this,_EventStream_aborted,"f")}abort(){this.controller.abort()}_userAbortError(){let error=new APIUserAbortError;return Object.defineProperty(error,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),error}_listenForAbort(signal){if(!signal||this.ended)return;if(signal.aborted){__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_abortFromSignal).call(this,signal);return}if(__classPrivateFieldGet(this,_EventStream_abortListeners,"f").some((registration)=>registration.signal===signal))return;let listener=()=>__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_abortFromSignal).call(this,signal);signal.addEventListener("abort",listener,{once:!0}),__classPrivateFieldGet(this,_EventStream_abortListeners,"f").push({signal,listener})}on(event,listener){var _a;return((_a=__classPrivateFieldGet(this,_EventStream_listeners,"f"))[event]||(_a[event]=[])).push({listener}),this}off(event,listener){let listeners=__classPrivateFieldGet(this,_EventStream_listeners,"f")[event];if(!listeners)return this;let emittedRegistration=__classPrivateFieldGet(this,_EventStream_emittedListenerRegistrations,"f").get(listener);if(emittedRegistration?.event===event&&!emittedRegistration.registration.removed&&!emittedRegistration.registration.detached)return __classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_removeEmittedListener).call(this,event,emittedRegistration.registration),this;let index=listeners.findIndex((l)=>!l.removed&&l.listener===listener);if(index!==-1)listeners.splice(index,1);return this}once(event,listener){var _a;return((_a=__classPrivateFieldGet(this,_EventStream_listeners,"f"))[event]||(_a[event]=[])).push({listener,once:!0}),this}emitted(event){return new Promise((resolve,reject)=>{__classPrivateFieldSet(this,_EventStream_catchingPromiseCreated,!0,"f");let onError=(error)=>{this.off(event,onEvent),reject(error)},onEvent=(...values)=>{if(event!=="error")this.off("error",onError);resolve(values.length>1?values:values[0])};if(event!=="error")__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_onceForEmitted).call(this,"error",onError);__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_onceForEmitted).call(this,event,onEvent)})}events(event){return this._createIterator((push)=>{let onEvent=(...args)=>{sdkOwnedBufferedEventArguments.add(args);try{push(args)}finally{sdkOwnedBufferedEventArguments.delete(args)}};return this.on(event,onEvent),()=>this.off(event,onEvent)},{rejectOnError:event!=="error",rejectOnAbort:event!=="abort"})}_createIterator(attach,{rejectOnError=!0,rejectOnAbort=!0,onReturn}={}){let pushQueue=createEventQueue(),bufferedEventSizes=createEventQueue(),readQueue=createEventQueue(),bufferedLedger=createBufferedEventLedger(),ended=this.ended,failure,failureDelivered=!1,detach=()=>{return},doneResult=()=>({value:void 0,done:!0}),finishReaders=()=>{while(readQueue.length)readQueue.dequeue().resolve(doneResult())},rejectReader=()=>{if(!failure||failureDelivered||!readQueue.length)return;failureDelivered=!0,readQueue.dequeue().reject(failure)},cleanup=()=>{if(detach(),this.off("end",onEnd),rejectOnError)this.off("error",onFailure);if(rejectOnAbort)this.off("abort",onFailure)},deactivateBufferedEvent=(entry)=>{if(entry.active=!1,entry.check)__classPrivateFieldGet(this,_EventStream_pendingBufferedEventChecks,"f").delete(entry.check),entry.check=void 0},failBufferedEvents=(discardRetained=!1)=>{if(discardRetained){while(bufferedEventSizes.length)deactivateBufferedEvent(bufferedEventSizes.dequeue());pushQueue.clear(),bufferedLedger.clear()}let error=new OpenAIError(`Event stream iterator buffer limit exceeded (${MAX_BUFFERED_ITERATOR_EVENTS} events or ${MAX_BUFFERED_ITERATOR_BYTES} bytes); consume events as they arrive.`);try{__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_handleError).call(this,error)}finally{this.controller.abort()}return error},revalidateBufferedEvent=(value,entry)=>{if(!entry.active||__classPrivateFieldGet(this,_EventStream_ended,"f"))return;let graph=inspectBufferedEventGraph(value,MAX_BUFFERED_ITERATOR_BYTES);if(!graph||!bufferedLedger.refresh(entry.retention,graph))failBufferedEvents(!0)},push=(value)=>{if(ended)return;let reader=readQueue.dequeue();if(reader)reader.resolve({value,done:!1});else{if(pushQueue.length>=MAX_BUFFERED_ITERATOR_EVENTS){failBufferedEvents();return}let graph=inspectBufferedEventGraph(value,MAX_BUFFERED_ITERATOR_BYTES),retention=graph&&bufferedLedger.retain(graph);if(!retention){failBufferedEvents();return}if(typeof value==="object"&&value!==null&&sdkOwnedBufferedEventArguments.has(value)){let argumentsTuple=value;for(let index=0;index<argumentsTuple.length;index+=1){let argument=argumentsTuple[index];if(typeof argument==="string")argumentsTuple[index]=bufferedJSONParse(bufferedJSONStringify(argument))}}let entry={retention,active:!0,check:void 0};pushQueue.enqueue(value),bufferedEventSizes.enqueue(entry);let check=()=>{entry.check=void 0,revalidateBufferedEvent(value,entry)};entry.check=check,__classPrivateFieldGet(this,_EventStream_pendingBufferedEventChecks,"f").add(check)}},onFailure=(error)=>{if(failure=error,!pushQueue.length)rejectReader()},adoptTerminalFailure=()=>{if(failure)return;let terminal=__classPrivateFieldGet(this,_EventStream_terminalFailure,"f");if(!terminal)return;if(terminal.kind==="error"?rejectOnError:rejectOnAbort)failure=terminal.error},onEnd=()=>{if(ended=!0,adoptTerminalFailure(),cleanup(),!pushQueue.length)rejectReader(),finishReaders()};if(!ended){if(detach=attach(push),this.on("end",onEnd),rejectOnError)this.on("error",onFailure);if(rejectOnAbort)this.on("abort",onFailure)}return{next:()=>{if(pushQueue.length){let value=pushQueue.dequeue(),entry=bufferedEventSizes.dequeue();deactivateBufferedEvent(entry);let graph=inspectBufferedEventGraph(value,MAX_BUFFERED_ITERATOR_BYTES);if(!graph||!bufferedLedger.refresh(entry.retention,graph)){let error=failBufferedEvents(!0);return failureDelivered=!0,Promise.reject(error)}return bufferedLedger.release(entry.retention),Promise.resolve({value,done:!1})}if(ended||this.ended)adoptTerminalFailure();if(failure&&!failureDelivered)return failureDelivered=!0,Promise.reject(failure);if(ended)return Promise.resolve(doneResult());return new Promise((resolve,reject)=>{readQueue.enqueue({resolve,reject})})},return:()=>{ended=!0,failureDelivered=!0;while(bufferedEventSizes.length)deactivateBufferedEvent(bufferedEventSizes.dequeue());if(pushQueue.clear(),bufferedLedger.clear(),cleanup(),finishReaders(),onReturn)this.done().catch(()=>{return}),onReturn();return Promise.resolve(doneResult())},[Symbol.asyncIterator](){return this}}}async done(){__classPrivateFieldSet(this,_EventStream_catchingPromiseCreated,!0,"f"),await __classPrivateFieldGet(this,_EventStream_endPromise,"f")}_hasListeners(event){return Boolean(__classPrivateFieldGet(this,_EventStream_listeners,"f")[event]?.some((listener)=>!listener.removed))}_emit(event,...args){if(__classPrivateFieldGet(this,_EventStream_ended,"f"))return;if(event==="end")__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_removeAbortListeners).call(this),__classPrivateFieldSet(this,_EventStream_ended,!0,"f"),__classPrivateFieldGet(this,_EventStream_resolveEndPromise,"f").call(this);let listeners=__classPrivateFieldGet(this,_EventStream_listeners,"f")[event],dispatchError,dispatchThrew=!1;try{if(listeners){__classPrivateFieldGet(this,_EventStream_listeners,"f")[event]=listeners.filter((listener)=>{if(listener.once)listener.detached=!0;return!listener.once&&!listener.removed}),__classPrivateFieldSet(this,_EventStream_listenerDispatchDepth,__classPrivateFieldGet(this,_EventStream_listenerDispatchDepth,"f")+1,"f");try{for(let registration of listeners)if(!registration.removed){let{listener}=registration;listener(...args)}}finally{if(__classPrivateFieldSet(this,_EventStream_listenerDispatchDepth,__classPrivateFieldGet(this,_EventStream_listenerDispatchDepth,"f")-1,"f"),__classPrivateFieldGet(this,_EventStream_listenerDispatchDepth,"f")===0){__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_cleanupEmittedListeners).call(this);for(let check of __classPrivateFieldGet(this,_EventStream_pendingBufferedEventChecks,"f"))if(__classPrivateFieldGet(this,_EventStream_pendingBufferedEventChecks,"f").delete(check),!__classPrivateFieldGet(this,_EventStream_ended,"f"))check()}}}}catch(error){dispatchError=error,dispatchThrew=!0}try{__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_settleTerminalEvent).call(this,event,args,Boolean(listeners?.length))}catch(error){if(!dispatchThrew)dispatchError=error,dispatchThrew=!0}if(dispatchThrew)throw dispatchError}_emitFinal(){}}var _EventStream_instances,_EventStream_connectedPromise,_EventStream_resolveConnectedPromise,_EventStream_rejectConnectedPromise,_EventStream_endPromise,_EventStream_resolveEndPromise,_EventStream_rejectEndPromise,_EventStream_listeners,_EventStream_abortListeners,_EventStream_emittedListenerRegistrations,_EventStream_pendingListenerCleanup,_EventStream_pendingBufferedEventChecks,_EventStream_listenerDispatchDepth,_EventStream_ended,_EventStream_errored,_EventStream_aborted,_EventStream_catchingPromiseCreated,_EventStream_terminalFailure,_EventStream_abortFromSignal,_EventStream_removeAbortListeners,_EventStream_onceForEmitted,_EventStream_removeEmittedListener,_EventStream_cleanupEmittedListeners,_EventStream_handleError,_EventStream_settleTerminalEvent,MAX_BUFFERED_ITERATOR_EVENTS=4096,MAX_BUFFERED_ITERATOR_BYTES=8388608,MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS=4096,MAX_BUFFERED_EVENT_DEPTH=256,bufferedJSONStringify,bufferedJSONParse,sdkOwnedBufferedEventArguments,typedArrayBufferGetter,typedArrayLengthGetter,dataViewBufferGetter,symbolDescriptionGetter,dateTimestampGetter,arrayBufferByteLengthGetter2,sharedArrayBufferByteLengthGetter,errorStackDescriptor,functionToString,objectToString,errorBrandDescriptor,nativeErrorBrand,nativeErrorConstructorSource,nativeDateConstructorSource,nativeFunctionConstructorSource,trustedIntrinsicPrototypes,trustedNativeConstructorSources,canonicalIntrinsicDescriptors,foreignErrorStackDescriptors,nativeProxyDetector,typedArrayConstructorDescriptor,blobInternalHandlePrototype,mapEntries,setValues,headersEntriesDescriptor,headersEntries,retainedStorageBrands,BUFFERED_LEDGER_ENTRY_BYTES=32,BUFFERED_LEDGER_NODE_BYTES=32,BUFFERED_LEDGER_EDGE_BYTES=8,BUFFERED_LEDGER_OWNER_BYTES=16,MAX_BUFFERED_LEDGER_RECONCILIATION_WORK=131072;var init_EventStream=__esm(()=>{init_tslib();init_error2();bufferedJSONStringify=JSON.stringify,bufferedJSONParse=JSON.parse,sdkOwnedBufferedEventArguments=new WeakSet,typedArrayBufferGetter=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,typedArrayLengthGetter=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,dataViewBufferGetter=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,symbolDescriptionGetter=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,dateTimestampGetter=Date.prototype.getTime,arrayBufferByteLengthGetter2=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,sharedArrayBufferByteLengthGetter=typeof SharedArrayBuffer==="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,errorStackDescriptor=Object.getOwnPropertyDescriptor(Error("native stack descriptor"),"stack"),functionToString=Function.prototype.toString,objectToString=Object.prototype.toString,errorBrandDescriptor=Object.getOwnPropertyDescriptor(Error,"isError"),nativeErrorBrand=errorBrandDescriptor&&"value"in errorBrandDescriptor&&typeof errorBrandDescriptor.value==="function"?errorBrandDescriptor.value:void 0,nativeErrorConstructorSource=functionToString.call(Error),nativeDateConstructorSource=functionToString.call(Date),nativeFunctionConstructorSource=functionToString.call(Function),trustedIntrinsicPrototypes=new Set([APIConnectionError.prototype,APIConnectionTimeoutError.prototype,APIError.prototype,OpenAIError.prototype,APIUserAbortError.prototype,AuthenticationError.prototype,BadRequestError.prototype,ConflictError.prototype,ContentFilterFinishReasonError.prototype,InternalServerError.prototype,InvalidWebhookSignatureError.prototype,LengthFinishReasonError.prototype,NotFoundError.prototype,OAuthError.prototype,PermissionDeniedError.prototype,RateLimitError.prototype,SubjectTokenProviderError.prototype,UnprocessableEntityError.prototype]),trustedNativeConstructorSources=new Set,canonicalIntrinsicDescriptors=new Map,foreignErrorStackDescriptors=new WeakMap;nativeProxyDetector=captureNativeProxyDetector();for(let constructor of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])rememberTrustedIntrinsic(constructor);for(let name of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let descriptor=Object.getOwnPropertyDescriptor(globalThis,name);if(descriptor&&"value"in descriptor)rememberTrustedIntrinsic(descriptor.value)}typedArrayConstructorDescriptor=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");if(typedArrayConstructorDescriptor&&"value"in typedArrayConstructorDescriptor)rememberTrustedIntrinsic(typedArrayConstructorDescriptor.value);if(typeof Buffer==="function")rememberTrustedIntrinsic(Buffer);blobInternalHandlePrototype=(()=>{if(typeof Blob!=="function")return;try{let blob=new Blob([]);for(let key of Object.getOwnPropertySymbols(blob)){let descriptor=Object.getOwnPropertyDescriptor(blob,key);if(descriptor&&"value"in descriptor&&typeof descriptor.value==="object"&&descriptor.value)return Object.getPrototypeOf(descriptor.value)}}catch{return}return})(),mapEntries=Map.prototype.entries,setValues=Set.prototype.values,headersEntriesDescriptor=typeof Headers==="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,headersEntries=headersEntriesDescriptor&&"value"in headersEntriesDescriptor&&typeof headersEntriesDescriptor.value==="function"?headersEntriesDescriptor.value:void 0,retainedStorageBrands=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);_EventStream_connectedPromise=new WeakMap,_EventStream_resolveConnectedPromise=new WeakMap,_EventStream_rejectConnectedPromise=new WeakMap,_EventStream_endPromise=new WeakMap,_EventStream_resolveEndPromise=new WeakMap,_EventStream_rejectEndPromise=new WeakMap,_EventStream_listeners=new WeakMap,_EventStream_abortListeners=new WeakMap,_EventStream_emittedListenerRegistrations=new WeakMap,_EventStream_pendingListenerCleanup=new WeakMap,_EventStream_pendingBufferedEventChecks=new WeakMap,_EventStream_listenerDispatchDepth=new WeakMap,_EventStream_ended=new WeakMap,_EventStream_errored=new WeakMap,_EventStream_aborted=new WeakMap,_EventStream_catchingPromiseCreated=new WeakMap,_EventStream_terminalFailure=new WeakMap,_EventStream_instances=new WeakSet,_EventStream_abortFromSignal=function(signal){try{this.controller.abort(signal.reason)}catch{this.controller.abort()}},_EventStream_removeAbortListeners=function(){for(let{signal,listener}of __classPrivateFieldGet(this,_EventStream_abortListeners,"f").splice(0))signal.removeEventListener("abort",listener)},_EventStream_onceForEmitted=function(event,listener){let previousListeners=__classPrivateFieldGet(this,_EventStream_listeners,"f")[event],previousLength=previousListeners?.length??0;this.once(event,listener);let listeners=__classPrivateFieldGet(this,_EventStream_listeners,"f")[event],[registration]=listeners?.slice(-1)??[];if((previousListeners===void 0||listeners===previousListeners)&&listeners?.length===previousLength+1&&registration?.listener===listener&&registration.once)__classPrivateFieldGet(this,_EventStream_emittedListenerRegistrations,"f").set(listener,{event,registration})},_EventStream_removeEmittedListener=function(event,registration){if(registration.removed)return;if(registration.removed=!0,__classPrivateFieldGet(this,_EventStream_emittedListenerRegistrations,"f").delete(registration.listener),__classPrivateFieldGet(this,_EventStream_pendingListenerCleanup,"f").add(event),__classPrivateFieldGet(this,_EventStream_listenerDispatchDepth,"f")===0)__classPrivateFieldGet(this,_EventStream_instances,"m",_EventStream_cleanupEmittedListeners).call(this)},_EventStream_cleanupEmittedListeners=function(){for(let event of __classPrivateFieldGet(this,_EventStream_pendingListenerCleanup,"f")){let eventType=event,listeners=__classPrivateFieldGet(this,_EventStream_listeners,"f")[eventType];if(listeners)__classPrivateFieldGet(this,_EventStream_listeners,"f")[eventType]=listeners.filter((listener)=>!listener.removed)}__classPrivateFieldGet(this,_EventStream_pendingListenerCleanup,"f").clear()},_EventStream_handleError=function(error){if(__classPrivateFieldSet(this,_EventStream_errored,!0,"f"),error instanceof Error&&error.name==="AbortError")error=this._userAbortError();if(error instanceof APIUserAbortError)return __classPrivateFieldSet(this,_EventStream_aborted,!0,"f"),this._emit("abort",error);if(error instanceof OpenAIError)return this._emit("error",error);if(error instanceof Error){let openAIError=new OpenAIError(error.message);return openAIError.cause=error,this._emit("error",openAIError)}return this._emit("error",new OpenAIError(String(error)))},_EventStream_settleTerminalEvent=function(event,args,hasListeners){if(event==="abort"){let error=args[0];if(__classPrivateFieldSet(this,_EventStream_terminalFailure,__classPrivateFieldGet(this,_EventStream_terminalFailure,"f")??{kind:"abort",error},"f"),!__classPrivateFieldGet(this,_EventStream_catchingPromiseCreated,"f")&&!hasListeners)Promise.reject(error);__classPrivateFieldGet(this,_EventStream_rejectConnectedPromise,"f").call(this,error),__classPrivateFieldGet(this,_EventStream_rejectEndPromise,"f").call(this,error),this._emit("end");return}if(event==="error"){let error=args[0];if(__classPrivateFieldSet(this,_EventStream_terminalFailure,__classPrivateFieldGet(this,_EventStream_terminalFailure,"f")??{kind:"error",error},"f"),!__classPrivateFieldGet(this,_EventStream_catchingPromiseCreated,"f")&&!hasListeners)Promise.reject(error);__classPrivateFieldGet(this,_EventStream_rejectConnectedPromise,"f").call(this,error),__classPrivateFieldGet(this,_EventStream_rejectEndPromise,"f").call(this,error),this._emit("end")}}});function isRunnableFunctionWithParse(fn){return typeof fn.parse==="function"}function normalizeToolCallIds(chatCompletion){for(let choice of chatCompletion.choices)for(let toolCall of choice.message.tool_calls??[])if(!toolCall.id)toolCall.id=`call_${uuid4()}`}function toRequestMessage(message){if(!isAssistantMessage(message))return message;let requestMessage={role:"assistant"};if(message.audio!=null)requestMessage.audio={id:message.audio.id};if(message.content!==void 0)requestMessage.content=message.content;if(message.function_call!=null)requestMessage.function_call=message.function_call;if(message.name!==void 0)requestMessage.name=message.name;if(message.refusal!=null)requestMessage.refusal=message.refusal;if(message.tool_calls!==void 0)requestMessage.tool_calls=message.tool_calls.map((toolCall)=>{if(toolCall.type==="custom")return{id:toolCall.id,type:toolCall.type,custom:{input:toolCall.custom.input,name:toolCall.custom.name}};return{id:toolCall.id,type:toolCall.type,function:{arguments:toolCall.function.arguments,name:toolCall.function.name}}});return requestMessage}var _AbstractChatCompletionRunner_instances,_a2,_AbstractChatCompletionRunner_completionArrivedBeforeAbort,_AbstractChatCompletionRunner_afterCompletionInvoked,_AbstractChatCompletionRunner_getFinalContent,_AbstractChatCompletionRunner_getFinalMessage,_AbstractChatCompletionRunner_getFinalFunctionToolCall,_AbstractChatCompletionRunner_getFinalFunctionToolCallResult,_AbstractChatCompletionRunner_calculateTotalUsage,_AbstractChatCompletionRunner_throwIfAborted,_AbstractChatCompletionRunner_validateParams,_AbstractChatCompletionRunner_stringifyFunctionCallResult,DEFAULT_MAX_CHAT_COMPLETIONS=10,AbstractChatCompletionRunner;var init_AbstractChatCompletionRunner=__esm(()=>{init_tslib();init_error2();init_values();init_parser();init_EventStream();AbstractChatCompletionRunner=class AbstractChatCompletionRunner extends EventStream{constructor(){super(...arguments);_AbstractChatCompletionRunner_instances.add(this),this._chatCompletions=[],_AbstractChatCompletionRunner_completionArrivedBeforeAbort.set(this,!1),_AbstractChatCompletionRunner_afterCompletionInvoked.set(this,!1),this.messages=[]}_addChatCompletion(chatCompletion){__classPrivateFieldSet(this,_AbstractChatCompletionRunner_completionArrivedBeforeAbort,!this.controller.signal.aborted,"f"),normalizeToolCallIds(chatCompletion),this._chatCompletions.push(chatCompletion),this._emit("chatCompletion",chatCompletion);let message=chatCompletion.choices[0]?.message;if(message)this._addMessage(message);return chatCompletion}_addMessage(message,emit=!0,normalizeContent=!0){if(normalizeContent&&!("content"in message))message.content=null;if(this.messages.push(message),emit){if(this._emit("message",message),isToolMessage(message)&&message.content)this._emit("functionToolCallResult",message.content);else if(isAssistantMessage(message)&&message.tool_calls){for(let tool_call of message.tool_calls)if(tool_call.type==="function")this._emit("functionToolCall",tool_call.function)}}}async finalChatCompletion(){await this.done();let completion=this._chatCompletions[this._chatCompletions.length-1];if(!completion)throw new OpenAIError("stream ended without producing a ChatCompletion");return completion}async finalContent(){return await this.done(),__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this)}async finalMessage(){return await this.done(),__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this)}async finalFunctionToolCall(){return await this.done(),__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this)}async finalFunctionToolCallResult(){return await this.done(),__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this)}async totalUsage(){return await this.done(),__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){if(__classPrivateFieldGet(this,_AbstractChatCompletionRunner_afterCompletionInvoked,"f"))__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_throwIfAborted).call(this);let completion=this._chatCompletions[this._chatCompletions.length-1];if(completion)this._emit("finalChatCompletion",completion);let finalMessage=__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this);if(finalMessage)this._emit("finalMessage",finalMessage);let finalContent=__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this);if(finalContent)this._emit("finalContent",finalContent);let finalFunctionCall=__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);if(finalFunctionCall)this._emit("finalFunctionToolCall",finalFunctionCall);let finalFunctionCallResult=__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);if(finalFunctionCallResult!=null)this._emit("finalFunctionToolCallResult",finalFunctionCallResult);if(this._chatCompletions.some((c)=>c.usage))this._emit("totalUsage",__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this))}async _createChatCompletion(client,params,options){this._listenForAbort(options?.signal),__classPrivateFieldGet(_a2,_a2,"m",_AbstractChatCompletionRunner_validateParams).call(_a2,params);let chatCompletion=await client.chat.completions.create({...params,stream:!1},{...options,signal:this.controller.signal});return this._connected(),this._addChatCompletion(parseChatCompletion(chatCompletion,params))}async _runChatCompletion(client,params,options){for(let message of params.messages)this._addMessage(message,!1,!1);return await this._createChatCompletion(client,params,options)}async _runTools(client,params,runner,options){let{tool_choice="auto",stream,toolContext:inputToolContext,...restParams}=params,toolContext=inputToolContext,singleFunctionToCall=typeof tool_choice!=="string"&&tool_choice.type==="function"&&tool_choice?.function?.name,{maxChatCompletions=DEFAULT_MAX_CHAT_COMPLETIONS,afterCompletion}=options||{},runAfterCompletion=async(completion)=>{if(afterCompletion==null)return;__classPrivateFieldSet(this,_AbstractChatCompletionRunner_afterCompletionInvoked,!0,"f"),await afterCompletion(completion,runner),__classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_throwIfAborted).call(this)},inputTools=params.tools.map((tool)=>{if(isAutoParsableTool(tool)){if(!tool.$callback)throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:tool.$callback,name:tool.function.name,description:tool.function.description||"",parameters:tool.function.parameters,parse:tool.$parseRaw,strict:!0}}}return tool}),functionsByName=Object.create(null);for(let f of inputTools)if(f.type==="function")functionsByName[f.function.name||f.function.function.name]=f.function;let tools="tools"in params?inputTools.map((t)=>t.type==="function"?{type:"function",function:{name:t.function.name||t.function.function.name,parameters:t.function.parameters,description:t.function.description,strict:t.function.strict}}:t):void 0;for(let message of params.messages)this._addMessage(message,!1,!1);let allowBufferedToolCall=!1,runToolCall=async(toolCall)=>{let bufferedToolCall=allowBufferedToolCall;if(allowBufferedToolCall=!1,toolCall.type!=="function")return{message:void 0,functionCalled:!1};let tool_call_id=toolCall.id,{name,arguments:args}=toolCall.function,fn=functionsByName[name];if(!fn){let content=`Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name)=>JSON.stringify(name)).join(", ")}. Please try again`;return{message:{role:"tool",tool_call_id,content},functionCalled:!1}}if(singleFunctionToCall&&singleFunctionToCall!==name){let content=`Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;return{message:{role:"tool",tool_call_id,content},functionCalled:!1}}let rawContent;if(isRunnableFunctionWithParse(fn)){let parsed;try{parsed=await fn.parse(args)}catch(error){if(this.controller.signal.aborted)throw this._userAbortError();let content=error instanceof Error?error.message:String(error);return{message:{role:"tool",tool_call_id,content},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{rawContent=await fn.function(parsed,runner,toolContext)}catch(error){if(this.controller.signal.aborted&&Object.is(error,this.controller.signal.reason))throw this._userAbortError();throw error}}else{if(this.controller.signal.aborted&&!bufferedToolCall)throw this._userAbortError();try{rawContent=await fn.function(args,runner,toolContext)}catch(error){if(this.controller.signal.aborted&&Object.is(error,this.controller.signal.reason))throw this._userAbortError();throw error}}let content=__classPrivateFieldGet(_a2,_a2,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(_a2,rawContent);return{message:{role:"tool",tool_call_id,content},functionCalled:!0}};for(let i=0;i<maxChatCompletions;++i){let chatCompletion=await this._createChatCompletion(client,{...restParams,tool_choice,tools,messages:this.messages.map(toRequestMessage)},options);allowBufferedToolCall=this.controller.signal.aborted&&__classPrivateFieldGet(this,_AbstractChatCompletionRunner_completionArrivedBeforeAbort,"f");let message=chatCompletion.choices[0]?.message;if(!message)throw new OpenAIError("missing message in ChatCompletion response");if(!message.tool_calls?.length){await runAfterCompletion(chatCompletion);return}if(singleFunctionToCall||params.parallel_tool_calls===!1)for(let toolCall of message.tool_calls){let result=await runToolCall(toolCall);if(result.message)this._addMessage(result.message);if(this.controller.signal.aborted)throw this._userAbortError();if(singleFunctionToCall&&result.functionCalled){await runAfterCompletion(chatCompletion);return}}else{let results=await Promise.allSettled(message.tool_calls.map(runToolCall));if(!this.controller.signal.aborted){for(let result of results)if(result.status==="rejected")throw result.reason}for(let result of results)if(result.status==="fulfilled"&&result.value.message)this._addMessage(result.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await runAfterCompletion(chatCompletion)}}};_a2=AbstractChatCompletionRunner,_AbstractChatCompletionRunner_completionArrivedBeforeAbort=new WeakMap,_AbstractChatCompletionRunner_afterCompletionInvoked=new WeakMap,_AbstractChatCompletionRunner_instances=new WeakSet,_AbstractChatCompletionRunner_getFinalContent=function(){return __classPrivateFieldGet(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this).content??null},_AbstractChatCompletionRunner_getFinalMessage=function(){let i=this.messages.length;while(i-- >0){let message=this.messages[i];if(isAssistantMessage(message))return{...message,content:message.content??null,refusal:message.refusal??null}}throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant")},_AbstractChatCompletionRunner_getFinalFunctionToolCall=function(){for(let i=this.messages.length-1;i>=0;i--){let message=this.messages[i];if(isAssistantMessage(message)&&message?.tool_calls?.length)for(let j=message.tool_calls.length-1;j>=0;j--){let toolCall=message.tool_calls[j];if(toolCall?.type==="function")return toolCall.function}}return},_AbstractChatCompletionRunner_getFinalFunctionToolCallResult=function(){for(let i=this.messages.length-1;i>=0;i--){let message=this.messages[i];if(isToolMessage(message)&&message.content!=null&&typeof message.content==="string"&&this.messages.some((x)=>x.role==="assistant"&&x.tool_calls?.some((y)=>y.type==="function"&&y.id===message.tool_call_id)))return message.content}return},_AbstractChatCompletionRunner_calculateTotalUsage=function(){let total={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage}of this._chatCompletions)if(usage){total.completion_tokens+=usage.completion_tokens,total.prompt_tokens+=usage.prompt_tokens,total.total_tokens+=usage.total_tokens;for(let key of["completion_tokens_details","prompt_tokens_details"]){let details=usage[key];if(isObj(details)){let totalDetails=total[key]??(total[key]={});for(let name in details){if(!hasOwn(details,name))continue;let count=details[name];if(typeof count==="number")Object.defineProperty(totalDetails,name,{value:(hasOwn(totalDetails,name)?totalDetails[name]??0:0)+count,enumerable:!0,configurable:!0,writable:!0})}}}}return total},_AbstractChatCompletionRunner_throwIfAborted=function(){if(this.controller.signal.aborted)throw this._userAbortError()},_AbstractChatCompletionRunner_validateParams=function(params){if(params.n!=null&&params.n>1)throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_AbstractChatCompletionRunner_stringifyFunctionCallResult=function(rawContent){if(typeof rawContent==="string")return rawContent;if(rawContent===void 0)return"undefined";return JSON.stringify(rawContent)}});var ChatCompletionRunner;var init_ChatCompletionRunner=__esm(()=>{init_AbstractChatCompletionRunner();ChatCompletionRunner=class ChatCompletionRunner extends AbstractChatCompletionRunner{static runTools(client,params,options){let runner=new ChatCompletionRunner,opts={...options,__metadata:{...options?.__metadata,helperMethod:"runTools"}};return runner._run(()=>runner._runTools(client,params,runner,opts)),runner}_addMessage(message,emit=!0,normalizeContent=!0){if(super._addMessage(message,emit,normalizeContent),emit&&isAssistantMessage(message)&&message.content)this._emit("content",message.content)}}});function parseJSON(jsonString,allowPartial=Allow.ALL){if(typeof jsonString!=="string")throw TypeError(`expecting str, got ${typeof jsonString}`);if(!jsonString.trim())throw Error(`${jsonString} is empty`);return _parseJSON(jsonString.trim(),allowPartial)}var Allow,PartialJSON,MalformedJSON,_parseJSON=(jsonString,allow)=>{let length=jsonString.length,index=0,markPartialJSON=(msg)=>{throw new PartialJSON(`${msg} at position ${index}`)},throwMalformedError=(msg)=>{throw new MalformedJSON(`${msg} at position ${index}`)},parseAny=()=>{if(skipBlank(),index>=length)markPartialJSON("Unexpected end of input");if(jsonString[index]==='"')return parseStr();if(jsonString[index]==="{")return parseObj();if(jsonString[index]==="[")return parseArr();if(jsonString.substring(index,index+4)==="null"||Allow.NULL&allow&&length-index<4&&"null".startsWith(jsonString.substring(index)))return index+=4,null;if(jsonString.substring(index,index+4)==="true"||Allow.BOOL&allow&&length-index<4&&"true".startsWith(jsonString.substring(index)))return index+=4,!0;if(jsonString.substring(index,index+5)==="false"||Allow.BOOL&allow&&length-index<5&&"false".startsWith(jsonString.substring(index)))return index+=5,!1;if(jsonString.substring(index,index+8)==="Infinity"||Allow.INFINITY&allow&&length-index<8&&"Infinity".startsWith(jsonString.substring(index)))return index+=8,1/0;if(jsonString.substring(index,index+9)==="-Infinity"||Allow.MINUS_INFINITY&allow&&length-index>1&&length-index<9&&"-Infinity".startsWith(jsonString.substring(index)))return index+=9,-1/0;if(jsonString.substring(index,index+3)==="NaN"||Allow.NAN&allow&&length-index<3&&"NaN".startsWith(jsonString.substring(index)))return index+=3,Number.NaN;return parseNum()},parseStr=()=>{let start=index,escape2=!1;index++;while(index<length&&(jsonString[index]!=='"'||escape2&&jsonString[index-1]==="\\"))escape2=jsonString[index]==="\\"?!escape2:!1,index++;if(jsonString.charAt(index)==='"')try{return JSON.parse(jsonString.substring(start,++index-Number(escape2)))}catch(e){throwMalformedError(String(e))}else if(Allow.STR&allow)try{return JSON.parse(jsonString.substring(start,index-Number(escape2))+'"')}catch{return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("\\"))+'"')}markPartialJSON("Unterminated string literal")},parseObj=()=>{index++,skipBlank();let obj={};try{while(jsonString[index]!=="}"){if(skipBlank(),index>=length&&Allow.OBJ&allow)return obj;let key=parseStr();skipBlank(),index++;try{let value=parseAny();Object.defineProperty(obj,key,{value,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Allow.OBJ&allow)return obj;throw e}if(skipBlank(),jsonString[index]===",")index++}}catch{if(Allow.OBJ&allow)return obj;markPartialJSON("Expected '}' at end of object")}return index++,obj},parseArr=()=>{index++;let arr=[];try{while(jsonString[index]!=="]")if(arr.push(parseAny()),skipBlank(),jsonString[index]===",")index++}catch{if(Allow.ARR&allow)return arr;markPartialJSON("Expected ']' at end of array")}return index++,arr},parseNum=()=>{if(index===0){if(jsonString==="-"&&Allow.NUM&allow)markPartialJSON("Not sure what '-' is");try{return JSON.parse(jsonString)}catch(e){if(Allow.NUM&allow)try{if(jsonString[jsonString.length-1]===".")return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf(".")));return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf("e")))}catch{}throwMalformedError(String(e))}}let start=index;if(jsonString[index]==="-")index++;while(jsonString[index]&&!",]}".includes(jsonString[index]))index++;if(index===length&&!(Allow.NUM&allow))markPartialJSON("Unterminated number literal");let number=jsonString.substring(start,index);try{return JSON.parse(number)}catch{if(number==="-"&&Allow.NUM&allow)markPartialJSON("Not sure what '-' is");try{return JSON.parse(number.substring(0,number.lastIndexOf("e")))}catch(e){throwMalformedError(String(e))}}},skipBlank=()=>{while(index<length&&`
20
+ \r `.includes(jsonString[index]))index++};return parseAny()},partialParse=(input)=>parseJSON(input,Allow.ALL^Allow.NUM);var init_parser2=__esm(()=>{Allow={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};PartialJSON=class PartialJSON extends Error{};MalformedJSON=class MalformedJSON extends Error{}});var init_streaming2=__esm(()=>{init_streaming()});function normalizeChatCompletionChunk(chunk){if(!Array.isArray(chunk?.choices))return chunk;return{...chunk,choices:chunk.choices.map((choice)=>({...choice,finish_reason:choice.finish_reason??null}))}}function normalizeChatCompletionStream(stream){let iterator=stream[Symbol.asyncIterator].bind(stream);return stream[Symbol.asyncIterator]=async function*(){let source={[Symbol.asyncIterator]:iterator};for await(let chunk of source)yield normalizeChatCompletionChunk(chunk)},stream}function parseStructuredStreamingJSON(content){try{return partialParse(content)}catch(error){if(error instanceof MalformedJSON||error instanceof SyntaxError)return parseResponseFormatContent({type:"json_schema",$parseRaw:void 0},content);throw error}}function makeChatCompletionReadableStreamMessageChunk(chunk,message,toolCallIds){let payload={type:"message",message,...toolCallIds?{tool_call_ids:toolCallIds}:{}};return{id:chunk.id,choices:[],created:chunk.created,model:chunk.model,object:`${CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX}${JSON.stringify(payload)}`}}function isChatCompletionReadableStreamMessage(item){return"type"in item&&item.type==="message"&&"message"in item||"object"in item&&typeof item.object==="string"&&item.object.startsWith(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX)}function getChatCompletionReadableStreamMessage(item){if("type"in item)return item;return JSON.parse(item.object.slice(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX.length))}function createPartialJSONParseState(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function recordPartialJSONFragment(state,budget,fragment,validationWorkBudget){if(budget.fragments>=MAX_PARTIAL_JSON_FRAGMENTS)throw new OpenAIError("Chat completion stream exceeded its structured JSON fragment limit");let bytes=0,{depth,escaped,has_non_whitespace:hasNonWhitespace,in_string:inString}=state,completed=!1,firstCharacter=!0;for(let character of fragment){let previousBytes=bytes,codePoint=character.codePointAt(0);if(firstCharacter&&state.pending_high_surrogate&&codePoint>=56320&&codePoint<=57343)bytes+=1;else if(codePoint<=127)bytes+=1;else if(codePoint<=2047)bytes+=2;else if(codePoint<=65535)bytes+=3;else bytes+=4;if(firstCharacter=!1,budget.bytes+bytes>MAX_PARTIAL_JSON_BYTES)throw new OpenAIError("Chat completion stream exceeded its structured JSON byte limit");if(validationWorkBudget&&validationWorkBudget.work+bytes>MAX_PARTIAL_JSON_PARSE_WORK)throw validationWorkBudget.work+=previousBytes,new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");if(character!==" "&&character!==`
21
+ `&&character!=="\r"&&character!=="\t")hasNonWhitespace=!0;if(inString){if(escaped)escaped=!1;else if(character==="\\")escaped=!0;else if(character==='"')inString=!1,completed||(completed=depth===0);continue}if(character==='"')inString=!0;else if(character==="{"||character==="["){if(depth+=1,depth>MAX_PARTIAL_JSON_DEPTH)throw new OpenAIError("Chat completion stream exceeded its structured JSON nesting depth limit")}else if((character==="}"||character==="]")&&depth>0)depth-=1,completed||(completed=depth===0)}if(state.bytes+=bytes,state.fragments+=1,state.depth=depth,state.escaped=escaped,state.has_non_whitespace=hasNonWhitespace,state.in_string=inString,fragment.length>0){let finalCodeUnit=fragment.codePointAt(fragment.length-1)??0;state.pending_high_surrogate=finalCodeUnit>=55296&&finalCodeUnit<=56319}if(budget.bytes+=bytes,budget.fragments+=1,validationWorkBudget)validationWorkBudget.work+=bytes;if(!hasNonWhitespace||bytes===0)return!1;let minimumGrowth=Math.max(EAGER_PARTIAL_JSON_BYTES,Math.floor(state.last_parsed_bytes/2));if(state.bytes>EAGER_PARTIAL_JSON_BYTES&&!completed&&state.bytes-state.last_parsed_bytes<minimumGrowth)return!1;return!0}function reservePartialJSONParse(state,budget){if(budget.work+state.bytes>MAX_PARTIAL_JSON_PARSE_WORK)return!1;return budget.work+=state.bytes,state.work+=state.bytes,state.last_parsed_bytes=state.bytes,!0}function captureStructuredJSONSnapshot(snapshot,property){let descriptor=Object.getOwnPropertyDescriptor(snapshot,property);if(!descriptor){let prototype=Object.getPrototypeOf(snapshot);for(let depth=0;prototype!==null;depth+=1){if(depth>=MAX_PARTIAL_JSON_DEPTH||Object.getOwnPropertyDescriptor(prototype,property))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");prototype=Object.getPrototypeOf(prototype)}return}if(!("value"in descriptor)||typeof descriptor.value!=="string"&&descriptor.value!==null&&descriptor.value!==void 0)throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");return descriptor.value}function captureStructuredMessageSnapshot(choice){let descriptor=Object.getOwnPropertyDescriptor(choice,"message");if(!descriptor||!("value"in descriptor)||typeof descriptor.value!=="object"||descriptor.value===null)throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");return descriptor.value}function captureSnapshotArray(snapshot,property,maximum,kind){let descriptor=Object.getOwnPropertyDescriptor(snapshot,property);if(!descriptor){let prototype=Object.getPrototypeOf(snapshot);for(let depth=0;prototype!==null;depth+=1){if(depth>=MAX_PARTIAL_JSON_DEPTH||Object.getOwnPropertyDescriptor(prototype,property))throw new OpenAIError(`Chat completion stream contains an unsafe snapshot ${kind} collection`);prototype=Object.getPrototypeOf(prototype)}return}if(!("value"in descriptor)||!Array.isArray(descriptor.value))throw new OpenAIError(`Chat completion stream contains an unsafe snapshot ${kind} collection`);let length=Object.getOwnPropertyDescriptor(descriptor.value,"length");if(!length||!("value"in length)||!Number.isSafeInteger(length.value)||length.value>maximum)throw new OpenAIError(`Chat completion stream exceeded its snapshot ${kind} limit`);return descriptor.value}function captureSnapshotArrayItem(array,index){let descriptor=Object.getOwnPropertyDescriptor(array,index);if(!descriptor)return;if(!("value"in descriptor))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");return descriptor.value}function mapCapturedSnapshotArray(array,maximum,kind,map){let descriptor=Object.getOwnPropertyDescriptor(array,"length"),length=descriptor&&"value"in descriptor?descriptor.value:void 0;if(typeof length!=="number"||!Number.isSafeInteger(length)||length<0||length>maximum)throw new OpenAIError(`Chat completion stream exceeded its snapshot ${kind} limit`);let mapped=[];mapped.length=length;for(let index=0;index<length;index+=1){let item=Object.getOwnPropertyDescriptor(array,index);if(!item)continue;if(!("value"in item))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");mapped[index]=map(item.value,index)}return mapped}function validateStructuredJSONSnapshot(value,budget,validationWorkBudget){let state=createPartialJSONParseState(),parseBudget=budget??{bytes:0,fragments:0,work:0};if(recordPartialJSONFragment(state,parseBudget,value,validationWorkBudget),!reservePartialJSONParse(state,parseBudget))throw new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");return value}function ownFunctionToolIdentity(toolCall){let type=Object.getOwnPropertyDescriptor(toolCall,"type"),fn=Object.getOwnPropertyDescriptor(toolCall,"function");if(!type||!("value"in type)||type.value!=="function"||!fn||!("value"in fn))return;if(typeof fn.value!=="object"||fn.value===null)return;let name=Object.getOwnPropertyDescriptor(fn.value,"name");if(!name||!("value"in name)||typeof name.value!=="string"||name.value.length===0)return;return{type:"function",name:name.value}}function assertBoundToolCallIdentity(toolCall,identity){let current=ownFunctionToolIdentity(toolCall);if(!current||current.name!==identity.name||current.type!==identity.type)throw new OpenAIError("Chat completion stream contains a changed tool call identity")}function assignOwnProperties(target,source){if(Object.prototype.propertyIsEnumerable.call(source,"__proto__")&&!hasOwn(target,"__proto__"))Object.defineProperty(target,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0});return Object.assign(target,source)}function cloneParserConfigObject(value,stableFields=[]){let descriptors=Object.getOwnPropertyDescriptors(value);for(let field of stableFields){let descriptor=descriptors[field];if(!descriptor&&!(field in value))continue;descriptors[field]={value:descriptor&&"value"in descriptor?descriptor.value:Reflect.get(value,field,value),enumerable:descriptor?.enumerable??!1,configurable:descriptor?.configurable??!0,writable:descriptor&&"writable"in descriptor?descriptor.writable:!1}}return Object.create(Object.getPrototypeOf(value),descriptors)}function snapshotChatCompletionParserParams(params){let snapshot=cloneParserConfigObject(params);if(params.tools){let stableTools=[],lengthDescriptor=Object.getOwnPropertyDescriptor(params.tools,"length"),length=lengthDescriptor&&"value"in lengthDescriptor?lengthDescriptor.value:void 0,toolCount=typeof length==="number"&&Number.isSafeInteger(length)&&length>=0?Math.min(length,MAX_STREAM_TOOL_CALLS):0;for(let index=0;index<toolCount;index+=1){let item=Object.getOwnPropertyDescriptor(params.tools,String(index));if(!item||!("value"in item)){stableTools.length=index+1;continue}let tool=item.value,stableTool=cloneParserConfigObject(tool,["type","$brand","$parseRaw","$callback","function"]),descriptors=Object.getOwnPropertyDescriptors(stableTool);if(isChatCompletionFunctionTool(stableTool)){let descriptor=descriptors.function;descriptors.function={...descriptor&&"value"in descriptor?descriptor:{configurable:!0,enumerable:!0,writable:!0},value:cloneParserConfigObject(stableTool.function,["name","strict"])}}stableTools[index]=Object.create(Object.getPrototypeOf(tool),descriptors)}snapshot.tools=stableTools}if(params.response_format)snapshot.response_format=cloneParserConfigObject(params.response_format,["type","$brand","$parseRaw"]);return snapshot}function canonicalSerializedParserSchema(value,budget){let ancestors=new WeakSet,charge=(bytes)=>{if(!Number.isSafeInteger(bytes)||bytes<0||budget.bytes+bytes>MAX_SERIALIZED_PARSER_SCHEMA_BYTES)return!1;return budget.bytes+=bytes,!0},visit=(current,depth)=>{if(depth>MAX_SERIALIZED_PARSER_SCHEMA_DEPTH||budget.nodes>=MAX_SERIALIZED_PARSER_SCHEMA_NODES)return UNSAFE_SERIALIZED_PARSER_VALUE;if(budget.nodes+=1,current===void 0||typeof current==="function"||typeof current==="symbol")return OMITTED_SERIALIZED_PARSER_VALUE;if(typeof current==="bigint")return UNSAFE_SERIALIZED_PARSER_VALUE;if(current===null||typeof current==="boolean"||typeof current==="number"){let serialized=stringifyParserSchemaValue(current);return typeof serialized==="string"&&charge(serialized.length)?serialized:UNSAFE_SERIALIZED_PARSER_VALUE}if(typeof current==="string"){if(!charge(current.length*6+2))return UNSAFE_SERIALIZED_PARSER_VALUE;return stringifyParserSchemaValue(current)}if(typeof current!=="object"||ancestors.has(current))return UNSAFE_SERIALIZED_PARSER_VALUE;let array=Array.isArray(current),prototype=Object.getPrototypeOf(current);if(array&&prototype!==Array.prototype||!array&&prototype!==null&&prototype!==Object.prototype)return UNSAFE_SERIALIZED_PARSER_VALUE;for(let owner=current;owner!==null;owner=Object.getPrototypeOf(owner)){let serializer=Object.getOwnPropertyDescriptor(owner,"toJSON");if(!serializer)continue;if(!("value"in serializer)||typeof serializer.value==="function")return UNSAFE_SERIALIZED_PARSER_VALUE;break}ancestors.add(current);try{if(!charge(2))return UNSAFE_SERIALIZED_PARSER_VALUE;if(array){let lengthDescriptor=Object.getOwnPropertyDescriptor(current,"length"),length=lengthDescriptor&&"value"in lengthDescriptor?lengthDescriptor.value:void 0;if(typeof length!=="number"||!Number.isSafeInteger(length)||length<0||length>MAX_SERIALIZED_PARSER_SCHEMA_NODES-budget.nodes)return UNSAFE_SERIALIZED_PARSER_VALUE;let items=[];for(let index=0;index<length;index+=1){let key=String(index),descriptor=Object.getOwnPropertyDescriptor(current,key);if(!descriptor){if(Object.getOwnPropertyDescriptor(Array.prototype,key)||Object.getOwnPropertyDescriptor(Object.prototype,key))return UNSAFE_SERIALIZED_PARSER_VALUE;if(budget.nodes+=1,!charge(4))return UNSAFE_SERIALIZED_PARSER_VALUE;items.push("null");continue}if(!("value"in descriptor))return UNSAFE_SERIALIZED_PARSER_VALUE;let item=visit(descriptor.value,depth+1);if(item===UNSAFE_SERIALIZED_PARSER_VALUE)return item;items.push(item===OMITTED_SERIALIZED_PARSER_VALUE?"null":item)}return`[${items.join(",")}]`}let keys=Reflect.ownKeys(current);if(keys.length>MAX_SERIALIZED_PARSER_SCHEMA_NODES-budget.nodes)return UNSAFE_SERIALIZED_PARSER_VALUE;let entries=[];for(let key of keys){if(typeof key!=="string")continue;let descriptor=Object.getOwnPropertyDescriptor(current,key);if(!descriptor)return UNSAFE_SERIALIZED_PARSER_VALUE;if(!descriptor.enumerable)continue;if(!("value"in descriptor))return UNSAFE_SERIALIZED_PARSER_VALUE;entries.push([key,descriptor.value])}entries.sort(([left],[right])=>{if(left===right)return 0;return left<right?-1:1});let fields=[];for(let[key,entry]of entries){let normalized=visit(entry,depth+1);if(normalized===UNSAFE_SERIALIZED_PARSER_VALUE)return normalized;if(normalized===OMITTED_SERIALIZED_PARSER_VALUE)continue;if(!charge(key.length*6+3))return UNSAFE_SERIALIZED_PARSER_VALUE;fields.push(`${stringifyParserSchemaValue(key)}:${normalized}`)}return`{${fields.join(",")}}`}finally{ancestors.delete(current)}};try{let normalized=visit(value,0);return typeof normalized==="string"?normalized:void 0}catch{return}}function rememberSerializedParserSchema(signatures,source,holder,key){let parser=Object.getOwnPropertyDescriptor(source,"$parseRaw"),schema=Object.getOwnPropertyDescriptor(holder,key);if(!parser||!("value"in parser)||typeof parser.value!=="function"||!schema||!("value"in schema))return;let normalized=canonicalSerializedParserSchema(schema.value,{nodes:0,bytes:0});if(normalized!==void 0)signatures.set(source,normalized)}function hasMatchingSerializedParserSchema(signatures,source,holder,key,value){let expected=source&&signatures.get(source),descriptor=Object.getOwnPropertyDescriptor(holder,key);return expected!==void 0&&descriptor!==void 0&&"value"in descriptor&&canonicalSerializedParserSchema(value,{nodes:0,bytes:0})===expected}function serializedParserDescriptor(descriptor,value){return descriptor&&"value"in descriptor?{...descriptor,value}:{configurable:!0,enumerable:!0,writable:!0,value}}function shadowSerializedParserMetadata(descriptors,source,fields){for(let field of fields){let descriptor=descriptors[field];if(!descriptor&&!(field in source))continue;descriptors[field]=descriptor&&"value"in descriptor?{...descriptor,value:void 0}:{configurable:descriptor?.configurable??!0,enumerable:descriptor?.enumerable??!1,writable:!1,value:void 0}}}function snapshotSerializedParserTool(serialized){let source=serialized.source??{type:serialized.type,...serialized.type==="function"?{function:{}}:{}},descriptors=Object.getOwnPropertyDescriptors(source);if(descriptors.type=serializedParserDescriptor(descriptors.type,serialized.type),serialized.type!=="function"||!serialized.function){if(descriptors.function)descriptors.function=serializedParserDescriptor(descriptors.function,void 0);return shadowSerializedParserMetadata(descriptors,source,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(source),descriptors)}let descriptor=descriptors.function,original=descriptor&&"value"in descriptor&&typeof descriptor.value==="object"&&descriptor.value!==null?descriptor.value:{},functionDescriptors=Object.getOwnPropertyDescriptors(original);if(functionDescriptors.name=serializedParserDescriptor(functionDescriptors.name,serialized.function.name),functionDescriptors.strict=serializedParserDescriptor(functionDescriptors.strict,serialized.function.strict),descriptors.function=serializedParserDescriptor(descriptor,Object.create(Object.getPrototypeOf(original),functionDescriptors)),!serialized.function.schemaMatches)shadowSerializedParserMetadata(descriptors,source,["$brand","$parseRaw","$callback"]);return Object.create(Object.getPrototypeOf(source),descriptors)}function snapshotSerializedResponseFormat(serialized){let source=serialized.source??{type:serialized.type},descriptors=Object.getOwnPropertyDescriptors(source);if(descriptors.type=serializedParserDescriptor(descriptors.type,serialized.type),serialized.type!=="json_schema"||!serialized.source||!serialized.schemaMatches)shadowSerializedParserMetadata(descriptors,source,["$brand","$parseRaw"]);return Object.create(Object.getPrototypeOf(source),descriptors)}function ownSerializedParserObject(holder,key){let descriptor=Object.getOwnPropertyDescriptor(holder,key);if(!descriptor||!("value"in descriptor))return;let{value}=descriptor;return typeof value==="object"&&value!==null?value:void 0}function observeSerializedChatCompletionParserParams(body,initial,update){let originalToolOwners=new WeakMap,originalSchemaSignatures=new WeakMap;if(body.tools)for(let index=0;index<body.tools.length&&index<MAX_STREAM_TOOL_CALLS;index+=1){let owner=ownSerializedParserObject(body.tools,String(index)),source=initial.tools?.[index];if(owner&&source){originalToolOwners.set(owner,source);let originalFunction=ownSerializedParserObject(source,"function");if(originalFunction)rememberSerializedParserSchema(originalSchemaSignatures,source,originalFunction,"parameters")}}if(initial.response_format)rememberSerializedParserSchema(originalSchemaSignatures,initial.response_format,initial.response_format,"json_schema");let root,tools,responseFormat,responseFrame,frames=[],toolFrames=new WeakMap,actualToolOwners=new Map,functionFrames=new WeakMap;return observeJSONRequestBody(body,{value(holder,key,value){if(!root&&key===""&&typeof value==="object"&&value!==null){root=value,tools=void 0,responseFormat=void 0,responseFrame=void 0,frames=[],toolFrames=new WeakMap,actualToolOwners=new Map,functionFrames=new WeakMap;return}if(holder===root&&key==="response_format"){if(typeof value==="object"&&value!==null)responseFormat=value,responseFrame={source:ownSerializedParserObject(holder,key)===body.response_format?initial.response_format:void 0,schemaMatches:!1};return}if(holder===root&&key==="tools"){if(Array.isArray(value))return tools=new Proxy(value,{get(target,property){let actual=Reflect.get(target,property,target);if(typeof property==="string"){let index=Number(property);if(Number.isSafeInteger(index)&&index>=0&&index<MAX_STREAM_TOOL_CALLS&&String(index)===property)actualToolOwners.set(index,typeof actual==="object"&&actual!==null?actual:void 0)}return actual}}),tools;return}if(holder===tools){let index=Number(key);if(!Number.isSafeInteger(index)||index<0||index>=MAX_STREAM_TOOL_CALLS||typeof value!=="object"||value===null)return;let owner=actualToolOwners.get(index),frame={source:owner?originalToolOwners.get(owner):void 0};frames[index]=frame,toolFrames.set(value,frame);return}let tool=toolFrames.get(holder);if(tool){if(key==="type"&&typeof value==="string")tool.type=value;else if(key==="function"&&typeof value==="object"&&value!==null){let fn={source:tool.source,schemaMatches:!1};tool.function=fn,functionFrames.set(value,fn)}return}if(holder===responseFormat&&responseFrame){if(key==="type"&&typeof value==="string")responseFrame.type=value;else if(key==="json_schema")responseFrame.schemaMatches=hasMatchingSerializedParserSchema(originalSchemaSignatures,responseFrame.source,holder,key,value);return}let fn=functionFrames.get(holder);if(fn){if(key==="name"&&typeof value==="string")fn.name=value;else if(key==="strict"&&typeof value==="boolean")fn.strict=value;else if(key==="parameters")fn.schemaMatches=hasMatchingSerializedParserSchema(originalSchemaSignatures,fn.source,holder,key,value)}return},complete(){if(!root)return;let snapshot=cloneParserConfigObject(initial);if(tools){let serializedTools=[];for(let index=0;index<frames.length;index+=1){let frame=frames[index];if(frame)serializedTools[index]=snapshotSerializedParserTool(frame)}snapshot.tools=serializedTools}else delete snapshot.tools;if(responseFrame)snapshot.response_format=snapshotSerializedResponseFormat(responseFrame);else delete snapshot.response_format;update(snapshot),root=void 0,tools=void 0,responseFormat=void 0,responseFrame=void 0,frames=[],toolFrames=new WeakMap,actualToolOwners=new Map,functionFrames=new WeakMap}})}function finalizeChatCompletion(snapshot,params,audioDoneChoiceIndexes,validatedMessages){let{id,choices,created,model,system_fingerprint,...rest}=snapshot,completion={...rest,id,choices:mapCapturedSnapshotArray(choices,MAX_STREAM_CHOICES,"choice",(choice)=>{let validated=validatedMessages.get(choice);if(!validated)throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");let stableChoice=new Proxy(choice,{get(target,property,receiver){return property==="message"?validated.message:Reflect.get(target,property,receiver)}}),{message:sourceMessage,finish_reason,index,logprobs,...choiceRest}=stableChoice,message=new Proxy(sourceMessage,{get(target,property,receiver){if(property==="content")return validated.content;if(property==="refusal")return validated.refusal;if(property==="tool_calls")return validated.toolCallCollection;return Reflect.get(target,property,receiver)}}),{content=null,function_call,tool_calls,audio,...messageRest}=message,finishReason=finish_reason??(audioDoneChoiceIndexes.has(index)&&isCompleteAudio(audio)?"stop":null);if(!finishReason)throw new OpenAIError(`missing finish_reason for choice ${index}`);let audioResponse=audio?{audio}:{},role=message.role;if(!role)throw new OpenAIError(`missing role for choice ${index}`);if(function_call){let{arguments:args,name}=function_call;if(args==null)throw new OpenAIError(`missing function_call.arguments for choice ${index}`);if(!name)throw new OpenAIError(`missing function_call.name for choice ${index}`);return{...choiceRest,message:{...audioResponse,content,function_call:{arguments:args,name},role,refusal:message.refusal??null},finish_reason:finishReason,index,logprobs}}if(tool_calls)return{...choiceRest,index,finish_reason:finishReason,logprobs,message:{...messageRest,...audioResponse,role,content,refusal:message.refusal??null,tool_calls:mapCapturedSnapshotArray(tool_calls,MAX_STREAM_TOOL_CALLS,"tool-call",(tool_call,i)=>{let captured=validated.toolCalls.get(i);if(!captured){let identity=ownFunctionToolIdentity(tool_call);if(identity&&shouldParseToolCall(params,{type:identity.type,function:{name:identity.name}}))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot")}if(captured&&captured.tool!==tool_call)throw new OpenAIError("Chat completion stream contains a changed tool call identity");let stableFunction=captured&&new Proxy(captured.function,{get(target,property,receiver){if(property==="arguments")return captured.arguments;if(property==="name")return captured.name;return Reflect.get(target,property,receiver)}}),stableTool=captured&&stableFunction?new Proxy(tool_call,{get(target,property,receiver){if(property==="type")return captured.type;if(property==="function")return stableFunction;return Reflect.get(target,property,receiver)}}):tool_call;if(stableTool.type==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type`);if(stableTool.type==="custom"){let{custom,type,id,...toolRest}=stableTool,{input="",name,...customRest}=custom||{};if(name==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].custom.name`);return{...toolRest,id:id||`call_${uuid4()}`,type,custom:{...customRest,name,input}}}let{function:fn,type,id,...toolRest}=stableTool,{arguments:args,name,...fnRest}=fn||{};if(name==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name`);if(args==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments`);return{...toolRest,id:id||`call_${uuid4()}`,type,function:{...fnRest,name,arguments:args}}})}};return{...choiceRest,message:{...messageRest,...audioResponse,content,role,refusal:message.refusal??null},finish_reason:finishReason,index,logprobs}}),created,model,object:"chat.completion",...system_fingerprint?{system_fingerprint}:{}};return maybeParseChatCompletion(completion,params)}function isCompleteAudio(audio){return audio?.id!=null&&audio.data!=null&&audio.transcript!=null&&audio.expires_at!=null}function assertIsEmpty(obj){}function assertNever(_x){return _x}var _ChatCompletionStream_instances,_ChatCompletionStream_params,_ChatCompletionStream_rejectsUnfinishedTurns,_ChatCompletionStream_audioDoneChoiceIndexes,_ChatCompletionStream_choiceEventStates,_ChatCompletionStream_currentChatCompletionSnapshot,_ChatCompletionStream_hasAutoParseableTool,_ChatCompletionStream_partialJSONParseBudget,_ChatCompletionStream_beginRequest,_ChatCompletionStream_getChoiceEventState,_ChatCompletionStream_addChunk,_ChatCompletionStream_emitToolCallDoneEvent,_ChatCompletionStream_emitContentDoneEvents,_ChatCompletionStream_validateStructuredSnapshots,_ChatCompletionStream_endRequest,_ChatCompletionStream_accumulateChatCompletion,CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX="chat.completion.chunk.message:",MAX_STREAM_CHOICES=128,MAX_STREAM_TOOL_CALLS=128,MAX_PARTIAL_JSON_BYTES=16777216,MAX_PARTIAL_JSON_FRAGMENTS=65536,MAX_PARTIAL_JSON_DEPTH=128,MAX_PARTIAL_JSON_PARSE_WORK=67108864,EAGER_PARTIAL_JSON_BYTES=1024,MAX_SERIALIZED_PARSER_SCHEMA_NODES=4096,stringifyParserSchemaValue,MAX_SERIALIZED_PARSER_SCHEMA_BYTES=1048576,MAX_SERIALIZED_PARSER_SCHEMA_DEPTH=64,OMITTED_SERIALIZED_PARSER_VALUE,UNSAFE_SERIALIZED_PARSER_VALUE,ChatCompletionStream;var init_ChatCompletionStream=__esm(()=>{init_tslib();init_parser2();init_error2();init_request_options();init_values();init_parser();init_streaming2();init_AbstractChatCompletionRunner();stringifyParserSchemaValue=JSON.stringify,OMITTED_SERIALIZED_PARSER_VALUE=Symbol("omitted serialized parser value"),UNSAFE_SERIALIZED_PARSER_VALUE=Symbol("unsafe serialized parser value");ChatCompletionStream=class ChatCompletionStream extends AbstractChatCompletionRunner{constructor(params){super();_ChatCompletionStream_instances.add(this),_ChatCompletionStream_params.set(this,void 0),_ChatCompletionStream_rejectsUnfinishedTurns.set(this,!1),_ChatCompletionStream_audioDoneChoiceIndexes.set(this,void 0),_ChatCompletionStream_choiceEventStates.set(this,void 0),_ChatCompletionStream_currentChatCompletionSnapshot.set(this,void 0),_ChatCompletionStream_hasAutoParseableTool.set(this,void 0),_ChatCompletionStream_partialJSONParseBudget.set(this,void 0),__classPrivateFieldSet(this,_ChatCompletionStream_params,params,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_audioDoneChoiceIndexes,new Set,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_choiceEventStates,[],"f"),__classPrivateFieldSet(this,_ChatCompletionStream_hasAutoParseableTool,!1,"f");let tools=params?.tools,lengthDescriptor=tools&&Object.getOwnPropertyDescriptor(tools,"length"),length=lengthDescriptor&&"value"in lengthDescriptor?lengthDescriptor.value:void 0;if(tools&&typeof length==="number"&&Number.isSafeInteger(length)&&length>=0)for(let index=0;index<Math.min(length,MAX_STREAM_TOOL_CALLS);index+=1){let descriptor=Object.getOwnPropertyDescriptor(tools,String(index));if(!descriptor||!("value"in descriptor))continue;let tool=descriptor.value;if(isChatCompletionFunctionTool(tool)&&(isAutoParsableTool(tool)||tool.function.strict===!0)){__classPrivateFieldSet(this,_ChatCompletionStream_hasAutoParseableTool,!0,"f");break}}__classPrivateFieldSet(this,_ChatCompletionStream_partialJSONParseBudget,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return __classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f")}static fromReadableStream(stream){let runner=new ChatCompletionStream(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}static createChatCompletion(client,params,options){let runner=new ChatCompletionStream(params);return runner._run(()=>runner._runChatCompletion(client,{...params,stream:!0},{...options,__metadata:{...options?.__metadata,helperMethod:"stream"}})),runner}_runTools(client,params,runner,options){return __classPrivateFieldSet(this,_ChatCompletionStream_rejectsUnfinishedTurns,!0,"f"),super._runTools(client,params,runner,options)}async _createChatCompletion(client,params,options){this._listenForAbort(options?.signal);let requestParams={...params,stream:!0};__classPrivateFieldSet(this,_ChatCompletionStream_params,requestParams,"f"),__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this);let parserParams=snapshotChatCompletionParserParams(requestParams);__classPrivateFieldSet(this,_ChatCompletionStream_params,parserParams,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_hasAutoParseableTool,parserParams.tools?.some((tool)=>isChatCompletionFunctionTool(tool)&&(isAutoParsableTool(tool)||tool.function.strict===!0))??!1,"f");let stopObserving=requestParams.tools||requestParams.response_format?observeSerializedChatCompletionParserParams(requestParams,parserParams,(serialized)=>{__classPrivateFieldSet(this,_ChatCompletionStream_params,serialized,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_hasAutoParseableTool,serialized.tools?.some((tool)=>isChatCompletionFunctionTool(tool)&&(isAutoParsableTool(tool)||tool.function.strict===!0))??!1,"f")}):void 0,stream=await client.chat.completions.create(requestParams,{...options,signal:this.controller.signal}).finally(stopObserving);this._connected();for await(let chunk of stream)__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,chunk);if(stream.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}async _fromReadableStream(readableStream,options){this._listenForAbort(options?.signal),__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this),this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller),chatId;for await(let item of stream){if("error"in item&&hasOwn(item,"error")&&typeof item.error==="object"&&item.error!==null)throw new APIError(void 0,item.error,void 0,void 0);if(isChatCompletionReadableStreamMessage(item)){let message=getChatCompletionReadableStreamMessage(item);if(__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f")){let toolCalls=__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f").choices[0]?.message.tool_calls;for(let[index,id]of message.tool_call_ids?.entries()??[]){let toolCall=toolCalls?.[index];if(toolCall&&id)toolCall.id=id}this._addChatCompletion(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this)),chatId=void 0}this._addMessage(message.message);continue}let chunk=normalizeChatCompletionChunk(item);if(chatId&&chunk.id&&chatId!==chunk.id)this._addChatCompletion(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this));if(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,chunk),chunk.id)chatId=chunk.id}if(stream.controller.signal?.aborted)throw this._userAbortError();if(__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"))return this._addChatCompletion(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this));let lastChatCompletion=this._chatCompletions[this._chatCompletions.length-1];if(lastChatCompletion)return lastChatCompletion;throw new OpenAIError("request ended without sending any chunks")}[(_ChatCompletionStream_params=new WeakMap,_ChatCompletionStream_rejectsUnfinishedTurns=new WeakMap,_ChatCompletionStream_audioDoneChoiceIndexes=new WeakMap,_ChatCompletionStream_choiceEventStates=new WeakMap,_ChatCompletionStream_currentChatCompletionSnapshot=new WeakMap,_ChatCompletionStream_hasAutoParseableTool=new WeakMap,_ChatCompletionStream_partialJSONParseBudget=new WeakMap,_ChatCompletionStream_instances=new WeakSet,_ChatCompletionStream_beginRequest=function(){if(this.ended)return;__classPrivateFieldSet(this,_ChatCompletionStream_audioDoneChoiceIndexes,new Set,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_partialJSONParseBudget,{bytes:0,fragments:0,work:0},"f")},_ChatCompletionStream_getChoiceEventState=function(choice){let state=__classPrivateFieldGet(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index];if(state)return state;return state={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},__classPrivateFieldGet(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index]=state,state},_ChatCompletionStream_addChunk=function(chunk){if(this.ended)return;let capturedChoiceFrames=new WeakMap,completion=__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_accumulateChatCompletion).call(this,chunk,capturedChoiceFrames);this._emit("chunk",chunk,completion);for(let choice of chunk.choices){let capturedChoice=capturedChoiceFrames.get(choice),choiceSnapshot=completion.choices[capturedChoice?.index??choice.index],capturedToolCalls=capturedChoice?.tool_calls??[],{delta}=choice,structuredResponse=isParseableResponseFormat(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.response_format),boundedSnapshot=structuredResponse||__classPrivateFieldGet(this,_ChatCompletionStream_hasAutoParseableTool,"f"),messageSnapshot=boundedSnapshot?captureStructuredMessageSnapshot(choiceSnapshot):choiceSnapshot.message,refusal=boundedSnapshot?captureStructuredJSONSnapshot(messageSnapshot,"refusal"):messageSnapshot.refusal,messageContent=!refusal&&structuredResponse?captureStructuredJSONSnapshot(messageSnapshot,"content"):messageSnapshot.content;if(delta?.content!=null&&messageSnapshot.role==="assistant"&&messageContent)this._emit("content",delta.content,messageContent),this._emit("content.delta",{delta:delta.content,snapshot:messageContent,parsed:messageSnapshot.parsed});if(delta?.refusal!=null&&messageSnapshot.role==="assistant"&&refusal)this._emit("refusal.delta",{delta:delta.refusal,snapshot:refusal});if(choice.logprobs?.content!=null&&messageSnapshot.role==="assistant")this._emit("logprobs.content.delta",{content:choice.logprobs?.content,snapshot:choiceSnapshot.logprobs?.content??[]});if(choice.logprobs?.refusal!=null&&messageSnapshot.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:choice.logprobs?.refusal,snapshot:choiceSnapshot.logprobs?.refusal??[]});let state=__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot);if(choiceSnapshot.finish_reason){if(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,choiceSnapshot),state.current_tool_call_index!=null)__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,choiceSnapshot,state.current_tool_call_index)}for(let toolCall of capturedToolCalls){if(state.current_tool_call_index!==toolCall.index){if(__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,choiceSnapshot),state.current_tool_call_index!=null)__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,choiceSnapshot,state.current_tool_call_index)}state.current_tool_call_index=toolCall.index}for(let toolCallDelta of capturedToolCalls){let toolCallSnapshot=messageSnapshot.tool_calls?.[toolCallDelta.index];if(!toolCallSnapshot?.type)continue;if(toolCallSnapshot.type==="function"){let boundIdentity=state.tool_call_identities.get(toolCallDelta.index),argumentsSnapshot;if(boundIdentity?.parseable){let capturedArguments=captureStructuredJSONSnapshot(toolCallSnapshot.function,"arguments");if(typeof capturedArguments!=="string")throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");argumentsSnapshot=capturedArguments}else argumentsSnapshot=toolCallSnapshot.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:toolCallSnapshot.function.name,index:toolCallDelta.index,arguments:argumentsSnapshot,parsed_arguments:toolCallSnapshot.function.parsed_arguments,arguments_delta:toolCallDelta.arguments_delta})}else if(toolCallSnapshot.type!=="custom")assertNever(toolCallSnapshot)}}},_ChatCompletionStream_emitToolCallDoneEvent=function(choiceSnapshot,toolCallIndex){let state=__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot);if(state.done_tool_calls.has(toolCallIndex))return;let toolCallSnapshot=(__classPrivateFieldGet(this,_ChatCompletionStream_hasAutoParseableTool,"f")?captureStructuredMessageSnapshot(choiceSnapshot):choiceSnapshot.message).tool_calls?.[toolCallIndex];if(!toolCallSnapshot)throw Error("no tool call snapshot");let boundIdentity=state.tool_call_identities.get(toolCallIndex);if(boundIdentity)assertBoundToolCallIdentity(toolCallSnapshot,boundIdentity);if(!toolCallSnapshot.type)throw Error("tool call snapshot missing `type`");if(toolCallSnapshot.type==="function"){let inputTool=__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.tools?.find((tool)=>isChatCompletionFunctionTool(tool)&&tool.function.name===toolCallSnapshot.function.name),parsedArguments=null,parseable=isAutoParsableTool(inputTool)||inputTool?.function.strict===!0,argumentsSnapshot;if(parseable){if(__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"))__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_validateStructuredSnapshots).call(this,__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"));let capturedArguments=captureStructuredJSONSnapshot(toolCallSnapshot.function,"arguments");if(typeof capturedArguments!=="string")throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");argumentsSnapshot=capturedArguments}else argumentsSnapshot=toolCallSnapshot.function.arguments;if(isAutoParsableTool(inputTool))parsedArguments=inputTool.$parseRaw(validateStructuredJSONSnapshot(argumentsSnapshot));else if(inputTool?.function.strict)parsedArguments=parseResponseFormatContent({type:"json_schema",$parseRaw:void 0},validateStructuredJSONSnapshot(argumentsSnapshot));if(choiceSnapshot.finish_reason)state.done_tool_calls.add(toolCallIndex);this._emit("tool_calls.function.arguments.done",{name:toolCallSnapshot.function.name,index:toolCallIndex,arguments:argumentsSnapshot,parsed_arguments:parsedArguments})}else if(toolCallSnapshot.type!=="custom")assertNever(toolCallSnapshot)},_ChatCompletionStream_emitContentDoneEvents=function(choiceSnapshot){let state=__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot),structuredResponse=isParseableResponseFormat(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.response_format),boundedSnapshot=structuredResponse||__classPrivateFieldGet(this,_ChatCompletionStream_hasAutoParseableTool,"f"),messageSnapshot=boundedSnapshot?captureStructuredMessageSnapshot(choiceSnapshot):choiceSnapshot.message,refusal=boundedSnapshot?captureStructuredJSONSnapshot(messageSnapshot,"refusal"):messageSnapshot.refusal,parseableContent=!refusal&&structuredResponse,content=parseableContent?captureStructuredJSONSnapshot(messageSnapshot,"content"):messageSnapshot.content;if(content!=null&&(content!==""||!refusal&&!messageSnapshot.tool_calls?.length&&!messageSnapshot.function_call)&&!state.content_done){if(parseableContent&&__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"))__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_validateStructuredSnapshots).call(this,__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"));state.content_done=!0,this._emit("content.done",{content,parsed:refusal?null:parseResponseFormatContent(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.response_format,parseableContent?validateStructuredJSONSnapshot(content):content)})}if(refusal&&!state.refusal_done)state.refusal_done=!0,this._emit("refusal.done",{refusal});if(choiceSnapshot.logprobs?.content&&!state.logprobs_content_done)state.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:choiceSnapshot.logprobs.content});if(choiceSnapshot.logprobs?.refusal&&!state.logprobs_refusal_done)state.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:choiceSnapshot.logprobs.refusal})},_ChatCompletionStream_validateStructuredSnapshots=function(snapshot){let finalJSONBudget={bytes:0,fragments:0,work:0},parseableContent=isParseableResponseFormat(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.response_format),validatedMessages=new WeakMap,choices=captureSnapshotArray(snapshot,"choices",MAX_STREAM_CHOICES,"choice");if(!choices)throw new OpenAIError("Chat completion stream contains an unsafe snapshot choice collection");for(let choiceIndex=0;choiceIndex<choices.length;choiceIndex+=1){let choice=captureSnapshotArrayItem(choices,choiceIndex);if(!choice)continue;let message=captureStructuredMessageSnapshot(choice),refusal=captureStructuredJSONSnapshot(message,"refusal"),content=captureStructuredJSONSnapshot(message,"content"),validatedTools=new Map,toolCalls=captureSnapshotArray(message,"tool_calls",MAX_STREAM_TOOL_CALLS,"tool-call");validatedMessages.set(choice,Object.freeze({message,content,refusal,toolCallCollection:toolCalls,toolCalls:validatedTools}));let state=__classPrivateFieldGet(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index];if(parseableContent&&!refusal&&typeof content==="string")validateStructuredJSONSnapshot(content,finalJSONBudget,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f"));for(let[index,identity]of state?.tool_call_identities??[]){let toolCall=toolCalls&&captureSnapshotArrayItem(toolCalls,index);if(!toolCall)throw new OpenAIError("Chat completion stream contains a changed tool call identity");assertBoundToolCallIdentity(toolCall,identity)}if(!__classPrivateFieldGet(this,_ChatCompletionStream_hasAutoParseableTool,"f"))continue;for(let toolCallIndex=0;toolCallIndex<(toolCalls?.length??0);toolCallIndex+=1){let toolCall=captureSnapshotArrayItem(toolCalls,toolCallIndex);if(!toolCall)continue;let identity=ownFunctionToolIdentity(toolCall);if(!identity){let type=Object.getOwnPropertyDescriptor(toolCall,"type");if(type&&!("value"in type))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");if(type?.value!=="function")continue;let fn=Object.getOwnPropertyDescriptor(toolCall,"function");if(fn&&!("value"in fn))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");if(fn&&typeof fn.value==="object"&&fn.value!==null){let name=Object.getOwnPropertyDescriptor(fn.value,"name");if(name&&!("value"in name))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!shouldParseToolCall(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f"),{type:identity.type,function:{name:identity.name}}))continue;let descriptor=Object.getOwnPropertyDescriptor(toolCall,"function");if(!descriptor||!("value"in descriptor))throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");let fn=descriptor.value,argumentsSnapshot=captureStructuredJSONSnapshot(fn,"arguments");if(typeof argumentsSnapshot!=="string")throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");validateStructuredJSONSnapshot(argumentsSnapshot,finalJSONBudget,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f")),validatedTools.set(toolCallIndex,Object.freeze({tool:toolCall,function:fn,type:identity.type,name:identity.name,arguments:argumentsSnapshot}))}}return validatedMessages},_ChatCompletionStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");let snapshot=__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f");if(!snapshot)throw new OpenAIError("request ended without sending any chunks");let validatedMessages=__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_validateStructuredSnapshots).call(this,snapshot),audioDoneChoiceIndexes=__classPrivateFieldGet(this,_ChatCompletionStream_audioDoneChoiceIndexes,"f");return __classPrivateFieldSet(this,_ChatCompletionStream_audioDoneChoiceIndexes,new Set,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f"),__classPrivateFieldSet(this,_ChatCompletionStream_choiceEventStates,[],"f"),finalizeChatCompletion(snapshot,__classPrivateFieldGet(this,_ChatCompletionStream_params,"f"),audioDoneChoiceIndexes,validatedMessages)},_ChatCompletionStream_accumulateChatCompletion=function(chunk,capturedChoiceFrames){var _a,_b,_c,_d,_e;let snapshot=__classPrivateFieldGet(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"),{choices,obfuscation:_obfuscation,...rest}=chunk;if(!snapshot){let newSnapshot={...rest,choices:[]};__classPrivateFieldSet(this,_ChatCompletionStream_currentChatCompletionSnapshot,newSnapshot,"f"),snapshot=newSnapshot}else if(chunk.id)assignOwnProperties(snapshot,rest);let requestedChoiceCount=__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.n,maxChoices=typeof requestedChoiceCount==="number"&&Number.isSafeInteger(requestedChoiceCount)&&requestedChoiceCount>0?Math.min(requestedChoiceCount,MAX_STREAM_CHOICES):MAX_STREAM_CHOICES;for(let chunkChoice of chunk.choices){let{delta,finish_reason,index,logprobs=null,...other}=chunkChoice,capturedToolCalls=[];if(capturedChoiceFrames.set(chunkChoice,Object.freeze({index,tool_calls:capturedToolCalls})),!Number.isSafeInteger(index)||index<0||index>=maxChoices)throw new OpenAIError(`Chat completion stream contains an invalid choice index: ${index}`);let choice=snapshot.choices[index];if(!choice){let newChoice={finish_reason:finish_reason??null,index,message:{},logprobs:null,...other};snapshot.choices[index]=newChoice,choice=newChoice}if(isParseableResponseFormat(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.response_format)||__classPrivateFieldGet(this,_ChatCompletionStream_hasAutoParseableTool,"f"))captureStructuredJSONSnapshot(captureStructuredMessageSnapshot(choice),"refusal");if(logprobs)if(choice.logprobs){let{content,refusal,...rest}=logprobs;if(assertIsEmpty(rest),assignOwnProperties(choice.logprobs,rest),content)(_a=choice.logprobs).content??(_a.content=[]),choice.logprobs.content.push(...content);if(refusal)(_b=choice.logprobs).refusal??(_b.refusal=[]),choice.logprobs.refusal.push(...refusal)}else{if(choice.logprobs={...logprobs},logprobs.content)choice.logprobs.content=[...logprobs.content];if(logprobs.refusal)choice.logprobs.refusal=[...logprobs.refusal]}if(finish_reason){if(choice.finish_reason=finish_reason,__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")&&(__classPrivateFieldGet(this,_ChatCompletionStream_rejectsUnfinishedTurns,"f")||hasAutoParseableInput(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")))){if(finish_reason==="length")throw new LengthFinishReasonError;if(finish_reason==="content_filter")throw new ContentFilterFinishReasonError}}if(assignOwnProperties(choice,other),!delta){Object.freeze(capturedToolCalls);continue}__classPrivateFieldGet(this,_ChatCompletionStream_audioDoneChoiceIndexes,"f").delete(index);let{audio,content,refusal,function_call,role,...capturedDeltaFields}=delta,{tool_calls:capturedToolCallDelta,...rest}=capturedDeltaFields,tool_calls=hasOwn(capturedDeltaFields,"tool_calls")?capturedToolCallDelta:delta.tool_calls;if(assertIsEmpty(rest),assignOwnProperties(choice.message,rest),audio?.expires_at!=null&&audio.id==null&&audio.data==null&&audio.transcript==null&&content==null&&refusal==null&&function_call==null&&role==null&&tool_calls==null&&Object.keys(rest).length===0)__classPrivateFieldGet(this,_ChatCompletionStream_audioDoneChoiceIndexes,"f").add(index);if(refusal)choice.message.refusal=(choice.message.refusal||"")+refusal;if(role)choice.message.role=role;if(audio){let audioSnapshot=(_c=choice.message).audio??(_c.audio={});if(audio.id!=null)audioSnapshot.id=audio.id;if(audio.data!=null)audioSnapshot.data=(audioSnapshot.data??"")+audio.data;if(audio.transcript!=null)audioSnapshot.transcript=(audioSnapshot.transcript??"")+audio.transcript;if(audio.expires_at!=null)audioSnapshot.expires_at=audio.expires_at}if(function_call)if(choice.message.function_call){if(function_call.name)choice.message.function_call.name=function_call.name;if(function_call.arguments)(_d=choice.message.function_call).arguments??(_d.arguments=""),choice.message.function_call.arguments+=function_call.arguments}else choice.message.function_call=function_call;if(content!=null)if(!choice.message.refusal&&isParseableResponseFormat(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.response_format)){let eventState=__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choice),parseState=eventState.content_parse_state??(eventState.content_parse_state=createPartialJSONParseState()),shouldParse=recordPartialJSONFragment(parseState,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f"),content);if(choice.message.content=(captureStructuredJSONSnapshot(choice.message,"content")||"")+content,!parseState.has_non_whitespace)choice.message.parsed=null;else if(shouldParse&&reservePartialJSONParse(parseState,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f")))__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_validateStructuredSnapshots).call(this,snapshot),choice.message.parsed=parseStructuredStreamingJSON(validateStructuredJSONSnapshot(choice.message.content));else if(content.length>0)choice.message.parsed=null}else choice.message.content=(choice.message.content||"")+content;if(tool_calls){let toolCallSnapshots=(_e=choice.message).tool_calls??(_e.tool_calls=[]);for(let toolCallDelta of tool_calls){let{index,id,type,function:fn,custom,...rest}=toolCallDelta;if(!Number.isSafeInteger(index)||index<0||index>=MAX_STREAM_TOOL_CALLS)throw new OpenAIError(`Chat completion stream contains an invalid tool call index: ${index}`);let argumentsDelta="",tool_call=toolCallSnapshots[index]??(toolCallSnapshots[index]={}),functionName=fn?.name,eventState=__classPrivateFieldGet(this,_ChatCompletionStream_hasAutoParseableTool,"f")?__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choice):void 0,boundIdentity=eventState?.tool_call_identities.get(index);if(boundIdentity){if(assertBoundToolCallIdentity(tool_call,boundIdentity),type!==void 0&&type!==boundIdentity.type||functionName!==void 0&&functionName!==boundIdentity.name)throw new OpenAIError("Chat completion stream contains a changed tool call identity")}if(assignOwnProperties(tool_call,rest),id)tool_call.id=id;if(type)tool_call.type=type;if(custom){let customSnapshot=tool_call.custom??(tool_call.custom={name:custom.name??"",input:""});if(custom.name)customSnapshot.name=custom.name;if(custom.input)customSnapshot.input+=custom.input}if(fn){let functionSnapshot=tool_call.function??(tool_call.function={name:functionName??"",arguments:""});if(functionName)functionSnapshot.name=functionName;if(eventState&&!boundIdentity){let identity=ownFunctionToolIdentity(tool_call),configuredTool=identity&&__classPrivateFieldGet(this,_ChatCompletionStream_params,"f")?.tools?.find((tool)=>isChatCompletionFunctionTool(tool)&&tool.function.name===identity.name);if(identity){if(boundIdentity={...identity,parseable:configuredTool!==void 0&&shouldParseToolCall(__classPrivateFieldGet(this,_ChatCompletionStream_params,"f"),{type:identity.type,function:{name:identity.name}})},eventState.tool_call_identities.set(index,boundIdentity),!boundIdentity.parseable){let provisionalState=eventState.tool_call_parse_states.get(index);if(provisionalState)__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f").bytes-=provisionalState.bytes,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f").fragments-=provisionalState.fragments,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f").work-=provisionalState.work,eventState.tool_call_parse_states.delete(index)}}}let argumentFragment=fn.arguments;if(argumentFragment!=null)if(argumentsDelta=argumentFragment,eventState&&boundIdentity?.parseable!==!1){let parseState=eventState.tool_call_parse_states.get(index);if(!parseState)parseState=createPartialJSONParseState(),eventState.tool_call_parse_states.set(index,parseState);let shouldParse=recordPartialJSONFragment(parseState,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f"),argumentFragment),previousArguments=captureStructuredJSONSnapshot(functionSnapshot,"arguments");if(typeof previousArguments!=="string")throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");if(functionSnapshot.arguments=previousArguments+argumentFragment,shouldParse&&boundIdentity?.parseable===!0&&reservePartialJSONParse(parseState,__classPrivateFieldGet(this,_ChatCompletionStream_partialJSONParseBudget,"f")))__classPrivateFieldGet(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_validateStructuredSnapshots).call(this,snapshot),functionSnapshot.parsed_arguments=parseStructuredStreamingJSON(validateStructuredJSONSnapshot(functionSnapshot.arguments));else if(argumentFragment.length>0&&hasOwn(functionSnapshot,"parsed_arguments"))functionSnapshot.parsed_arguments=void 0}else functionSnapshot.arguments+=argumentFragment}capturedToolCalls.push(Object.freeze({index,arguments_delta:argumentsDelta}))}}Object.freeze(capturedToolCalls)}return snapshot},Symbol.asyncIterator)](){return this._createIterator((push)=>{let onChunk=(chunk)=>push(chunk);return this.on("chunk",onChunk),()=>this.off("chunk",onChunk)},{onReturn:()=>this.abort()})}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var ChatCompletionStreamingRunner;var init_ChatCompletionStreamingRunner=__esm(()=>{init_ChatCompletionStream();init_error2();init_streaming2();ChatCompletionStreamingRunner=class ChatCompletionStreamingRunner extends ChatCompletionStream{static fromReadableStream(stream){let runner=new ChatCompletionStreamingRunner(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}toReadableStream(){let lastChunk,toolCallIds,iterator=this._createIterator((push)=>{let onChunk=(chunk)=>{lastChunk=chunk,push(chunk)},onMessage=(message)=>{if(isAssistantMessage(message)){toolCallIds=message.tool_calls?.map((toolCall)=>toolCall.id);return}if(isToolMessage(message)){if(!lastChunk)throw new OpenAIError("cannot serialize a tool message before receiving any chunks");push(makeChatCompletionReadableStreamMessageChunk(lastChunk,message,toolCallIds)),toolCallIds=void 0}};return this.on("chunk",onChunk),this.on("message",onMessage),()=>{this.off("chunk",onChunk),this.off("message",onMessage)}},{onReturn:()=>this.abort()});return new Stream(()=>iterator,this.controller).toReadableStream()}static runTools(client,params,options){let runner=new ChatCompletionStreamingRunner(params),opts={...options,__metadata:{...options?.__metadata,helperMethod:"runTools"}};return runner._run(()=>runner._runTools(client,params,runner,opts)),runner}}});function resolveResourceRequestOptions2(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery2(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys2.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys2.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys2,Completions;var init_completions=__esm(()=>{init_messages();init_messages();init_pagination();init_path();init_ChatCompletionRunner();init_ChatCompletionStreamingRunner();init_ChatCompletionStream();init_parser();init_ChatCompletionStreamingRunner();init_ChatCompletionStream();init_ChatCompletionRunner();normalizeRequestOptionsForQueryKeys2=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Completions=class Completions extends APIResource{constructor(){super(...arguments);this.messages=new Messages(this._client)}create(body,options){return this._client.post("/chat/completions",resolveResourceRequestOptions2(options,(options)=>withBodyFinalization({body,...options,stream:body.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))._thenUnwrap((result,props)=>props.options.stream?normalizeChatCompletionStream(result):result)}retrieve(completionID,options){return this._client.get(path`/chat/completions/${completionID}`,resolveResourceRequestOptions2(options,(options)=>({...options,__security:{bearerAuth:!0}})))}update(completionID,body,options){return this._client.post(path`/chat/completions/${completionID}`,resolveResourceRequestOptions2(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery2(query,["after","limit","metadata","model","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/chat/completions",CursorPage,resolveResourceRequestOptions2(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(completionID,options){return this._client.delete(path`/chat/completions/${completionID}`,resolveResourceRequestOptions2(options,(options)=>({...options,__security:{bearerAuth:!0}})))}parse(body,options){return validateInputTools(body.tools),this._client.chat.completions.create(body,{...options,__metadata:{...options?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap((completion)=>parseChatCompletion(completion,body))}runTools(body,options){if(body.stream)return ChatCompletionStreamingRunner.runTools(this._client,body,options);return ChatCompletionRunner.runTools(this._client,body,options)}stream(body,options){return ChatCompletionStream.createChatCompletion(this._client,body,options)}};Completions.Messages=Messages});var Chat;var init_chat=__esm(()=>{init_completions();init_completions();Chat=class Chat extends APIResource{constructor(){super(...arguments);this.completions=new Completions(this._client)}};Chat.Completions=Completions});var init_completions2=__esm(()=>{init_messages();init_completions()});var init_chat2=__esm(()=>{init_chat();init_completions2()});var init_shared=()=>{};function resolveResourceRequestOptions3(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery3(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys3.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys3.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys3,AdminAPIKeys;var init_admin_api_keys=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys3=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);AdminAPIKeys=class AdminAPIKeys extends APIResource{create(body,options){return this._client.post("/organization/admin_api_keys",resolveResourceRequestOptions3(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(keyID,options){return this._client.get(path`/organization/admin_api_keys/${keyID}`,resolveResourceRequestOptions3(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery3(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/admin_api_keys",CursorPage,resolveResourceRequestOptions3(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(keyID,options){return this._client.delete(path`/organization/admin_api_keys/${keyID}`,resolveResourceRequestOptions3(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions4(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery4(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys4.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys4.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys4,AuditLogs;var init_audit_logs=__esm(()=>{init_pagination();normalizeRequestOptionsForQueryKeys4=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);AuditLogs=class AuditLogs extends APIResource{list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery4(query,["actor_emails","actor_ids","after","before","effective_at","event_types","limit","project_ids","resource_ids","tenant_only"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/audit_logs",ConversationCursorPage,resolveResourceRequestOptions4(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions5(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery5(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys5.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys5.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys5,Certificates;var init_certificates=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys5=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Certificates=class Certificates extends APIResource{create(body,options){return this._client.post("/organization/certificates",resolveResourceRequestOptions5(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(certificateID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery5(query,["include"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.get(path`/organization/certificates/${certificateID}`,resolveResourceRequestOptions5(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}update(certificateID,body,options){return this._client.post(path`/organization/certificates/${certificateID}`,resolveResourceRequestOptions5(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery5(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/certificates",ConversationCursorPage,resolveResourceRequestOptions5(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(certificateID,options){return this._client.delete(path`/organization/certificates/${certificateID}`,resolveResourceRequestOptions5(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}activate(body,options){return this._client.getAPIList("/organization/certificates/activate",Page,resolveResourceRequestOptions5(options,(options)=>({body,method:"post",...options,__security:{adminAPIKeyAuth:!0}})))}deactivate(body,options){return this._client.getAPIList("/organization/certificates/deactivate",Page,resolveResourceRequestOptions5(options,(options)=>({body,method:"post",...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions6(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var DataRetention;var init_data_retention=__esm(()=>{DataRetention=class DataRetention extends APIResource{retrieve(options){return this._client.get("/organization/data_retention",resolveResourceRequestOptions6(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(body,options){return this._client.post("/organization/data_retention",resolveResourceRequestOptions6(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions7(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery6(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys6.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys6.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys6,ExternalKeys;var init_external_keys=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys6=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);ExternalKeys=class ExternalKeys extends APIResource{create(body,options){return this._client.post("/organization/external_keys",resolveResourceRequestOptions7(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(externalKeyID,options){return this._client.get(path`/organization/external_keys/${externalKeyID}`,resolveResourceRequestOptions7(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery6(query,["after","limit","order","purpose"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/external_keys",CursorPage,resolveResourceRequestOptions7(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(externalKeyID,options){return this._client.delete(path`/organization/external_keys/${externalKeyID}`,resolveResourceRequestOptions7(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}validate(externalKeyID,options){return this._client.post(path`/organization/external_keys/${externalKeyID}/validate`,resolveResourceRequestOptions7(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions8(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery7(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys7.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys7.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys7,ExternalStorage;var init_external_storage=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys7=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);ExternalStorage=class ExternalStorage extends APIResource{create(body,options){return this._client.post("/organization/external_storage",resolveResourceRequestOptions8(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(externalStorageID,options){return this._client.get(path`/organization/external_storage/${externalStorageID}`,resolveResourceRequestOptions8(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery7(query,["after","limit","order","project_id"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/external_storage",CursorPage,resolveResourceRequestOptions8(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(externalStorageID,options){return this._client.delete(path`/organization/external_storage/${externalStorageID}`,resolveResourceRequestOptions8(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}validate(externalStorageID,options){return this._client.post(path`/organization/external_storage/${externalStorageID}/validate`,resolveResourceRequestOptions8(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions9(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery8(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys8.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys8.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys8,Invites;var init_invites=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys8=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Invites=class Invites extends APIResource{create(body,options){return this._client.post("/organization/invites",resolveResourceRequestOptions9(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(inviteID,options){return this._client.get(path`/organization/invites/${inviteID}`,resolveResourceRequestOptions9(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery8(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/invites",ConversationCursorPage,resolveResourceRequestOptions9(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(inviteID,options){return this._client.delete(path`/organization/invites/${inviteID}`,resolveResourceRequestOptions9(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions10(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery9(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys9.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys9.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys9,Roles;var init_roles=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys9=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Roles=class Roles extends APIResource{create(body,options){return this._client.post("/organization/roles",resolveResourceRequestOptions10(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(roleID,options){return this._client.get(path`/organization/roles/${roleID}`,resolveResourceRequestOptions10(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(roleID,body,options){return this._client.post(path`/organization/roles/${roleID}`,resolveResourceRequestOptions10(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery9(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/roles",NextCursorPage,resolveResourceRequestOptions10(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(roleID,options){return this._client.delete(path`/organization/roles/${roleID}`,resolveResourceRequestOptions10(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions11(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery10(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys10.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys10.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys10,SpendAlerts;var init_spend_alerts=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys10=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);SpendAlerts=class SpendAlerts extends APIResource{create(body,options){return this._client.post("/organization/spend_alerts",resolveResourceRequestOptions11(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(alertID,options){return this._client.get(path`/organization/spend_alerts/${alertID}`,resolveResourceRequestOptions11(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(alertID,body,options){return this._client.post(path`/organization/spend_alerts/${alertID}`,resolveResourceRequestOptions11(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery10(query,["after","before","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/spend_alerts",ConversationCursorPage,resolveResourceRequestOptions11(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(alertID,options){return this._client.delete(path`/organization/spend_alerts/${alertID}`,resolveResourceRequestOptions11(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions12(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var SpendLimit;var init_spend_limit=__esm(()=>{SpendLimit=class SpendLimit extends APIResource{retrieve(options){return this._client.get("/organization/spend_limit",resolveResourceRequestOptions12(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(body,options){return this._client.post("/organization/spend_limit",resolveResourceRequestOptions12(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}delete(options){return this._client.delete("/organization/spend_limit",resolveResourceRequestOptions12(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions13(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Usage;var init_usage=__esm(()=>{Usage=class Usage extends APIResource{audioSpeeches(query,options){return this._client.get("/organization/usage/audio_speeches",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}audioTranscriptions(query,options){return this._client.get("/organization/usage/audio_transcriptions",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}codeInterpreterSessions(query,options){return this._client.get("/organization/usage/code_interpreter_sessions",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}completions(query,options){return this._client.get("/organization/usage/completions",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}costs(query,options){return this._client.get("/organization/costs",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}decisions(query,options){return this._client.get("/organization/usage/decisions",resolveResourceRequestOptions13(options,(options)=>({query:Object.fromEntries(Object.entries(query).filter(([,value])=>value!==null)),...options,__security:{adminAPIKeyAuth:!0}})))}embeddings(query,options){return this._client.get("/organization/usage/embeddings",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}fileSearchCalls(query,options){return this._client.get("/organization/usage/file_search_calls",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}images(query,options){return this._client.get("/organization/usage/images",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}moderations(query,options){return this._client.get("/organization/usage/moderations",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}vectorStores(query,options){return this._client.get("/organization/usage/vector_stores",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}webSearchCalls(query,options){return this._client.get("/organization/usage/web_search_calls",resolveResourceRequestOptions13(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions14(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery11(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys11.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys11.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys11,Roles2;var init_roles2=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys11=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Roles2=class Roles2 extends APIResource{create(groupID,body,options){return this._client.post(path`/organization/groups/${groupID}/roles`,resolveResourceRequestOptions14(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(roleID,params,options){let{group_id}=params;return this._client.get(path`/organization/groups/${group_id}/roles/${roleID}`,resolveResourceRequestOptions14(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(groupID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery11(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/groups/${groupID}/roles`,NextCursorPage,resolveResourceRequestOptions14(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(roleID,params,options){let{group_id}=params;return this._client.delete(path`/organization/groups/${group_id}/roles/${roleID}`,resolveResourceRequestOptions14(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions15(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery12(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys12.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys12.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys12,Users;var init_users=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys12=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Users=class Users extends APIResource{create(groupID,body,options){return this._client.post(path`/organization/groups/${groupID}/users`,resolveResourceRequestOptions15(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(userID,params,options){let{group_id}=params;return this._client.get(path`/organization/groups/${group_id}/users/${userID}`,resolveResourceRequestOptions15(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(groupID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery12(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/groups/${groupID}/users`,NextCursorPage,resolveResourceRequestOptions15(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(userID,params,options){let{group_id}=params;return this._client.delete(path`/organization/groups/${group_id}/users/${userID}`,resolveResourceRequestOptions15(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions16(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery13(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys13.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys13.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys13,Groups;var init_groups=__esm(()=>{init_roles2();init_roles2();init_users();init_users();init_pagination();init_path();normalizeRequestOptionsForQueryKeys13=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Groups=class Groups extends APIResource{constructor(){super(...arguments);this.users=new Users(this._client),this.roles=new Roles2(this._client)}create(body,options){return this._client.post("/organization/groups",resolveResourceRequestOptions16(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(groupID,options){return this._client.get(path`/organization/groups/${groupID}`,resolveResourceRequestOptions16(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(groupID,body,options){return this._client.post(path`/organization/groups/${groupID}`,resolveResourceRequestOptions16(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery13(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/groups",NextCursorPage,resolveResourceRequestOptions16(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(groupID,options){return this._client.delete(path`/organization/groups/${groupID}`,resolveResourceRequestOptions16(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}};Groups.Users=Users;Groups.Roles=Roles2});function resolveResourceRequestOptions17(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery14(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys14.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys14.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys14,APIKeys;var init_api_keys=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys14=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);APIKeys=class APIKeys extends APIResource{retrieve(apiKeyID,params,options){let{project_id}=params;return this._client.get(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`,resolveResourceRequestOptions17(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(apiKeyID,params,options){let{project_id,...body}=params;return this._client.post(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`,resolveResourceRequestOptions17(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery14(query,["after","limit","owner_project_access"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/api_keys`,ConversationCursorPage,resolveResourceRequestOptions17(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(apiKeyID,params,options){let{project_id}=params;return this._client.delete(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`,resolveResourceRequestOptions17(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions18(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery15(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys15.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys15.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys15,Certificates2;var init_certificates2=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys15=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Certificates2=class Certificates2 extends APIResource{list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery15(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/certificates`,ConversationCursorPage,resolveResourceRequestOptions18(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}activate(projectID,body,options){return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/activate`,Page,resolveResourceRequestOptions18(options,(options)=>({body,method:"post",...options,__security:{adminAPIKeyAuth:!0}})))}deactivate(projectID,body,options){return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/deactivate`,Page,resolveResourceRequestOptions18(options,(options)=>({body,method:"post",...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions19(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var DataRetention2;var init_data_retention2=__esm(()=>{init_path();DataRetention2=class DataRetention2 extends APIResource{retrieve(projectID,options){return this._client.get(path`/organization/projects/${projectID}/data_retention`,resolveResourceRequestOptions19(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/data_retention`,resolveResourceRequestOptions19(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions20(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var HostedToolPermissions;var init_hosted_tool_permissions=__esm(()=>{init_path();HostedToolPermissions=class HostedToolPermissions extends APIResource{retrieve(projectID,options){return this._client.get(path`/organization/projects/${projectID}/hosted_tool_permissions`,resolveResourceRequestOptions20(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/hosted_tool_permissions`,resolveResourceRequestOptions20(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions21(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var ModelPermissions;var init_model_permissions=__esm(()=>{init_path();ModelPermissions=class ModelPermissions extends APIResource{retrieve(projectID,options){return this._client.get(path`/organization/projects/${projectID}/model_permissions`,resolveResourceRequestOptions21(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/model_permissions`,resolveResourceRequestOptions21(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}delete(projectID,options){return this._client.delete(path`/organization/projects/${projectID}/model_permissions`,resolveResourceRequestOptions21(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions22(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery16(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys16.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys16.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys16,RateLimits;var init_rate_limits=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys16=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);RateLimits=class RateLimits extends APIResource{listRateLimits(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery16(query,["after","before","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/rate_limits`,ConversationCursorPage,resolveResourceRequestOptions22(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}updateRateLimit(rateLimitID,params,options){let{project_id,...body}=params;return this._client.post(path`/organization/projects/${project_id}/rate_limits/${rateLimitID}`,resolveResourceRequestOptions22(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions23(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery17(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys17.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys17.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys17,Roles3;var init_roles3=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys17=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Roles3=class Roles3 extends APIResource{create(projectID,body,options){return this._client.post(path`/projects/${projectID}/roles`,resolveResourceRequestOptions23(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(roleID,params,options){let{project_id}=params;return this._client.get(path`/projects/${project_id}/roles/${roleID}`,resolveResourceRequestOptions23(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(roleID,params,options){let{project_id,...body}=params;return this._client.post(path`/projects/${project_id}/roles/${roleID}`,resolveResourceRequestOptions23(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery17(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/projects/${projectID}/roles`,NextCursorPage,resolveResourceRequestOptions23(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(roleID,params,options){let{project_id}=params;return this._client.delete(path`/projects/${project_id}/roles/${roleID}`,resolveResourceRequestOptions23(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions24(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery18(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys18.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys18.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys18,SpendAlerts2;var init_spend_alerts2=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys18=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);SpendAlerts2=class SpendAlerts2 extends APIResource{create(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/spend_alerts`,resolveResourceRequestOptions24(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(alertID,params,options){let{project_id}=params;return this._client.get(path`/organization/projects/${project_id}/spend_alerts/${alertID}`,resolveResourceRequestOptions24(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(alertID,params,options){let{project_id,...body}=params;return this._client.post(path`/organization/projects/${project_id}/spend_alerts/${alertID}`,resolveResourceRequestOptions24(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery18(query,["after","before","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/spend_alerts`,ConversationCursorPage,resolveResourceRequestOptions24(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(alertID,params,options){let{project_id}=params;return this._client.delete(path`/organization/projects/${project_id}/spend_alerts/${alertID}`,resolveResourceRequestOptions24(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions25(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var SpendLimit2;var init_spend_limit2=__esm(()=>{init_path();SpendLimit2=class SpendLimit2 extends APIResource{retrieve(projectID,options){return this._client.get(path`/organization/projects/${projectID}/spend_limit`,resolveResourceRequestOptions25(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/spend_limit`,resolveResourceRequestOptions25(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}delete(projectID,options){return this._client.delete(path`/organization/projects/${projectID}/spend_limit`,resolveResourceRequestOptions25(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions26(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Roles4;var init_roles4=__esm(()=>{init_pagination();init_path();Roles4=class Roles4 extends APIResource{create(groupID,params,options){let{project_id,...body}=params;return this._client.post(path`/projects/${project_id}/groups/${groupID}/roles`,resolveResourceRequestOptions26(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(roleID,params,options){let{project_id,group_id}=params;return this._client.get(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`,resolveResourceRequestOptions26(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(groupID,params,options){let{project_id,...query}=params;return this._client.getAPIList(path`/projects/${project_id}/groups/${groupID}/roles`,NextCursorPage,resolveResourceRequestOptions26(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(roleID,params,options){let{project_id,group_id}=params;return this._client.delete(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`,resolveResourceRequestOptions26(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions27(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery19(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys19.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys19.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys19,Groups2;var init_groups2=__esm(()=>{init_roles4();init_roles4();init_pagination();init_path();normalizeRequestOptionsForQueryKeys19=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Groups2=class Groups2 extends APIResource{constructor(){super(...arguments);this.roles=new Roles4(this._client)}create(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/groups`,resolveResourceRequestOptions27(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(groupID,params,options){let{project_id,...query}=params;return this._client.get(path`/organization/projects/${project_id}/groups/${groupID}`,resolveResourceRequestOptions27(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery19(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/groups`,NextCursorPage,resolveResourceRequestOptions27(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(groupID,params,options){let{project_id}=params;return this._client.delete(path`/organization/projects/${project_id}/groups/${groupID}`,resolveResourceRequestOptions27(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}};Groups2.Roles=Roles4});function resolveResourceRequestOptions28(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var APIKeys2;var init_api_keys2=__esm(()=>{init_path();APIKeys2=class APIKeys2 extends APIResource{create(serviceAccountID,params,options){let{project_id,...body}=params;return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}/api_keys`,resolveResourceRequestOptions28(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions29(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery20(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys20.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys20.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys20,ServiceAccounts;var init_service_accounts=__esm(()=>{init_api_keys2();init_api_keys2();init_pagination();init_path();normalizeRequestOptionsForQueryKeys20=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);ServiceAccounts=class ServiceAccounts extends APIResource{constructor(){super(...arguments);this.apiKeys=new APIKeys2(this._client)}create(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/service_accounts`,resolveResourceRequestOptions29(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(serviceAccountID,params,options){let{project_id}=params;return this._client.get(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`,resolveResourceRequestOptions29(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(serviceAccountID,params,options){let{project_id,...body}=params;return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`,resolveResourceRequestOptions29(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery20(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/service_accounts`,ConversationCursorPage,resolveResourceRequestOptions29(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(serviceAccountID,params,options){let{project_id}=params;return this._client.delete(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`,resolveResourceRequestOptions29(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}};ServiceAccounts.APIKeys=APIKeys2});function resolveResourceRequestOptions30(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Roles5;var init_roles5=__esm(()=>{init_pagination();init_path();Roles5=class Roles5 extends APIResource{create(userID,params,options){let{project_id,...body}=params;return this._client.post(path`/projects/${project_id}/users/${userID}/roles`,resolveResourceRequestOptions30(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(roleID,params,options){let{project_id,user_id}=params;return this._client.get(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`,resolveResourceRequestOptions30(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(userID,params,options){let{project_id,...query}=params;return this._client.getAPIList(path`/projects/${project_id}/users/${userID}/roles`,NextCursorPage,resolveResourceRequestOptions30(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(roleID,params,options){let{project_id,user_id}=params;return this._client.delete(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`,resolveResourceRequestOptions30(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions31(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery21(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys21.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys21.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys21,Users2;var init_users2=__esm(()=>{init_roles5();init_roles5();init_pagination();init_path();normalizeRequestOptionsForQueryKeys21=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Users2=class Users2 extends APIResource{constructor(){super(...arguments);this.roles=new Roles5(this._client)}create(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}/users`,resolveResourceRequestOptions31(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(userID,params,options){let{project_id}=params;return this._client.get(path`/organization/projects/${project_id}/users/${userID}`,resolveResourceRequestOptions31(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(userID,params,options){let{project_id,...body}=params;return this._client.post(path`/organization/projects/${project_id}/users/${userID}`,resolveResourceRequestOptions31(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(projectID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery21(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/projects/${projectID}/users`,ConversationCursorPage,resolveResourceRequestOptions31(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(userID,params,options){let{project_id}=params;return this._client.delete(path`/organization/projects/${project_id}/users/${userID}`,resolveResourceRequestOptions31(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}};Users2.Roles=Roles5});function resolveResourceRequestOptions32(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery22(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys22.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys22.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys22,Projects;var init_projects=__esm(()=>{init_api_keys();init_api_keys();init_certificates2();init_certificates2();init_data_retention2();init_data_retention2();init_hosted_tool_permissions();init_hosted_tool_permissions();init_model_permissions();init_model_permissions();init_rate_limits();init_rate_limits();init_roles3();init_roles3();init_spend_alerts2();init_spend_alerts2();init_spend_limit2();init_spend_limit2();init_groups2();init_groups2();init_service_accounts();init_service_accounts();init_users2();init_users2();init_pagination();init_path();normalizeRequestOptionsForQueryKeys22=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Projects=class Projects extends APIResource{constructor(){super(...arguments);this.users=new Users2(this._client),this.serviceAccounts=new ServiceAccounts(this._client),this.apiKeys=new APIKeys(this._client),this.rateLimits=new RateLimits(this._client),this.modelPermissions=new ModelPermissions(this._client),this.hostedToolPermissions=new HostedToolPermissions(this._client),this.groups=new Groups2(this._client),this.roles=new Roles3(this._client),this.dataRetention=new DataRetention2(this._client),this.spendLimit=new SpendLimit2(this._client),this.spendAlerts=new SpendAlerts2(this._client),this.certificates=new Certificates2(this._client)}create(body,options){return this._client.post("/organization/projects",resolveResourceRequestOptions32(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(projectID,options){return this._client.get(path`/organization/projects/${projectID}`,resolveResourceRequestOptions32(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(projectID,body,options){return this._client.post(path`/organization/projects/${projectID}`,resolveResourceRequestOptions32(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery22(query,["after","include_archived","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/projects",ConversationCursorPage,resolveResourceRequestOptions32(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}archive(projectID,options){return this._client.post(path`/organization/projects/${projectID}/archive`,resolveResourceRequestOptions32(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}};Projects.Users=Users2;Projects.ServiceAccounts=ServiceAccounts;Projects.APIKeys=APIKeys;Projects.RateLimits=RateLimits;Projects.ModelPermissions=ModelPermissions;Projects.HostedToolPermissions=HostedToolPermissions;Projects.Groups=Groups2;Projects.Roles=Roles3;Projects.DataRetention=DataRetention2;Projects.SpendLimit=SpendLimit2;Projects.SpendAlerts=SpendAlerts2;Projects.Certificates=Certificates2});function resolveResourceRequestOptions33(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery23(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys23.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys23.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys23,Roles6;var init_roles6=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys23=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Roles6=class Roles6 extends APIResource{create(userID,body,options){return this._client.post(path`/organization/users/${userID}/roles`,resolveResourceRequestOptions33(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(roleID,params,options){let{user_id}=params;return this._client.get(path`/organization/users/${user_id}/roles/${roleID}`,resolveResourceRequestOptions33(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}list(userID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery23(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/organization/users/${userID}/roles`,NextCursorPage,resolveResourceRequestOptions33(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(roleID,params,options){let{user_id}=params;return this._client.delete(path`/organization/users/${user_id}/roles/${roleID}`,resolveResourceRequestOptions33(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});function resolveResourceRequestOptions34(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery24(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys24.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys24.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys24,Users3;var init_users3=__esm(()=>{init_roles6();init_roles6();init_pagination();init_path();normalizeRequestOptionsForQueryKeys24=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Users3=class Users3 extends APIResource{constructor(){super(...arguments);this.roles=new Roles6(this._client)}retrieve(userID,options){return this._client.get(path`/organization/users/${userID}`,resolveResourceRequestOptions34(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}update(userID,body,options){return this._client.post(path`/organization/users/${userID}`,resolveResourceRequestOptions34(options,(options)=>({body,...options,__security:{adminAPIKeyAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery24(query,["after","emails","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/organization/users",ConversationCursorPage,resolveResourceRequestOptions34(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(userID,options){return this._client.delete(path`/organization/users/${userID}`,resolveResourceRequestOptions34(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}};Users3.Roles=Roles6});var Organization;var init_organization=__esm(()=>{init_admin_api_keys();init_admin_api_keys();init_audit_logs();init_audit_logs();init_certificates();init_certificates();init_data_retention();init_data_retention();init_external_keys();init_external_keys();init_external_storage();init_external_storage();init_invites();init_invites();init_roles();init_roles();init_spend_alerts();init_spend_alerts();init_spend_limit();init_spend_limit();init_usage();init_usage();init_groups();init_groups();init_projects();init_projects();init_users3();init_users3();Organization=class Organization extends APIResource{constructor(){super(...arguments);this.auditLogs=new AuditLogs(this._client),this.adminAPIKeys=new AdminAPIKeys(this._client),this.usage=new Usage(this._client),this.invites=new Invites(this._client),this.users=new Users3(this._client),this.groups=new Groups(this._client),this.roles=new Roles(this._client),this.dataRetention=new DataRetention(this._client),this.externalKeys=new ExternalKeys(this._client),this.externalStorage=new ExternalStorage(this._client),this.spendLimit=new SpendLimit(this._client),this.spendAlerts=new SpendAlerts(this._client),this.certificates=new Certificates(this._client),this.projects=new Projects(this._client)}};Organization.AuditLogs=AuditLogs;Organization.AdminAPIKeys=AdminAPIKeys;Organization.Usage=Usage;Organization.Invites=Invites;Organization.Users=Users3;Organization.Groups=Groups;Organization.Roles=Roles;Organization.DataRetention=DataRetention;Organization.ExternalKeys=ExternalKeys;Organization.ExternalStorage=ExternalStorage;Organization.SpendLimit=SpendLimit;Organization.SpendAlerts=SpendAlerts;Organization.Certificates=Certificates;Organization.Projects=Projects});var Admin;var init_admin=__esm(()=>{init_organization();init_organization();Admin=class Admin extends APIResource{constructor(){super(...arguments);this.organization=new Organization(this._client)}};Admin.Organization=Organization});function resolveResourceRequestOptions35(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Speech;var init_speech=__esm(()=>{init_headers();Speech=class Speech extends APIResource{create(body,options){return this._client.post("/audio/speech",resolveResourceRequestOptions35(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"application/octet-stream"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}}});function resolveResourceRequestOptions36(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization2(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}var Transcriptions;var init_transcriptions=__esm(()=>{init_uploads();Transcriptions=class Transcriptions extends APIResource{create(body,options){return this._client.post("/audio/transcriptions",resolveResourceRequestOptions36(options,(options)=>multipartFormRequestOptions(withBodyFinalization2(((request)=>({...request,__metadata:{model:body.model}}))({body,...options,stream:body.stream??!1,__security:{bearerAuth:!0}}),{streamFromBody:!0}),this._client)))}}});function resolveResourceRequestOptions37(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Translations;var init_translations=__esm(()=>{init_uploads();Translations=class Translations extends APIResource{create(body,options){return this._client.post("/audio/translations",resolveResourceRequestOptions37(options,(options)=>multipartFormRequestOptions(((request)=>({...request,__metadata:{model:body.model}}))({body,...options,__security:{bearerAuth:!0}}),this._client)))}}});function resolveResourceRequestOptions38(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery25(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys25.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys25.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys25,VoiceConsents;var init_voice_consents=__esm(()=>{init_pagination();init_uploads();init_path();normalizeRequestOptionsForQueryKeys25=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);VoiceConsents=class VoiceConsents extends APIResource{create(body,options){return this._client.post("/audio/voice_consents",resolveResourceRequestOptions38(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}retrieve(consentID,options){return this._client.get(path`/audio/voice_consents/${consentID}`,resolveResourceRequestOptions38(options,(options)=>({...options,__security:{bearerAuth:!0}})))}update(consentID,body,options){return this._client.post(path`/audio/voice_consents/${consentID}`,resolveResourceRequestOptions38(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery25(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/audio/voice_consents",CursorPage,resolveResourceRequestOptions38(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(consentID,options){return this._client.delete(path`/audio/voice_consents/${consentID}`,resolveResourceRequestOptions38(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions39(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Voices;var init_voices=__esm(()=>{init_uploads();init_path();Voices=class Voices extends APIResource{create(body,options){return this._client.post("/audio/voices",resolveResourceRequestOptions39(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}delete(voiceID,options){return this._client.delete(path`/audio/voices/${voiceID}`,resolveResourceRequestOptions39(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});var Audio;var init_audio=__esm(()=>{init_speech();init_speech();init_transcriptions();init_transcriptions();init_translations();init_translations();init_voice_consents();init_voice_consents();init_voices();init_voices();Audio=class Audio extends APIResource{constructor(){super(...arguments);this.transcriptions=new Transcriptions(this._client),this.translations=new Translations(this._client),this.speech=new Speech(this._client),this.voices=new Voices(this._client),this.voiceConsents=new VoiceConsents(this._client)}};Audio.Transcriptions=Transcriptions;Audio.Translations=Translations;Audio.Speech=Speech;Audio.Voices=Voices;Audio.VoiceConsents=VoiceConsents});function resolveResourceRequestOptions40(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery26(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys26.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys26.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys26,Batches;var init_batches=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys26=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Batches=class Batches extends APIResource{create(body,options){return this._client.post("/batches",resolveResourceRequestOptions40(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(batchID,options){return this._client.get(path`/batches/${batchID}`,resolveResourceRequestOptions40(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery26(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/batches",CursorPage,resolveResourceRequestOptions40(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}cancel(batchID,options){return this._client.post(path`/batches/${batchID}/cancel`,resolveResourceRequestOptions40(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions41(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery27(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys27.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys27.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys27,Assistants;var init_assistants=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys27=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Assistants=class Assistants extends APIResource{create(body,options){return this._client.post("/assistants",resolveResourceRequestOptions41(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(assistantID,options){return this._client.get(path`/assistants/${assistantID}`,resolveResourceRequestOptions41(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}update(assistantID,body,options){return this._client.post(path`/assistants/${assistantID}`,resolveResourceRequestOptions41(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery27(query,["after","before","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/assistants",CursorPage,resolveResourceRequestOptions41(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}delete(assistantID,options){return this._client.delete(path`/assistants/${assistantID}`,resolveResourceRequestOptions41(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions42(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery28(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys28.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys28.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys28,Invocations;var init_invocations=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys28=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Invocations=class Invocations extends APIResource{create(automationID,options){return this._client.post(path`/agents/automations/${automationID}/invocations`,resolveResourceRequestOptions42(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(invocationID,params,options){let{automation_id}=params;return this._client.get(path`/agents/automations/${automation_id}/invocations/${invocationID}`,resolveResourceRequestOptions42(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(automationID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery28(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/agents/automations/${automationID}/invocations`,CursorPage,resolveResourceRequestOptions42(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions43(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery29(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys29.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys29.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys29,Automations;var init_automations=__esm(()=>{init_invocations();init_invocations();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys29=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Automations=class Automations extends APIResource{constructor(){super(...arguments);this.invocations=new Invocations(this._client)}create(body,options){return this._client.post("/agents/automations",resolveResourceRequestOptions43(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(automationID,options){return this._client.get(path`/agents/automations/${automationID}`,resolveResourceRequestOptions43(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}update(automationID,body,options){return this._client.post(path`/agents/automations/${automationID}`,resolveResourceRequestOptions43(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery29(query,["after","limit","order","session_id"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/agents/automations",CursorPage,resolveResourceRequestOptions43(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(automationID,options){return this._client.delete(path`/agents/automations/${automationID}`,resolveResourceRequestOptions43(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}pause(automationID,options){return this._client.post(path`/agents/automations/${automationID}/pause`,resolveResourceRequestOptions43(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}resume(automationID,options){return this._client.post(path`/agents/automations/${automationID}/resume`,resolveResourceRequestOptions43(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};Automations.Invocations=Invocations});function validateAgentFilePath(path){let parts=path.split("/"),root=parts[2]??"";if(!path.startsWith("/workspace/")||path.includes("\\")||path.includes("\x00")||parts.slice(1).some((part)=>part===""||part==="."||part==="..")||root===".codex"||root===".managed-agents"||root.startsWith(".managed-agents-")||path==="/workspace/outputs")throw new OpenAIError("Agent files require a non-reserved absolute file path inside /workspace")}function preflight(files,options){let entries=Object.entries(files),headers=buildHeaders([options.headers]);if(entries.length>1&&(headers.values.has("idempotency-key")||!headers.nulls.has("idempotency-key")&&options?.idempotencyKey!==void 0))throw new OpenAIError("Do not reuse an Idempotency-Key across multiple file uploads");let paths={children:new Map};for(let[path]of entries){validateAgentFilePath(path);let node=paths;for(let part of path.split("/")){if(node.file)throw new OpenAIError("Agent file destinations conflict");let child=node.children.get(part);if(!child)child={children:new Map},node.children.set(part,child);node=child}if(node.children.size>0)throw new OpenAIError("Agent file destinations conflict");node.file=!0}return entries}async function prepareAgentFiles(client,files,options){let requestOptions={...options},headers=buildHeaders([client._options.defaultHeaders,requestOptions.headers]);requestOptions.headers=headers;let entries=preflight(files,requestOptions);if(entries.length>1)headers.nulls.add("idempotency-key");let prepared={files:[],uploadedFiles:[]};try{for(let[path,file]of entries){let uploaded=await client.files.create({file,purpose:"user_data"},requestOptions);prepared.uploadedFiles.push(uploaded),prepared.files.push({type:"file_id",file_id:uploaded.id,path})}return prepared}catch(error){throw new AgentFileUploadError(prepared.uploadedFiles,error)}}async function uploadAgentFile(client,resource,environmentID,params,options){let prepared=await prepareAgentFiles(client,{[params.path]:params.file},options),[reference]=prepared.files,[uploadedFile]=prepared.uploadedFiles;if(!reference||!uploadedFile)throw new OpenAIError("Missing prepared agent file");try{return{uploadedFile,environmentFile:await resource.create(environmentID,reference,options)}}catch(error){throw new AgentFileUploadError(prepared.uploadedFiles,error)}}var AgentFileUploadError;var init_files=__esm(()=>{init_error();init_headers();AgentFileUploadError=class AgentFileUploadError extends OpenAIError{constructor(uploadedFiles,cause){super("Agent file preparation or staging failed; uploaded files remain caller-owned.");this.name="AgentFileUploadError",this.uploadedFiles=uploadedFiles,Object.defineProperty(this,"cause",{value:cause,configurable:!0})}}});function resolveResourceRequestOptions44(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Files;var init_files2=__esm(()=>{init_pagination();init_headers();init_path();init_files();Files=class Files extends APIResource{create(environmentID,body,options){return this._client.post(path`/agents/environments/${environmentID}/files`,resolveResourceRequestOptions44(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(environmentID,query={},options){return this._client.getAPIList(path`/agents/environments/${environmentID}/files`,TokenPage,resolveResourceRequestOptions44(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}prepare(files,options){return prepareAgentFiles(this._client,files,options)}upload(environmentID,params,options){return uploadAgentFile(this._client,this,environmentID,params,options)}}});function resolveResourceRequestOptions45(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery30(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys30.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys30.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys30,Templates;var init_templates=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys30=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Templates=class Templates extends APIResource{create(body={},options){return this._client.post("/agents/environments/templates",resolveResourceRequestOptions45(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(environmentTemplateID,options){return this._client.get(path`/agents/environments/templates/${environmentTemplateID}`,resolveResourceRequestOptions45(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}update(environmentTemplateID,body={},options){return this._client.post(path`/agents/environments/templates/${environmentTemplateID}`,resolveResourceRequestOptions45(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery30(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/agents/environments/templates",CursorPage,resolveResourceRequestOptions45(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(environmentTemplateID,options){return this._client.delete(path`/agents/environments/templates/${environmentTemplateID}`,resolveResourceRequestOptions45(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions46(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery31(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys31.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys31.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys31,Environments,EnvironmentInfosPage;var init_environments=__esm(()=>{init_files2();init_files2();init_templates();init_templates();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys31=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Environments=class Environments extends APIResource{constructor(){super(...arguments);this.files=new Files(this._client),this.templates=new Templates(this._client)}create(params,options){let{"Idempotency-Key":idempotencyKey,...body}=params;return this._client.post("/agents/environments",resolveResourceRequestOptions46(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1",...idempotencyKey!=null?{"Idempotency-Key":idempotencyKey}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(environmentID,options){return this._client.get(path`/agents/environments/${environmentID}`,resolveResourceRequestOptions46(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery31(query,["after","limit","order","type"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/agents/environments",EnvironmentInfosPage,resolveResourceRequestOptions46(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};EnvironmentInfosPage=class EnvironmentInfosPage extends CursorPage{constructor(client,response,body,options){super(client,response,body,options);this.object=body.object,this.first_id=body.first_id,this.last_id=body.last_id}};Environments.Files=Files;Environments.Templates=Templates});async function*agentItems(load){let after;while(!0){let page=await load(after);if(yield*page.data,!page.has_more)return;let body=page.body,last=page.data[page.data.length-1],cursor=isObj(body)&&typeof body.last_id==="string"?body.last_id:last?.id;if(!cursor||cursor===after)throw new OpenAIError("Agent pagination cannot advance to the next page");after=cursor}}var init_pages=__esm(()=>{init_error();init_values()});class AgentResultArtifacts{constructor(resource,result){_AgentResultArtifacts_resource.set(this,void 0),_AgentResultArtifacts_sessionID.set(this,void 0),_AgentResultArtifacts_turnID.set(this,void 0),__classPrivateFieldSet(this,_AgentResultArtifacts_resource,resource,"f"),__classPrivateFieldSet(this,_AgentResultArtifacts_sessionID,result.session_id,"f"),__classPrivateFieldSet(this,_AgentResultArtifacts_turnID,result.turn_id,"f")}async retrieve(path,options){let selected;for await(let artifact of agentItems((after)=>__classPrivateFieldGet(this,_AgentResultArtifacts_resource,"f").list(__classPrivateFieldGet(this,_AgentResultArtifacts_sessionID,"f"),{},{...options,query:{...options?.query,after,environment_id:void 0}})))if(artifact.session_id===__classPrivateFieldGet(this,_AgentResultArtifacts_sessionID,"f")&&artifact.turn_id===__classPrivateFieldGet(this,_AgentResultArtifacts_turnID,"f")&&artifact.path===path){if(selected)throw new OpenAIError("Multiple artifacts match this result and path");selected=artifact}if(!selected)throw new OpenAIError("No artifact matches this result and path");return selected}async content(path,options){let artifact=await this.retrieve(path,options);return __classPrivateFieldGet(this,_AgentResultArtifacts_resource,"f").content(artifact.id,{session_id:__classPrivateFieldGet(this,_AgentResultArtifacts_sessionID,"f")},options)}async download(params,options){let{path,to}=params,artifact=await this.retrieve(path,options),response=await __classPrivateFieldGet(this,_AgentResultArtifacts_resource,"f").content(artifact.id,{session_id:__classPrivateFieldGet(this,_AgentResultArtifacts_sessionID,"f")},options);if(!response.body)throw new OpenAIError("Artifact response has no content stream");try{await response.body.pipeTo(to,options?.signal?{signal:options.signal}:{})}catch(error){try{await response.body.cancel()}catch{}throw error}return artifact}}var _AgentResultArtifacts_resource,_AgentResultArtifacts_sessionID,_AgentResultArtifacts_turnID;var init_result_artifacts=__esm(()=>{init_tslib();init_pages();init_error();_AgentResultArtifacts_resource=new WeakMap,_AgentResultArtifacts_sessionID=new WeakMap,_AgentResultArtifacts_turnID=new WeakMap});function resolveResourceRequestOptions47(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery32(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys32.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys32.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys32,Artifacts;var init_artifacts=__esm(()=>{init_pagination();init_headers();init_path();init_result_artifacts();normalizeRequestOptionsForQueryKeys32=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Artifacts=class Artifacts extends APIResource{retrieve(artifactID,params,options){let{session_id}=params;return this._client.get(path`/agents/sessions/${session_id}/artifacts/${artifactID}`,resolveResourceRequestOptions47(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(sessionID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery32(query,["after","environment_id","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/agents/sessions/${sessionID}/artifacts`,CursorPage,resolveResourceRequestOptions47(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(artifactID,params,options){let{session_id}=params;return this._client.delete(path`/agents/sessions/${session_id}/artifacts/${artifactID}`,resolveResourceRequestOptions47(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}content(artifactID,params,options){let{session_id}=params;return this._client.get(path`/agents/sessions/${session_id}/artifacts/${artifactID}/content`,resolveResourceRequestOptions47(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}forResult(result){return new AgentResultArtifacts(this,result)}}});function resolveResourceRequestOptions48(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Events;var init_events=__esm(()=>{init_headers();init_path();Events=class Events extends APIResource{create(sessionID,params,options){let{"Idempotency-Key":idempotencyKey,...body}=params;return this._client.post(path`/agents/sessions/${sessionID}/events`,resolveResourceRequestOptions48(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...idempotencyKey!=null?{"Idempotency-Key":idempotencyKey}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}stream(sessionID,options){return this._client.get(path`/agents/sessions/${sessionID}/events`,resolveResourceRequestOptions48(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},options?.headers]),stream:!0,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions49(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery33(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys33.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys33.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys33,Items;var init_items=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys33=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Items=class Items extends APIResource{list(sessionID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery33(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/agents/sessions/${sessionID}/items`,CursorPage,resolveResourceRequestOptions49(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions50(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery34(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys34.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys34.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys34,Traces;var init_traces=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys34=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Traces=class Traces extends APIResource{list(sessionID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery34(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/agents/sessions/${sessionID}/traces`,CursorPage,resolveResourceRequestOptions50(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions51(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Items2;var init_items2=__esm(()=>{init_pagination();init_headers();init_path();Items2=class Items2 extends APIResource{list(subagentID,params,options){let{session_id,...query}=params;return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagentID}/items`,CursorPage,resolveResourceRequestOptions51(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions52(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Items3;var init_items3=__esm(()=>{init_pagination();init_headers();init_path();Items3=class Items3 extends APIResource{list(turnID,params,options){let{session_id,subagent_id,...query}=params;return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagent_id}/turns/${turnID}/items`,CursorPage,resolveResourceRequestOptions52(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions53(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Turns;var init_turns=__esm(()=>{init_items3();init_items3();init_pagination();init_headers();init_path();Turns=class Turns extends APIResource{constructor(){super(...arguments);this.items=new Items3(this._client)}retrieve(turnID,params,options){let{session_id,subagent_id}=params;return this._client.get(path`/agents/sessions/${session_id}/subagents/${subagent_id}/turns/${turnID}`,resolveResourceRequestOptions53(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(subagentID,params,options){let{session_id,...query}=params;return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagentID}/turns`,CursorPage,resolveResourceRequestOptions53(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};Turns.Items=Items3});function resolveResourceRequestOptions54(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery35(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys35.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys35.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys35,Subagents;var init_subagents=__esm(()=>{init_items2();init_items2();init_turns();init_turns();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys35=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Subagents=class Subagents extends APIResource{constructor(){super(...arguments);this.items=new Items2(this._client),this.turns=new Turns(this._client)}retrieve(subagentID,params,options){let{session_id}=params;return this._client.get(path`/agents/sessions/${session_id}/subagents/${subagentID}`,resolveResourceRequestOptions54(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(sessionID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery35(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/agents/sessions/${sessionID}/subagents`,CursorPage,resolveResourceRequestOptions54(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};Subagents.Items=Items2;Subagents.Turns=Turns});function resolveResourceRequestOptions55(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Items4;var init_items4=__esm(()=>{init_pagination();init_headers();init_path();Items4=class Items4 extends APIResource{list(turnID,params,options){let{session_id,...query}=params;return this._client.getAPIList(path`/agents/sessions/${session_id}/turns/${turnID}/items`,ConversationCursorPage,resolveResourceRequestOptions55(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions56(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery36(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys36.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys36.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys36,Turns2;var init_turns2=__esm(()=>{init_items4();init_items4();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys36=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Turns2=class Turns2 extends APIResource{constructor(){super(...arguments);this.items=new Items4(this._client)}retrieve(turnID,params,options){let{session_id}=params;return this._client.get(path`/agents/sessions/${session_id}/turns/${turnID}`,resolveResourceRequestOptions56(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(sessionID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery36(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/agents/sessions/${sessionID}/turns`,CursorPage,resolveResourceRequestOptions56(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};Turns2.Items=Items4});class TurnState{constructor(){_TurnState_turnID.set(this,void 0),_TurnState_turnEnded.set(this,!1),_TurnState_eventIDs.set(this,new Set),_TurnState_calls.set(this,new Set)}accept(event){if(__classPrivateFieldGet(this,_TurnState_eventIDs,"f").has(event.event_id))return!1;if(__classPrivateFieldGet(this,_TurnState_eventIDs,"f").size===1024){let oldest=__classPrivateFieldGet(this,_TurnState_eventIDs,"f").values().next();if(!oldest.done)__classPrivateFieldGet(this,_TurnState_eventIDs,"f").delete(oldest.value)}if(__classPrivateFieldGet(this,_TurnState_eventIDs,"f").add(event.event_id),event.type==="agent.session.turn.created"&&event.turn.subagent_id===null&&__classPrivateFieldGet(this,_TurnState_turnID,"f")===void 0)__classPrivateFieldSet(this,_TurnState_turnID,event.turn_id,"f");if((event.type==="agent.session.turn.completed"||event.type==="agent.session.turn.failed"||event.type==="agent.session.turn.cancelled")&&__classPrivateFieldGet(this,_TurnState_turnID,"f")!==void 0&&event.turn_id===__classPrivateFieldGet(this,_TurnState_turnID,"f"))__classPrivateFieldSet(this,_TurnState_turnEnded,!0,"f");return!0}terminal(event){return event.type==="agent.session.failed"||event.type==="agent.session.idle"&&__classPrivateFieldGet(this,_TurnState_turnEnded,"f")}call(event){if(event.type!=="agent.session.turn.item.added"||event.item.type!=="function_call")return;let call=event.item,key=JSON.stringify([call.turn_id,call.call_id]);if(__classPrivateFieldGet(this,_TurnState_calls,"f").has(key))return;return __classPrivateFieldGet(this,_TurnState_calls,"f").add(key),call}}var _TurnState_turnID,_TurnState_turnEnded,_TurnState_eventIDs,_TurnState_calls;var init_turn_state=__esm(()=>{init_tslib();_TurnState_turnID=new WeakMap,_TurnState_turnEnded=new WeakMap,_TurnState_eventIDs=new WeakMap,_TurnState_calls=new WeakMap});function isInputContent(value){if(!isObj(value))return!1;let content=value,field;if(content.type==="input_text")field="text";else if(content.type==="input_image")field="image_url";else return!1;return hasOwn(content,"type")&&hasOwn(content,field)&&typeof content[field]==="string"}var init_tool_output=__esm(()=>{init_values()});var toolStages;var init_tool_stages=__esm(()=>{toolStages=Symbol.for("openai.beta.agents.toolStages")});function normalizedOutput(value){if(value===null)return null;if(typeof value==="string"||Array.isArray(value)&&value.every(isInputContent))return value;throw new OpenAIError("Tool output must be text, content, a JSON object, or null")}function toolResult(call,value){let output=isObj(value)?JSON.stringify(value):value,serialized=JSON.stringify(output);if(serialized===void 0)throw new OpenAIError("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:call.turn_id,call_id:call.call_id,success:!0,output:normalizedOutput(typeof output==="string"?output:JSON.parse(serialized))}}class AgentToolDispatcher{constructor(sessions,handlers,controller,options,onToolError){_AgentToolDispatcher_instances.add(this),_AgentToolDispatcher_handlers.set(this,void 0),_AgentToolDispatcher_options.set(this,void 0),_AgentToolDispatcher_sessions.set(this,void 0),_AgentToolDispatcher_controller.set(this,void 0),_AgentToolDispatcher_onToolError.set(this,void 0),__classPrivateFieldSet(this,_AgentToolDispatcher_sessions,sessions,"f"),__classPrivateFieldSet(this,_AgentToolDispatcher_controller,controller,"f"),__classPrivateFieldSet(this,_AgentToolDispatcher_onToolError,onToolError,"f"),__classPrivateFieldSet(this,_AgentToolDispatcher_handlers,new Map(Object.entries(handlers)),"f");let headers=buildHeaders([options?.headers]);headers.values.delete("idempotency-key"),headers.nulls.delete("idempotency-key");let{idempotencyKey:_key,...rest}=options??{};__classPrivateFieldSet(this,_AgentToolDispatcher_options,{...rest,headers,signal:controller.signal},"f")}canHandle(name){return typeof __classPrivateFieldGet(this,_AgentToolDispatcher_handlers,"f").get(name)==="function"}prepare(call,sessionID){let handler=call&&__classPrivateFieldGet(this,_AgentToolDispatcher_handlers,"f").get(call.name);if(!call||typeof handler!=="function")return;if(!sessionID)throw new OpenAIError("Tool call received before the session creation event");let snapshot=structuredClone(call);return async()=>{__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_checkAbort).call(this);let result=await __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_result).call(this,snapshot,handler,sessionID);__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_checkAbort).call(this),await __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_submit).call(this,sessionID,result)}}}var _AgentToolDispatcher_instances,_AgentToolDispatcher_handlers,_AgentToolDispatcher_options,_AgentToolDispatcher_sessions,_AgentToolDispatcher_controller,_AgentToolDispatcher_onToolError,_AgentToolDispatcher_result,_AgentToolDispatcher_checkAbort,_AgentToolDispatcher_abortError,_AgentToolDispatcher_wait,_AgentToolDispatcher_submit;var init_tool_dispatcher=__esm(()=>{init_tslib();init_error();init_headers();init_values();init_tool_output();init_tool_stages();_AgentToolDispatcher_handlers=new WeakMap,_AgentToolDispatcher_options=new WeakMap,_AgentToolDispatcher_sessions=new WeakMap,_AgentToolDispatcher_controller=new WeakMap,_AgentToolDispatcher_onToolError=new WeakMap,_AgentToolDispatcher_instances=new WeakSet,_AgentToolDispatcher_result=async function(call,handler,sessionID){let stage="arguments";try{let args=typeof call.arguments==="string"?JSON.parse(call.arguments):call.arguments;if(!isObj(args))throw new OpenAIError("Function arguments must be a JSON object");stage="execution";let arguments_=args,output=await __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_wait).call(this,()=>__classPrivateFieldGet(this,_AgentToolDispatcher_onToolError,"f")&&handler[toolStages]?handler(arguments_,(value)=>{stage=value}):handler(arguments_));return stage="output",toolResult(call,output)}catch(error){if(__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_checkAbort).call(this),__classPrivateFieldGet(this,_AgentToolDispatcher_onToolError,"f")){let failure=Object.freeze({error,stage,tool_name:call.name,session_id:sessionID,turn_id:call.turn_id,call_id:call.call_id});try{await __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_wait).call(this,()=>__classPrivateFieldGet(this,_AgentToolDispatcher_onToolError,"f")?.call(this,failure))}catch{__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_checkAbort).call(this)}}return{type:"agent.session.input.tool_result",turn_id:call.turn_id,call_id:call.call_id,success:!1,error:"Tool handler failed."}}},_AgentToolDispatcher_checkAbort=function(){if(__classPrivateFieldGet(this,_AgentToolDispatcher_controller,"f").signal.aborted)throw __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_abortError).call(this)},_AgentToolDispatcher_abortError=function(){let error=new APIUserAbortError;return Object.defineProperty(error,"cause",{value:__classPrivateFieldGet(this,_AgentToolDispatcher_controller,"f").signal.reason,writable:!0,configurable:!0}),error},_AgentToolDispatcher_wait=async function(action){let onAbort,aborted=new Promise((_resolve,reject)=>{onAbort=()=>reject(__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_abortError).call(this)),__classPrivateFieldGet(this,_AgentToolDispatcher_controller,"f").signal.addEventListener("abort",onAbort,{once:!0})});try{__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_checkAbort).call(this);let invoke=async()=>await action();return await Promise.race([invoke(),aborted])}finally{if(onAbort)__classPrivateFieldGet(this,_AgentToolDispatcher_controller,"f").signal.removeEventListener("abort",onAbort)}},_AgentToolDispatcher_submit=async function _AgentToolDispatcher_submit(sessionID,result,key=uuid4(),attempt=0){__classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_checkAbort).call(this);try{await __classPrivateFieldGet(this,_AgentToolDispatcher_sessions,"f").events.create(sessionID,{events:[result],"Idempotency-Key":key},__classPrivateFieldGet(this,_AgentToolDispatcher_options,"f"))}catch(error){let delay=[100,300,600][attempt];if(delay===void 0||!(error instanceof BadRequestError)||error.code!=="invalid_request_error"||!error.error||!("message"in error.error)||error.error.message!==`Unknown pending tool call: ${result.call_id}`)throw error;let timer;try{await __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_wait).call(this,()=>new Promise((resolve)=>{timer=setTimeout(resolve,delay)}))}finally{if(timer!==void 0)clearTimeout(timer)}await __classPrivateFieldGet(this,_AgentToolDispatcher_instances,"m",_AgentToolDispatcher_submit).call(this,sessionID,result,key,attempt+1)}}});function outputText(message){return message.content.map((block)=>block.type==="output_text"?block.text:"").join("")}class AgentTurnResult{constructor(turn,messages){this.turn=turn,this.messages=messages}get session_id(){return this.turn.session_id}get turn_id(){return this.turn.id}get output_text(){return this.messages.map(outputText).join("")}}var init_agent_turn_result=()=>{};var ParsedAgentTurnResult;var init_parsed_agent_turn_result=__esm(()=>{init_agent_turn_result();ParsedAgentTurnResult=class ParsedAgentTurnResult extends AgentTurnResult{constructor(result,parsed){super(result.turn,result.messages);this.raw_result=result,this.output_parsed=parsed}}});var _AgentOutputParseError_rawResult,AgentOutputParseError;var init_output_parse_error=__esm(()=>{init_tslib();init_error();AgentOutputParseError=class AgentOutputParseError extends OpenAIError{constructor(result){super("The completed agent output could not be parsed");this.name="AgentOutputParseError",_AgentOutputParseError_rawResult.set(this,void 0),__classPrivateFieldSet(this,_AgentOutputParseError_rawResult,result,"f")}get raw_result(){return __classPrivateFieldGet(this,_AgentOutputParseError_rawResult,"f")}};_AgentOutputParseError_rawResult=new WeakMap});function parseAgentResult(result,format){try{if(!format)return result;let first;for(let message of result.messages)for(let content of message.content)if(content.type==="output_text"){let value=format.$parseRaw(content.text);first??(first={value})}if(!first)throw new AgentOutputParseError(result);return new ParsedAgentTurnResult(result,first.value)}catch{throw new AgentOutputParseError(result)}}function ownJSONValue(object,key){let descriptor=object&&Object.getOwnPropertyDescriptor(object,key);return descriptor?.enumerable&&"value"in descriptor?descriptor.value:void 0}function agentFormatParser(format){if(!format)return;let descriptor=Object.getOwnPropertyDescriptor(format,"$parseRaw");if(!descriptor||!("value"in descriptor)||typeof descriptor.value!=="function")return;let schema=ownJSONValue(format,"schema");if(ownJSONValue(format,"type")!=="json_schema"||!schema)throw new OpenAIError("Typed agent formats require own enumerable type and schema data properties");let parse=descriptor.value;return{type:"json_schema",schema,$parseRaw:(text)=>parse.call(format,text)}}function snapshotJSONProperty(object,key,capture=(value)=>value){let descriptor=Object.getOwnPropertyDescriptor(object,key);if(!descriptor?.enumerable)return object;let value=capture(object[key]);if("value"in descriptor&&value===descriptor.value)return object;return Object.create(Object.getPrototypeOf(object),{...Object.getOwnPropertyDescriptors(object),[key]:{value,enumerable:!0,configurable:descriptor.configurable,writable:!0}})}function captureAgentOutput(input,options){let body=snapshotJSONProperty(input,"agent",(agent)=>agent?snapshotJSONProperty(agent,"text",(text)=>text?snapshotJSONProperty(text,"format"):text):agent),agent=ownJSONValue(body,"agent"),text=ownJSONValue(agent,"text"),format=agentFormatParser(ownJSONValue(text,"format"));if(!format)return{body,options};let schema=structuredClone(format.schema);for(let envelope of[body,agent,text])if(envelope&&"toJSON"in envelope)throw new OpenAIError("Typed agent requests cannot customize body, agent, or text serialization");let capturedOptions={...options};if(ownJSONValue(capturedOptions,"body")!==void 0)throw new OpenAIError("Typed agent requests cannot override the body in request options");return delete capturedOptions.body,{options:capturedOptions,body:{...body,agent:{...agent,text:{...text,format:{type:"json_schema",schema}}}},format}}async function parseAgentResultPromise(result,format){return parseAgentResult(await result,format)}var init_parse_result=__esm(()=>{init_error();init_parsed_agent_turn_result();init_output_parse_error()});var AgentTurnResultError;var init_agent_turn_result_error=__esm(()=>{init_error();AgentTurnResultError=class AgentTurnResultError extends OpenAIError{constructor(reason,session_id,turn,messages,required_actions=[],cause){super(`Could not collect the agent turn result: ${reason}`);this.name="AgentTurnResultError",this.reason=reason,this.session_id=session_id,this.turn=turn,this.messages=messages,this.required_actions=required_actions,this.cause=cause}get turn_id(){return this.turn?.id}}});class AgentTurnResultCollector{constructor(sessionID){_AgentTurnResultCollector_instances.add(this),_AgentTurnResultCollector_sessionID.set(this,void 0),_AgentTurnResultCollector_turn.set(this,void 0),_AgentTurnResultCollector_messages.set(this,new Map),_AgentTurnResultCollector_requiredActions.set(this,[]),_AgentTurnResultCollector_checkedActionsFor.set(this,void 0),_AgentTurnResultCollector_sessionFailed.set(this,!1),_AgentTurnResultCollector_terminal.set(this,!1),_AgentTurnResultCollector_idle.set(this,!1),__classPrivateFieldSet(this,_AgentTurnResultCollector_sessionID,sessionID,"f")}accept(event){if(this.ready)return;if("session"in event)__classPrivateFieldSet(this,_AgentTurnResultCollector_sessionID,__classPrivateFieldGet(this,_AgentTurnResultCollector_sessionID,"f")??event.session.id,"f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_requiredActions,structuredClone(event.session.required_actions??[]),"f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_checkedActionsFor,void 0,"f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_sessionFailed,__classPrivateFieldGet(this,_AgentTurnResultCollector_sessionFailed,"f")||event.type==="agent.session.failed","f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_idle,__classPrivateFieldGet(this,_AgentTurnResultCollector_idle,"f")||event.type==="agent.session.idle"&&__classPrivateFieldGet(this,_AgentTurnResultCollector_terminal,"f"),"f");if(event.type==="agent.session.turn.created"&&event.turn.subagent_id===null&&!__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f"))__classPrivateFieldSet(this,_AgentTurnResultCollector_turn,structuredClone(event.turn),"f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_sessionID,event.turn.session_id,"f");let turnID="turn_id"in event?event.turn_id:void 0;if("item"in event)turnID=event.item.turn_id;if(!__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f")||turnID!==__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f").id)return;__classPrivateFieldGet(this,_AgentTurnResultCollector_instances,"m",_AgentTurnResultCollector_acceptTurn).call(this,event)}error(reason,cause){return new AgentTurnResultError(reason,__classPrivateFieldGet(this,_AgentTurnResultCollector_sessionID,"f"),__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f"),__classPrivateFieldGet(this,_AgentTurnResultCollector_instances,"m",_AgentTurnResultCollector_finalMessages).call(this),__classPrivateFieldGet(this,_AgentTurnResultCollector_requiredActions,"f"),cause)}checkAction(canHandle){if(__classPrivateFieldGet(this,_AgentTurnResultCollector_sessionFailed,"f")||__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f")?.status==="failed")throw this.error("failed");if(__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f")?.status==="cancelled")throw this.error("cancelled");if(__classPrivateFieldGet(this,_AgentTurnResultCollector_checkedActionsFor,"f")===canHandle)return;if(__classPrivateFieldGet(this,_AgentTurnResultCollector_requiredActions,"f").some((action)=>action.type!=="function_call"||!canHandle(action.name)))throw this.error("requires_action");__classPrivateFieldSet(this,_AgentTurnResultCollector_checkedActionsFor,canHandle,"f")}get ready(){return __classPrivateFieldGet(this,_AgentTurnResultCollector_terminal,"f")&&__classPrivateFieldGet(this,_AgentTurnResultCollector_idle,"f")}release(){__classPrivateFieldGet(this,_AgentTurnResultCollector_messages,"f").clear(),__classPrivateFieldSet(this,_AgentTurnResultCollector_requiredActions,[],"f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_checkedActionsFor,void 0,"f")}finish(){if(this.checkAction(()=>this.ready),!__classPrivateFieldGet(this,_AgentTurnResultCollector_terminal,"f")||__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f")?.status!=="completed"||!__classPrivateFieldGet(this,_AgentTurnResultCollector_idle,"f"))throw this.error("observation");return new AgentTurnResult(__classPrivateFieldGet(this,_AgentTurnResultCollector_turn,"f"),__classPrivateFieldGet(this,_AgentTurnResultCollector_instances,"m",_AgentTurnResultCollector_finalMessages).call(this))}}var _AgentTurnResultCollector_instances,_AgentTurnResultCollector_sessionID,_AgentTurnResultCollector_turn,_AgentTurnResultCollector_messages,_AgentTurnResultCollector_requiredActions,_AgentTurnResultCollector_checkedActionsFor,_AgentTurnResultCollector_sessionFailed,_AgentTurnResultCollector_terminal,_AgentTurnResultCollector_idle,_AgentTurnResultCollector_acceptTurn,_AgentTurnResultCollector_acceptOutput,_AgentTurnResultCollector_finalMessages;var init_agent_turn_result_collector=__esm(()=>{init_tslib();init_agent_turn_result();init_agent_turn_result_error();_AgentTurnResultCollector_sessionID=new WeakMap,_AgentTurnResultCollector_turn=new WeakMap,_AgentTurnResultCollector_messages=new WeakMap,_AgentTurnResultCollector_requiredActions=new WeakMap,_AgentTurnResultCollector_checkedActionsFor=new WeakMap,_AgentTurnResultCollector_sessionFailed=new WeakMap,_AgentTurnResultCollector_terminal=new WeakMap,_AgentTurnResultCollector_idle=new WeakMap,_AgentTurnResultCollector_instances=new WeakSet,_AgentTurnResultCollector_acceptTurn=function(event){if("turn"in event)__classPrivateFieldSet(this,_AgentTurnResultCollector_turn,structuredClone(event.turn),"f"),__classPrivateFieldSet(this,_AgentTurnResultCollector_terminal,__classPrivateFieldGet(this,_AgentTurnResultCollector_terminal,"f")||(event.type==="agent.session.turn.completed"||event.type==="agent.session.turn.failed"||event.type==="agent.session.turn.cancelled"),"f");__classPrivateFieldGet(this,_AgentTurnResultCollector_instances,"m",_AgentTurnResultCollector_acceptOutput).call(this,event)},_AgentTurnResultCollector_acceptOutput=function(event){if(event.type!=="agent.session.turn.item.done"||event.item.type!=="message"||event.item.status!=="completed"||event.item.phase==="commentary"||__classPrivateFieldGet(this,_AgentTurnResultCollector_messages,"f").has(event.item.id))return;__classPrivateFieldGet(this,_AgentTurnResultCollector_messages,"f").set(event.item.id,{index:event.output_index,message:structuredClone(event.item)})},_AgentTurnResultCollector_finalMessages=function(){return[...__classPrivateFieldGet(this,_AgentTurnResultCollector_messages,"f").values()].sort((a,b)=>a.index-b.index).map(({message})=>message)}});class ResultCollection{constructor(source,canHandle=()=>!1,sessionID,signal){_ResultCollection_instances.add(this),_ResultCollection_iterator.set(this,void 0),_ResultCollection_ended.set(this,!1),_ResultCollection_enabled.set(this,!1),_ResultCollection_uncollectedEvents.set(this,!1),_ResultCollection_error.set(this,void 0),_ResultCollection_result.set(this,void 0),_ResultCollection_source.set(this,void 0),_ResultCollection_signal.set(this,void 0),_ResultCollection_canHandle.set(this,void 0),__classPrivateFieldSet(this,_ResultCollection_source,source,"f"),__classPrivateFieldSet(this,_ResultCollection_signal,signal,"f"),__classPrivateFieldSet(this,_ResultCollection_canHandle,canHandle,"f"),this.collector=new AgentTurnResultCollector(sessionID)}enable(){if(!__classPrivateFieldGet(this,_ResultCollection_enabled,"f")&&__classPrivateFieldGet(this,_ResultCollection_uncollectedEvents,"f"))throw new OpenAIError("Call withResultCollection() before consuming events, or call finalResult() on a fresh stream.");__classPrivateFieldSet(this,_ResultCollection_enabled,!0,"f")}iterate(){if(__classPrivateFieldGet(this,_ResultCollection_iterator,"f"))throw new OpenAIError("An agent result stream can only be consumed once");return __classPrivateFieldSet(this,_ResultCollection_iterator,__classPrivateFieldGet(this,_ResultCollection_instances,"m",_ResultCollection_observe).call(this),"f")}finalResult(){return __classPrivateFieldSet(this,_ResultCollection_result,__classPrivateFieldGet(this,_ResultCollection_result,"f")??__classPrivateFieldGet(this,_ResultCollection_instances,"m",_ResultCollection_collect).call(this),"f")}}var _ResultCollection_instances,_ResultCollection_iterator,_ResultCollection_ended,_ResultCollection_enabled,_ResultCollection_uncollectedEvents,_ResultCollection_error,_ResultCollection_result,_ResultCollection_source,_ResultCollection_signal,_ResultCollection_canHandle,_ResultCollection_observe,_ResultCollection_collect;var init_result_collection=__esm(()=>{init_tslib();init_error();init_agent_turn_result_collector();init_agent_turn_result_error();_ResultCollection_iterator=new WeakMap,_ResultCollection_ended=new WeakMap,_ResultCollection_enabled=new WeakMap,_ResultCollection_uncollectedEvents=new WeakMap,_ResultCollection_error=new WeakMap,_ResultCollection_result=new WeakMap,_ResultCollection_source=new WeakMap,_ResultCollection_signal=new WeakMap,_ResultCollection_canHandle=new WeakMap,_ResultCollection_instances=new WeakSet,_ResultCollection_observe=async function*(){let iterator=__classPrivateFieldGet(this,_ResultCollection_source,"f").call(this),done=!1;try{while(!0){let next=await iterator.next();if(next.done){done=!0;return}if(__classPrivateFieldGet(this,_ResultCollection_enabled,"f"))this.collector.accept(next.value);else __classPrivateFieldSet(this,_ResultCollection_uncollectedEvents,!0,"f");yield next.value}}catch(error){if(__classPrivateFieldGet(this,_ResultCollection_enabled,"f"))__classPrivateFieldSet(this,_ResultCollection_error,error,"f");throw error}finally{if(__classPrivateFieldSet(this,_ResultCollection_ended,!0,"f"),!done)await iterator.return?.()}},_ResultCollection_collect=async function(){this.enable();try{let iterator=__classPrivateFieldGet(this,_ResultCollection_iterator,"f")??this.iterate();while(!__classPrivateFieldGet(this,_ResultCollection_ended,"f")&&!this.collector.ready)if(this.collector.checkAction(__classPrivateFieldGet(this,_ResultCollection_canHandle,"f")),(await iterator.next()).done)break;if(__classPrivateFieldGet(this,_ResultCollection_error,"f")!==void 0&&!this.collector.ready)throw __classPrivateFieldGet(this,_ResultCollection_error,"f");if(!this.collector.ready&&__classPrivateFieldGet(this,_ResultCollection_signal,"f")?.aborted)throw this.collector.error("observation",__classPrivateFieldGet(this,_ResultCollection_signal,"f").reason);return this.collector.finish()}catch(error){throw error instanceof AgentTurnResultError?error:this.collector.error("observation",error)}finally{try{await __classPrivateFieldGet(this,_ResultCollection_iterator,"f")?.return()}finally{this.collector.release()}}}});async function cancelBody(response){try{await response?.body?.cancel()}catch{}}var _AgentSessionStream_instances,_AgentSessionStream_consumed,_AgentSessionStream_format,_AgentSessionStream_parsedResult,_AgentSessionStream_collection,_AgentSessionStream_stream,_AgentSessionStream_response,_AgentSessionStream_reading,_AgentSessionStream_sessions,_AgentSessionStream_sessionID,_AgentSessionStream_input,_AgentSessionStream_dispatcher,_AgentSessionStream_inputKey,_AgentSessionStream_options,_AgentSessionStream_iterate,_AgentSessionStream_checkAbort,_AgentSessionStream_abortError,AgentSessionStream;var init_agent_session_stream=__esm(()=>{init_tslib();init_turn_state();init_tool_dispatcher();init_parse_result();init_result_collection();init_error();init_headers();AgentSessionStream=class AgentSessionStream{constructor(sessions,sessionID,params,options){_AgentSessionStream_instances.add(this),this.controller=new AbortController,_AgentSessionStream_consumed.set(this,!1),_AgentSessionStream_format.set(this,void 0),_AgentSessionStream_parsedResult.set(this,void 0),_AgentSessionStream_collection.set(this,void 0),_AgentSessionStream_stream.set(this,void 0),_AgentSessionStream_response.set(this,void 0),_AgentSessionStream_reading.set(this,!1),_AgentSessionStream_sessions.set(this,void 0),_AgentSessionStream_sessionID.set(this,void 0),_AgentSessionStream_input.set(this,void 0),_AgentSessionStream_dispatcher.set(this,void 0),_AgentSessionStream_inputKey.set(this,void 0),_AgentSessionStream_options.set(this,void 0);let input=typeof params.input==="string"?[{role:"user",content:[{type:"input_text",text:params.input}]}]:params.input;if(params.input.length===0)throw new OpenAIError("input must not be empty");if(__classPrivateFieldSet(this,_AgentSessionStream_format,agentFormatParser(params.outputFormat),"f"),params.outputFormat&&!__classPrivateFieldGet(this,_AgentSessionStream_format,"f"))throw new OpenAIError("outputFormat must have its own parser function");__classPrivateFieldSet(this,_AgentSessionStream_sessions,sessions,"f"),__classPrivateFieldSet(this,_AgentSessionStream_sessionID,sessionID,"f"),__classPrivateFieldSet(this,_AgentSessionStream_input,{type:"agent.session.input.message",input},"f");let headers=buildHeaders([options?.headers]);__classPrivateFieldSet(this,_AgentSessionStream_inputKey,headers.nulls.has("idempotency-key")?void 0:headers.values.get("idempotency-key")??params.idempotencyKey??options?.idempotencyKey??uuid4(),"f"),headers.values.delete("idempotency-key"),headers.nulls.delete("idempotency-key");let{idempotencyKey:_key,...rest}=options??{};__classPrivateFieldSet(this,_AgentSessionStream_options,{...rest,headers},"f"),__classPrivateFieldSet(this,_AgentSessionStream_dispatcher,new AgentToolDispatcher(sessions,params.toolHandlers??{},this.controller,__classPrivateFieldGet(this,_AgentSessionStream_options,"f"),params.onToolError),"f"),__classPrivateFieldSet(this,_AgentSessionStream_collection,new ResultCollection(()=>__classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_iterate).call(this),(name)=>__classPrivateFieldGet(this,_AgentSessionStream_dispatcher,"f").canHandle(name),sessionID),"f")}abort(reason){if(this.controller.abort(reason),__classPrivateFieldGet(this,_AgentSessionStream_stream,"f")?.controller.abort(this.controller.signal.reason),!__classPrivateFieldGet(this,_AgentSessionStream_reading,"f"))cancelBody(__classPrivateFieldGet(this,_AgentSessionStream_response,"f"))}[(_AgentSessionStream_consumed=new WeakMap,_AgentSessionStream_format=new WeakMap,_AgentSessionStream_parsedResult=new WeakMap,_AgentSessionStream_collection=new WeakMap,_AgentSessionStream_stream=new WeakMap,_AgentSessionStream_response=new WeakMap,_AgentSessionStream_reading=new WeakMap,_AgentSessionStream_sessions=new WeakMap,_AgentSessionStream_sessionID=new WeakMap,_AgentSessionStream_input=new WeakMap,_AgentSessionStream_dispatcher=new WeakMap,_AgentSessionStream_inputKey=new WeakMap,_AgentSessionStream_options=new WeakMap,_AgentSessionStream_instances=new WeakSet,Symbol.asyncIterator)](){if(__classPrivateFieldGet(this,_AgentSessionStream_consumed,"f"))throw new OpenAIError("An AgentSessionStream can only be consumed once");return __classPrivateFieldSet(this,_AgentSessionStream_consumed,!0,"f"),__classPrivateFieldGet(this,_AgentSessionStream_collection,"f").iterate()}withResultCollection(){return __classPrivateFieldGet(this,_AgentSessionStream_collection,"f").enable(),this}finalResult(){return __classPrivateFieldSet(this,_AgentSessionStream_parsedResult,__classPrivateFieldGet(this,_AgentSessionStream_parsedResult,"f")??parseAgentResultPromise(__classPrivateFieldGet(this,_AgentSessionStream_collection,"f").finalResult(),__classPrivateFieldGet(this,_AgentSessionStream_format,"f")),"f")}};_AgentSessionStream_iterate=async function*(){let externalSignal=__classPrivateFieldGet(this,_AgentSessionStream_options,"f").signal,abort=()=>this.abort(externalSignal?.aborted?externalSignal.reason:this.controller.signal.reason);externalSignal?.addEventListener("abort",abort,{once:!0}),this.controller.signal.addEventListener("abort",abort,{once:!0});let options={...__classPrivateFieldGet(this,_AgentSessionStream_options,"f"),signal:this.controller.signal},state=new TurnState;try{if(externalSignal?.aborted)this.abort(externalSignal.reason);if(__classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_checkAbort).call(this),(await __classPrivateFieldGet(this,_AgentSessionStream_sessions,"f").retrieve(__classPrivateFieldGet(this,_AgentSessionStream_sessionID,"f"),options)).status!=="idle")throw new OpenAIError("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let subscription=await __classPrivateFieldGet(this,_AgentSessionStream_sessions,"f").events.stream(__classPrivateFieldGet(this,_AgentSessionStream_sessionID,"f"),options).withResponse();__classPrivateFieldSet(this,_AgentSessionStream_stream,subscription.data,"f"),__classPrivateFieldSet(this,_AgentSessionStream_response,subscription.response,"f"),__classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_checkAbort).call(this),await __classPrivateFieldGet(this,_AgentSessionStream_sessions,"f").events.create(__classPrivateFieldGet(this,_AgentSessionStream_sessionID,"f"),{events:[__classPrivateFieldGet(this,_AgentSessionStream_input,"f")],...__classPrivateFieldGet(this,_AgentSessionStream_inputKey,"f")===void 0?{}:{"Idempotency-Key":__classPrivateFieldGet(this,_AgentSessionStream_inputKey,"f")}},{...options,headers:buildHeaders([options.headers,{"Idempotency-Key":__classPrivateFieldGet(this,_AgentSessionStream_inputKey,"f")??null}])}),__classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_checkAbort).call(this),__classPrivateFieldSet(this,_AgentSessionStream_reading,!0,"f");for await(let event of __classPrivateFieldGet(this,_AgentSessionStream_stream,"f")){if(__classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_checkAbort).call(this),!state.accept(event))continue;let terminal=state.terminal(event),dispatch=__classPrivateFieldGet(this,_AgentSessionStream_dispatcher,"f").prepare(state.call(event),__classPrivateFieldGet(this,_AgentSessionStream_sessionID,"f"));if(terminal)__classPrivateFieldGet(this,_AgentSessionStream_stream,"f").controller.abort();if(yield event,terminal)return;__classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_checkAbort).call(this),await dispatch?.()}throw __classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_checkAbort).call(this),new OpenAIError("Session event stream ended before the turn reached idle or failed")}finally{externalSignal?.removeEventListener("abort",abort),this.controller.signal.removeEventListener("abort",abort),this.abort()}},_AgentSessionStream_checkAbort=function(){if(this.controller.signal.aborted)throw __classPrivateFieldGet(this,_AgentSessionStream_instances,"m",_AgentSessionStream_abortError).call(this)},_AgentSessionStream_abortError=function(){let error=new APIUserAbortError;return Object.defineProperty(error,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),error}});async function*dispatchCreationTools(source,dispatcher,signal){let state=new TurnState,sessionID;for await(let event of{[Symbol.asyncIterator]:source}){if(event.type==="agent.session.created")sessionID??(sessionID=event.session.id);let dispatch=state.accept(event)?dispatcher.prepare(state.call(event),sessionID):void 0;if(yield event,signal.aborted)return;try{await dispatch?.()}catch(error){if(signal.aborted&&error instanceof APIUserAbortError)return;throw error}}}function withAgentTurnResult(stream,format,tools){let collection;stream.__betaTransformIterator((source)=>{let{path:_path,method:_method,stream:_stream,...options}=tools?.options??{},dispatcher=tools&&new AgentToolDispatcher(tools.sessions,tools.handlers,stream.controller,options);return collection=new ResultCollection(dispatcher?()=>dispatchCreationTools(source,dispatcher,stream.controller.signal):source,dispatcher?(name)=>dispatcher.canHandle(name):void 0,void 0,stream.controller.signal),()=>collection.iterate()});let parsed,result=Object.assign(stream,{finalResult:()=>parsed??(parsed=parseAgentResultPromise(collection.finalResult(),format)),withResultCollection:()=>(collection.enable(),result)});return result}function captureCreationTools(body,options){let descriptor=Object.getOwnPropertyDescriptor(body,"toolHandlers");if(!descriptor)return{body,options};let handlers=body.toolHandlers;if(handlers===void 0&&"value"in descriptor)return{body,options};let descriptors=Object.getOwnPropertyDescriptors(body);delete descriptors.toolHandlers;let capturedOptions={...options};if("toJSON"in body||capturedOptions.body!==void 0)throw new OpenAIError("Creation tool handlers cannot customize request body serialization");if(handlers===void 0)return{body:Object.create(Object.getPrototypeOf(body),descriptors),options:capturedOptions};let{stream}=body;if(stream!==!0)throw new OpenAIError("toolHandlers requires stream: true");return capturedOptions.headers=buildHeaders([capturedOptions.headers]),descriptors.stream={value:stream,enumerable:!0,configurable:!0,writable:!0},{body:Object.create(Object.getPrototypeOf(body),descriptors),options:capturedOptions,handlers:handlers&&Object.fromEntries(Object.entries(handlers))}}var init_agent_session_create_stream=__esm(()=>{init_error();init_headers();init_turn_state();init_tool_dispatcher();init_parse_result();init_result_collection()});function resolveResourceRequestOptions57(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization3(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery37(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys37.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys37.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys37,Sessions;var init_sessions=__esm(()=>{init_artifacts();init_artifacts();init_events();init_events();init_items();init_items();init_traces();init_traces();init_subagents();init_subagents();init_turns2();init_turns2();init_pagination();init_headers();init_path();init_agent_session_stream();init_agent_session_create_stream();init_parse_result();normalizeRequestOptionsForQueryKeys37=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Sessions=class Sessions extends APIResource{constructor(){super(...arguments);this.subagents=new Subagents(this._client),this.artifacts=new Artifacts(this._client),this.items=new Items(this._client),this.events=new Events(this._client),this.traces=new Traces(this._client),this.turns=new Turns2(this._client)}create(body,options){let creation=captureCreationTools(body,options),output=captureAgentOutput(creation.body,creation.options);return((body,options)=>this._client.post("/agents/sessions",resolveResourceRequestOptions57(options,(options)=>withBodyFinalization3({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),stream:body.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0}))))(output.body,output.options)._thenUnwrap((data,{options})=>options.stream?withAgentTurnResult(data,output.format,creation.handlers?{sessions:this,handlers:creation.handlers,options:output.options}:void 0):data)}retrieve(sessionID,options){return this._client.get(path`/agents/sessions/${sessionID}`,resolveResourceRequestOptions57(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}update(sessionID,body={},options){return this._client.post(path`/agents/sessions/${sessionID}`,resolveResourceRequestOptions57(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery37(query,["after","agent_id","limit","metadata","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/agents/sessions",CursorPage,resolveResourceRequestOptions57(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(sessionID,options){return this._client.delete(path`/agents/sessions/${sessionID}`,resolveResourceRequestOptions57(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}stream(sessionID,params,options){return new AgentSessionStream(this,sessionID,params,options)}};Sessions.Subagents=Subagents;Sessions.Artifacts=Artifacts;Sessions.Items=Items;Sessions.Events=Events;Sessions.Traces=Traces;Sessions.Turns=Turns2});function resolveResourceRequestOptions58(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery38(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys38.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys38.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys38,Credentials;var init_credentials=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys38=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Credentials=class Credentials extends APIResource{create(vaultID,body,options){return this._client.post(path`/vaults/${vaultID}/credentials`,resolveResourceRequestOptions58(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(credentialID,params,options){let{vault_id}=params;return this._client.get(path`/vaults/${vault_id}/credentials/${credentialID}`,resolveResourceRequestOptions58(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}update(credentialID,params,options){let{vault_id,...body}=params;return this._client.post(path`/vaults/${vault_id}/credentials/${credentialID}`,resolveResourceRequestOptions58(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(vaultID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery38(query,["after","limit","metadata","order","status"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/vaults/${vaultID}/credentials`,CursorPage,resolveResourceRequestOptions58(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(credentialID,params,options){let{vault_id}=params;return this._client.delete(path`/vaults/${vault_id}/credentials/${credentialID}`,resolveResourceRequestOptions58(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions59(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery39(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys39.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys39.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys39,Vaults;var init_vaults=__esm(()=>{init_credentials();init_credentials();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys39=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Vaults=class Vaults extends APIResource{constructor(){super(...arguments);this.credentials=new Credentials(this._client)}create(body={},options){return this._client.post("/vaults",resolveResourceRequestOptions59(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(vaultID,options){return this._client.get(path`/vaults/${vaultID}`,resolveResourceRequestOptions59(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}update(vaultID,body,options){return this._client.post(path`/vaults/${vaultID}`,resolveResourceRequestOptions59(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery39(query,["after","limit","metadata","order","status"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/vaults",CursorPage,resolveResourceRequestOptions59(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(vaultID,options){return this._client.delete(path`/vaults/${vaultID}`,resolveResourceRequestOptions59(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};Vaults.Credentials=Credentials});function resolveResourceRequestOptions60(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery40(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys40.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys40.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys40,Agents;var init_agents=__esm(()=>{init_automations();init_automations();init_environments();init_environments();init_sessions();init_sessions();init_vaults();init_vaults();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys40=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Agents=class Agents extends APIResource{constructor(){super(...arguments);this.automations=new Automations(this._client),this.environments=new Environments(this._client),this.vaults=new Vaults(this._client),this.sessions=new Sessions(this._client)}create(body,options){return this._client.post("/agents",resolveResourceRequestOptions60(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(agentID,options){return this._client.get(path`/agents/${agentID}`,resolveResourceRequestOptions60(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}update(agentID,body={},options){return this._client.post(path`/agents/${agentID}`,resolveResourceRequestOptions60(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery40(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/agents",CursorPage,resolveResourceRequestOptions60(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(agentID,options){return this._client.delete(path`/agents/${agentID}`,resolveResourceRequestOptions60(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"agents=v1"},options?.headers]),__security:{bearerAuth:!0}})))}};Agents.Automations=Automations;Agents.Environments=Environments;Agents.Vaults=Vaults;Agents.Sessions=Sessions});function resolveResourceRequestOptions61(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Sessions2;var init_sessions2=__esm(()=>{init_headers();init_path();Sessions2=class Sessions2 extends APIResource{create(body,options){return this._client.post("/chatkit/sessions",resolveResourceRequestOptions61(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"chatkit_beta=v1"},options?.headers]),__security:{bearerAuth:!0}})))}cancel(sessionID,options){return this._client.post(path`/chatkit/sessions/${sessionID}/cancel`,resolveResourceRequestOptions61(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"chatkit_beta=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions62(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery41(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys41.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys41.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys41,Threads;var init_threads=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys41=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Threads=class Threads extends APIResource{retrieve(threadID,options){return this._client.get(path`/chatkit/threads/${threadID}`,resolveResourceRequestOptions62(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"chatkit_beta=v1"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery41(query,["after","before","limit","order","user"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/chatkit/threads",ConversationCursorPage,resolveResourceRequestOptions62(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"chatkit_beta=v1"},options?.headers]),__security:{bearerAuth:!0}})))}delete(threadID,options){return this._client.delete(path`/chatkit/threads/${threadID}`,resolveResourceRequestOptions62(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"chatkit_beta=v1"},options?.headers]),__security:{bearerAuth:!0}})))}listItems(threadID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery41(query,["after","before","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/chatkit/threads/${threadID}/items`,ConversationCursorPage,resolveResourceRequestOptions62(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"chatkit_beta=v1"},options?.headers]),__security:{bearerAuth:!0}})))}}});var ChatKit;var init_chatkit=__esm(()=>{init_sessions2();init_sessions2();init_threads();init_threads();ChatKit=class ChatKit extends APIResource{constructor(){super(...arguments);this.sessions=new Sessions2(this._client),this.threads=new Threads(this._client)}};ChatKit.Sessions=Sessions2;ChatKit.Threads=Threads});function resolveResourceRequestOptions63(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery42(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys42.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys42.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys42,InputItems;var init_input_items=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys42=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);InputItems=class InputItems extends APIResource{list(responseID,params={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery42(params,["after","betas","include","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,params={};params=params;let{betas,...query}=params??{};return this._client.getAPIList(path`/responses/${responseID}/input_items?beta=true`,CursorPage,resolveResourceRequestOptions63(options,(options)=>({query,...options,headers:buildHeaders([{...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions64(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var InputTokens;var init_input_tokens=__esm(()=>{init_headers();InputTokens=class InputTokens extends APIResource{count(params={},options){let{betas,...body}=params??{};return this._client.post("/responses/input_tokens?beta=true",resolveResourceRequestOptions64(options,(options)=>({body,...options,headers:buildHeaders([{...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions65(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization4(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery43(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys43.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys43.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys43,Responses;var init_responses=__esm(()=>{init_input_items();init_input_items();init_input_tokens();init_input_tokens();init_headers();init_path();normalizeRequestOptionsForQueryKeys43=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Responses=class Responses extends APIResource{constructor(){super(...arguments);this.inputItems=new InputItems(this._client),this.inputTokens=new InputTokens(this._client)}create(params,options){let{betas,...body}=params;return this._client.post("/responses?beta=true",resolveResourceRequestOptions65(options,(options)=>withBodyFinalization4({body,...options,headers:buildHeaders([{...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),stream:params.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}retrieve(responseID,params={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery43(params,["betas","include","include_obfuscation","starting_after","stream"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,params={};params=params;let{betas,...query}=params??{};return this._client.get(path`/responses/${responseID}?beta=true`,resolveResourceRequestOptions65(options,(options)=>({query,...options,headers:buildHeaders([{...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),stream:params?.stream??!1,__security:{bearerAuth:!0}})))}delete(responseID,params={},options){let{betas}=params??{};return this._client.delete(path`/responses/${responseID}?beta=true`,resolveResourceRequestOptions65(options,(options)=>({...options,headers:buildHeaders([{Accept:"*/*",...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}cancel(responseID,params={},options){let{betas}=params??{};return this._client.post(path`/responses/${responseID}/cancel?beta=true`,resolveResourceRequestOptions65(options,(options)=>({...options,headers:buildHeaders([{...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}compact(params,options){let{betas,...body}=params;return this._client.post("/responses/compact?beta=true",resolveResourceRequestOptions65(options,(options)=>({body,...options,headers:buildHeaders([{...betas?.toString()!=null?{"openai-beta":betas?.toString()}:void 0},options?.headers]),__security:{bearerAuth:!0}})))}};Responses.InputItems=InputItems;Responses.InputTokens=InputTokens});function resolveResourceRequestOptions66(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery44(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys44.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys44.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys44,Messages2;var init_messages2=__esm(()=>{init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys44=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Messages2=class Messages2 extends APIResource{create(threadID,body,options){return this._client.post(path`/threads/${threadID}/messages`,resolveResourceRequestOptions66(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(messageID,params,options){let{thread_id}=params;return this._client.get(path`/threads/${thread_id}/messages/${messageID}`,resolveResourceRequestOptions66(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}update(messageID,params,options){let{thread_id,...body}=params;return this._client.post(path`/threads/${thread_id}/messages/${messageID}`,resolveResourceRequestOptions66(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}list(threadID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery44(query,["after","before","limit","order","run_id"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/threads/${threadID}/messages`,CursorPage,resolveResourceRequestOptions66(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}delete(messageID,params,options){let{thread_id}=params;return this._client.delete(path`/threads/${thread_id}/messages/${messageID}`,resolveResourceRequestOptions66(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions67(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Steps;var init_steps=__esm(()=>{init_pagination();init_headers();init_path();Steps=class Steps extends APIResource{retrieve(stepID,params,options){let{thread_id,run_id,...query}=params;return this._client.get(path`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`,resolveResourceRequestOptions67(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}list(runID,params,options){let{thread_id,...query}=params;return this._client.getAPIList(path`/threads/${thread_id}/runs/${runID}/steps`,CursorPage,resolveResourceRequestOptions67(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}}});function sleepUntilAborted(milliseconds,signal){return new Promise((resolve,reject)=>{let timer,registered,settled=!1,removeAbortListener=(listener)=>{try{signal.removeEventListener("abort",listener)}catch{}},cleanup=()=>{if(timer!==void 0)clearTimeout(timer),timer=void 0;if(registered){let listener=registered;registered=void 0,removeAbortListener(listener)}},abort=()=>{if(settled)return;settled=!0,cleanup();try{let error=new APIUserAbortError;Object.defineProperty(error,"cause",{value:signal.reason,writable:!0,configurable:!0}),reject(error)}catch(error){reject(error)}};if(signal.aborted){abort();return}timer=setTimeout(()=>{if(settled)return;settled=!0,cleanup(),resolve()},milliseconds),registered=abort;try{if(signal.addEventListener("abort",abort,{once:!0}),settled)removeAbortListener(abort);else if(signal.aborted)abort()}catch(error){if(settled)removeAbortListener(abort);else settled=!0,cleanup(),reject(error)}})}async function pollWithResponse(retrieve,intermediateStatuses,terminalStatuses,options){let headers=buildHeaders([options?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":options?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data,response}=await retrieve(headers).withResponse(),{status}=data;if(intermediateStatuses.includes(status)){let sleepInterval=5000,pollIntervalMs=options?.pollIntervalMs;if(pollIntervalMs||pollIntervalMs===0)sleepInterval=pollIntervalMs;else{let headerInterval=response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=Number.parseInt(headerInterval);if(!Number.isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}let signal=options&&Object.prototype.propertyIsEnumerable.call(options,"signal")?options.signal:void 0;await(signal?sleepUntilAborted(sleepInterval,signal):sleep(sleepInterval))}else if(terminalStatuses.includes(status))return data}}var init_polling=__esm(()=>{init_error();init_headers()});function pollAssistantRun(resource,runID,params,options){return pollWithResponse((headers)=>resource.retrieve(runID,params,{...options,headers:{...options?.headers,...headers}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],options)}var init_assistant_run_polling=__esm(()=>{init_polling()});var fromBase64=(str)=>{if(typeof globalThis.Buffer<"u"){let buf=globalThis.Buffer.from(str,"base64");return new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}if(typeof atob<"u"){let bstr=atob(str),buf=new Uint8Array(bstr.length);for(let i=0;i<bstr.length;i++)buf[i]=bstr.charCodeAt(i);return buf}throw new OpenAIError("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},toFloat32Array=(base64Str)=>{if(typeof Buffer<"u"){let buf=Buffer.from(base64Str,"base64");if(buf.length%Float32Array.BYTES_PER_ELEMENT!==0)throw RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(buf.buffer,buf.byteOffset,buf.length/Float32Array.BYTES_PER_ELEMENT))}else{let binaryStr=atob(base64Str),len=binaryStr.length,bytes=new Uint8Array(len);for(let i=0;i<len;i++)bytes[i]=binaryStr.charCodeAt(i);return Array.from(new Float32Array(bytes.buffer))}};var init_base64=__esm(()=>{init_error()});var readEnv=(env)=>{try{if(typeof globalThis.process<"u")return globalThis.process.env?.[env]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(env)?.trim()||void 0}catch{return}return};var init_utils2=__esm(()=>{init_values();init_base64();init_log();init_query()});function getAssistantStreamDiagnosticProperty(property){switch(property){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return property;default:return"unknown"}}function createAssistantStreamDeltaProjection(cacheArrays){return{arrays:new Map,cacheArrays,records:new WeakMap}}function commitAssistantStreamArrayProjection(projection){for(let[array,projected]of projection.arrays)if(projected.cacheable&&!externallyMutableAssistantStreamValues.has(array))assistantStreamArrayStates.set(array,{length:projected.length,ownEntryCount:projected.ownEntryCount});else assistantStreamArrayStates.delete(array)}function isPrimitiveAssistantStreamValue(value){return typeof value==="string"||typeof value==="number"}function isPrimitiveAssistantStreamArrayDelta(accumulator,delta){return delta.every(isPrimitiveAssistantStreamValue)&&accumulator.every(isPrimitiveAssistantStreamValue)}function countOwnAssistantStreamArrayEntries(accumulator){let count=0;for(let key of Object.keys(accumulator)){let index=Number(key);if(Number.isSafeInteger(index)&&index>=0&&index<accumulator.length&&String(index)===key)count+=1}return count}function getAssistantStreamArrayOwnEntryCount(accumulator,enforceSparseHoleBudget,cachedState){if(!enforceSparseHoleBudget)return 0;if(cachedState?.length===accumulator.length)return cachedState.ownEntryCount;return countOwnAssistantStreamArrayEntries(accumulator)}function getAssistantStreamDeltaIndex(deltaEntry,kind,baselineLength){let{index}=deltaEntry;if(kind==="array"&&(index===null||index===void 0))throw Error("Expected array delta entry to have an `index` property");if(kind==="array"&&typeof index!=="number")throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(index)||index<0||index>=baselineLength+MAX_ASSISTANT_STREAM_ARRAY_GROWTH||index>=MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH)throw new OpenAIError(`Assistant stream delta contains an invalid ${kind} index: ${typeof index==="number"?index:"unknown"}`);return index}function assertValidAssistantStreamArrayDelta(accumulator,delta,kind,projection,validateRecord){let projectedArray=projection.arrays.get(accumulator);if(!projectedArray){let enforceSparseHoleBudget=projection.cacheArrays&&!externallyMutableAssistantStreamValues.has(accumulator),cachedState=enforceSparseHoleBudget?assistantStreamArrayStates.get(accumulator):void 0;projectedArray={baselineLength:accumulator.length,cacheable:enforceSparseHoleBudget,enforceSparseHoleBudget,entries:new Map,length:accumulator.length,ownEntryCount:getAssistantStreamArrayOwnEntryCount(accumulator,enforceSparseHoleBudget,cachedState)},projection.arrays.set(accumulator,projectedArray)}for(let deltaEntry of delta){if(!isObj(deltaEntry))throw Error("Expected array delta entry to be an object but got an invalid value");let validatedIndex=getAssistantStreamDeltaIndex(deltaEntry,kind,projectedArray.baselineLength),accumulatedEntry;if(projectedArray.entries.has(validatedIndex))accumulatedEntry=projectedArray.entries.get(validatedIndex);else if(hasOwn(accumulator,validatedIndex)){if(accumulatedEntry=accumulator[validatedIndex],accumulatedEntry===null||accumulatedEntry===void 0)projectedArray.entries.set(validatedIndex,deltaEntry)}else projectedArray.entries.set(validatedIndex,deltaEntry),projectedArray.ownEntryCount+=1;let projectedLength=Math.max(projectedArray.length,validatedIndex+1);if(projectedArray.enforceSparseHoleBudget&&projectedLength-projectedArray.ownEntryCount>MAX_ASSISTANT_STREAM_ARRAY_GROWTH)throw new OpenAIError(`Assistant stream delta contains an invalid ${kind} index: ${validatedIndex}`);if(isObj(accumulatedEntry))validateRecord(accumulatedEntry,deltaEntry,projection);projectedArray.length=projectedLength}}function assertValidAssistantStreamDeltaIndices(accumulator,delta,projection){let projectedValues=projection.records.get(accumulator);for(let[key,deltaValue]of Object.entries(delta)){if(key==="index"||key==="type")continue;let accumulatedValue;if(projectedValues?.has(key))accumulatedValue=projectedValues.get(key);else if(hasOwn(accumulator,key))accumulatedValue=accumulator[key];if(accumulatedValue===null||accumulatedValue===void 0){if(!projectedValues)projectedValues=new Map,projection.records.set(accumulator,projectedValues);projectedValues.set(key,deltaValue);continue}if(isObj(accumulatedValue)&&isObj(deltaValue))assertValidAssistantStreamDeltaIndices(accumulatedValue,deltaValue,projection);else if(Array.isArray(accumulatedValue)&&Array.isArray(deltaValue)&&!isPrimitiveAssistantStreamArrayDelta(accumulatedValue,deltaValue))assertValidAssistantStreamArrayDelta(accumulatedValue,deltaValue,"array",projection,assertValidAssistantStreamDeltaIndices)}}function isAssistantStreamValueExternallyMutable(value){return(isObj(value)||Array.isArray(value))&&externallyMutableAssistantStreamValues.has(value)}function markAssistantStreamValueExternallyMutable(value){if(!isObj(value)&&!Array.isArray(value)||externallyMutableAssistantStreamValues.has(value))return;if(externallyMutableAssistantStreamValues.add(value),Array.isArray(value))assistantStreamArrayStates.delete(value);for(let key of Reflect.ownKeys(value)){let descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&"value"in descriptor)markAssistantStreamValueExternallyMutable(descriptor.value)}}function defineAssistantStreamArrayEntry(accumulator,index,value){if(externallyMutableAssistantStreamValues.has(accumulator))markAssistantStreamValueExternallyMutable(value);Object.defineProperty(accumulator,index,{configurable:!0,enumerable:!0,value,writable:!0})}function getRequiredAssistantStreamArrayIndex(deltaEntry){let{index}=deltaEntry;if(index===null||index===void 0)throw Error("Expected array delta entry to have an `index` property");if(typeof index!=="number")throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return index}function applyAssistantStreamArrayDelta(accumulator,delta,applyRecord){if(isPrimitiveAssistantStreamArrayDelta(accumulator,delta)){accumulator.push(...delta),assistantStreamArrayStates.delete(accumulator);return}for(let deltaEntry of delta){if(!isObj(deltaEntry))throw Error("Expected array delta entry to be an object but got an invalid value");let index=getRequiredAssistantStreamArrayIndex(deltaEntry);if(hasOwn(accumulator,index)){let accumulatedEntry=accumulator[index];if(accumulatedEntry===null||accumulatedEntry===void 0){if(externallyMutableAssistantStreamValues.has(accumulator))markAssistantStreamValueExternallyMutable(deltaEntry);accumulator[index]=deltaEntry}else accumulator[index]=applyRecord(accumulatedEntry,deltaEntry)}else defineAssistantStreamArrayEntry(accumulator,index,deltaEntry)}}function applyAssistantStreamDelta(accumulator,delta){let externallyMutable=externallyMutableAssistantStreamValues.has(accumulator);for(let[key,deltaValue]of Object.entries(delta)){if(key==="__proto__"||key==="constructor"||key==="prototype")throw new OpenAIError(`Assistant stream delta contains an unsafe property: ${key}`);if(!hasOwn(accumulator,key)){if(externallyMutable)markAssistantStreamValueExternallyMutable(deltaValue);accumulator[key]=deltaValue;continue}let accumulatedValue=accumulator[key];if(accumulatedValue===null||accumulatedValue===void 0){if(externallyMutable)markAssistantStreamValueExternallyMutable(deltaValue);accumulator[key]=deltaValue;continue}if(key==="index"||key==="type"){accumulator[key]=deltaValue;continue}if(typeof accumulatedValue==="string"&&typeof deltaValue==="string")accumulatedValue+=deltaValue;else if(typeof accumulatedValue==="number"&&typeof deltaValue==="number")accumulatedValue+=deltaValue;else if(isObj(accumulatedValue)&&isObj(deltaValue))accumulatedValue=applyAssistantStreamDelta(accumulatedValue,deltaValue);else if(Array.isArray(accumulatedValue)&&Array.isArray(deltaValue)){applyAssistantStreamArrayDelta(accumulatedValue,deltaValue,applyAssistantStreamDelta);continue}else throw TypeError(`Unhandled record type: ${getAssistantStreamDiagnosticProperty(key)}`);accumulator[key]=accumulatedValue}return accumulator}function assertSafeAssistantStreamDelta(value){if(!isObj(value)&&!Array.isArray(value))return;for(let[key,nestedValue]of Object.entries(value)){if(key==="__proto__"||key==="constructor"||key==="prototype")throw new OpenAIError(`Assistant stream delta contains an unsafe property: ${key}`);assertSafeAssistantStreamDelta(nestedValue)}}function accumulateAssistantStreamDelta(accumulator,delta,cacheArrays=!1){assertSafeAssistantStreamDelta(delta);let accumulatorRecord=accumulator,deltaRecord=delta,projection=createAssistantStreamDeltaProjection(cacheArrays&&!isAssistantStreamValueExternallyMutable(accumulator));return assertValidAssistantStreamDeltaIndices(accumulatorRecord,deltaRecord,projection),applyAssistantStreamDelta(accumulatorRecord,deltaRecord),commitAssistantStreamArrayProjection(projection),accumulator}function createAssistantStreamArrayDeltaCommit(accumulator,delta,kind,cacheArrays=!0){assertSafeAssistantStreamDelta(delta);let projection=createAssistantStreamDeltaProjection(cacheArrays&&!isAssistantStreamValueExternallyMutable(accumulator));return assertValidAssistantStreamArrayDelta(accumulator,delta,kind,projection,assertValidAssistantStreamDeltaIndices),()=>commitAssistantStreamArrayProjection(projection)}var MAX_ASSISTANT_STREAM_ARRAY_GROWTH=1024,MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH=65536,assistantStreamArrayStates,externallyMutableAssistantStreamValues;var init_assistant_stream_delta=__esm(()=>{init_error2();init_utils2();assistantStreamArrayStates=new WeakMap,externallyMutableAssistantStreamValues=new WeakSet});function stabilizeAssistantStreamEvent(event){let eventDescriptor=Object.getOwnPropertyDescriptor(event,"event"),dataDescriptor=Object.getOwnPropertyDescriptor(event,"data"),eventType=Reflect.get(event,"event",event),data=Reflect.get(event,"data",event),stableData=data;if(eventType==="thread.message.created"||eventType==="thread.message.in_progress"||eventType==="thread.message.delta"||eventType==="thread.message.completed"||eventType==="thread.message.incomplete"||eventType==="thread.run.step.created"||eventType==="thread.run.step.in_progress"||eventType==="thread.run.step.delta"||eventType==="thread.run.step.completed"||eventType==="thread.run.step.failed"||eventType==="thread.run.step.cancelled"||eventType==="thread.run.step.expired"){let messageID=Object.getOwnPropertyDescriptor(data,"id");if(messageID&&"value"in messageID&&data.id!==messageID.value){let canonicalID=messageID.value;stableData=new Proxy(data,{get(target,property){return property==="id"?canonicalID:Reflect.get(target,property,target)}})}}let stableEvent=Object.freeze({event:eventType,data:stableData}),ordinaryEvent=eventDescriptor!==void 0&&"value"in eventDescriptor&&eventDescriptor.value===eventType&&dataDescriptor!==void 0&&"value"in dataDescriptor&&dataDescriptor.value===data&&stableData===data;return{event:stableEvent,exposedEvent:ordinaryEvent?event:{event:eventType,data:stableData}}}function assertNever2(_x){return _x}var _AssistantStream_instances,_AssistantStream_runStepSnapshots,_AssistantStream_runStepIDOwners,_AssistantStream_activeRunStepID,_AssistantStream_messageSnapshots,_AssistantStream_messageIDOwners,_AssistantStream_messageSnapshot,_AssistantStream_activeMessageID,_AssistantStream_finalRun,_AssistantStream_currentContentIndex,_AssistantStream_currentContent,_AssistantStream_currentToolCallIndex,_AssistantStream_currentToolCall,_AssistantStream_currentEvent,_AssistantStream_currentRunSnapshot,_AssistantStream_currentRunStepSnapshot,_AssistantStream_addEvent,_AssistantStream_endRequest,_AssistantStream_validateRunStepEvent,_AssistantStream_reserveRunStepAlias,_AssistantStream_validateMessageEvent,_AssistantStream_reserveMessageAlias,_AssistantStream_handleMessage,_AssistantStream_handleRunStep,_AssistantStream_emitExposed,_AssistantStream_handleEvent,_AssistantStream_accumulateRunStep,_AssistantStream_accumulateMessage,_AssistantStream_accumulateContent,_AssistantStream_handleRun,AssistantStream;var init_AssistantStream=__esm(()=>{init_tslib();init_streaming2();init_error2();init_EventStream();init_utils2();init_assistant_stream_delta();AssistantStream=class AssistantStream extends EventStream{constructor(){super(...arguments);_AssistantStream_instances.add(this),_AssistantStream_runStepSnapshots.set(this,Object.create(null)),_AssistantStream_runStepIDOwners.set(this,new Map),_AssistantStream_activeRunStepID.set(this,void 0),_AssistantStream_messageSnapshots.set(this,Object.create(null)),_AssistantStream_messageIDOwners.set(this,new Map),_AssistantStream_messageSnapshot.set(this,void 0),_AssistantStream_activeMessageID.set(this,void 0),_AssistantStream_finalRun.set(this,void 0),_AssistantStream_currentContentIndex.set(this,void 0),_AssistantStream_currentContent.set(this,void 0),_AssistantStream_currentToolCallIndex.set(this,void 0),_AssistantStream_currentToolCall.set(this,void 0),_AssistantStream_currentEvent.set(this,void 0),_AssistantStream_currentRunSnapshot.set(this,void 0),_AssistantStream_currentRunStepSnapshot.set(this,void 0)}[(_AssistantStream_runStepSnapshots=new WeakMap,_AssistantStream_runStepIDOwners=new WeakMap,_AssistantStream_activeRunStepID=new WeakMap,_AssistantStream_messageSnapshots=new WeakMap,_AssistantStream_messageIDOwners=new WeakMap,_AssistantStream_messageSnapshot=new WeakMap,_AssistantStream_activeMessageID=new WeakMap,_AssistantStream_finalRun=new WeakMap,_AssistantStream_currentContentIndex=new WeakMap,_AssistantStream_currentContent=new WeakMap,_AssistantStream_currentToolCallIndex=new WeakMap,_AssistantStream_currentToolCall=new WeakMap,_AssistantStream_currentEvent=new WeakMap,_AssistantStream_currentRunSnapshot=new WeakMap,_AssistantStream_currentRunStepSnapshot=new WeakMap,_AssistantStream_instances=new WeakSet,Symbol.asyncIterator)](){return this._createIterator((push)=>{let onEvent=(event)=>push(structuredClone(event));return this.on("event",onEvent),()=>this.off("event",onEvent)},{onReturn:()=>this.abort()})}static fromReadableStream(stream){let runner=new AssistantStream;return runner._run(()=>runner._fromReadableStream(stream)),runner}async _fromReadableStream(readableStream,options){this._listenForAbort(options?.signal),this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller);for await(let event of stream)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw this._userAbortError();return this._addRun(__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(runId,runs,params,options){let runner=new AssistantStream;return runner._run(()=>runner._runToolAssistantStream(runId,runs,params,{...options,__metadata:{...options?.__metadata,helperMethod:"stream"}})),runner}async _createToolAssistantStream(run,runId,params,options){this._listenForAbort(options?.signal);let body={...params,stream:!0},stream=await run.submitToolOutputs(runId,body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw this._userAbortError();return this._addRun(__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static createThreadAssistantStream(params,thread,options){let runner=new AssistantStream;return runner._run(()=>runner._threadAssistantStream(params,thread,{...options,__metadata:{...options?.__metadata,helperMethod:"stream"}})),runner}static createAssistantStream(threadId,runs,params,options){let runner=new AssistantStream;return runner._run(()=>runner._runAssistantStream(threadId,runs,params,{...options,__metadata:{...options?.__metadata,helperMethod:"stream"}})),runner}currentEvent(){return markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this,_AssistantStream_currentEvent,"f")),__classPrivateFieldGet(this,_AssistantStream_currentEvent,"f")}currentRun(){return markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this,_AssistantStream_currentRunSnapshot,"f")),__classPrivateFieldGet(this,_AssistantStream_currentRunSnapshot,"f")}currentMessageSnapshot(){return markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f")),__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f")}currentRunStepSnapshot(){return markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this,_AssistantStream_currentRunStepSnapshot,"f")),__classPrivateFieldGet(this,_AssistantStream_currentRunStepSnapshot,"f")}async finalRunSteps(){return await this.done(),Object.values(__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f"))}async finalMessages(){return await this.done(),Object.values(__classPrivateFieldGet(this,_AssistantStream_messageSnapshots,"f"))}async finalRun(){if(await this.done(),!__classPrivateFieldGet(this,_AssistantStream_finalRun,"f"))throw Error("Final run was not received.");return __classPrivateFieldGet(this,_AssistantStream_finalRun,"f")}async _createThreadAssistantStream(thread,params,options){this._listenForAbort(options?.signal);let body={...params,stream:!0},stream=await thread.createAndRun(body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw this._userAbortError();return this._addRun(__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}async _createAssistantStream(run,threadId,params,options){this._listenForAbort(options?.signal);let body={...params,stream:!0},stream=await run.create(threadId,body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw this._userAbortError();return this._addRun(__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static accumulateDelta(acc,delta){return accumulateAssistantStreamDelta(acc,delta)}_addRun(run){return __classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"run",run),run}async _threadAssistantStream(params,thread,options){return await this._createThreadAssistantStream(thread,params,options)}async _runAssistantStream(threadId,runs,params,options){return await this._createAssistantStream(runs,threadId,params,options)}async _runToolAssistantStream(runId,runs,params,options){return await this._createToolAssistantStream(runs,runId,params,options)}};_AssistantStream_addEvent=function(event){if(this.ended)return;let{event:stableEvent,exposedEvent}=stabilizeAssistantStreamEvent(event),messageID,messageData,runStepID,runStepData;switch(stableEvent.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{messageID=__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_validateMessageEvent).call(this,stableEvent),messageData=stableEvent.data;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":{runStepID=__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_validateRunStepEvent).call(this,stableEvent),runStepData=stableEvent.data;break}}if(__classPrivateFieldSet(this,_AssistantStream_currentEvent,exposedEvent,"f"),__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_handleEvent).call(this,exposedEvent),messageID!==void 0&&messageData!==void 0)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveMessageAlias).call(this,messageData,messageID);if(runStepID!==void 0&&runStepData!==void 0)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveRunStepAlias).call(this,runStepData,runStepID);if(runStepID===void 0&&__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f")!==void 0&&__classPrivateFieldGet(this,_AssistantStream_currentRunStepSnapshot,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveRunStepAlias).call(this,__classPrivateFieldGet(this,_AssistantStream_currentRunStepSnapshot,"f"),__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f"));switch(stableEvent.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":{__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_handleRun).call(this,stableEvent);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":{if(runStepID===void 0)throw new OpenAIError("Received assistant run-step event without a canonical run-step ID");let activeRunStep=__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID];if(activeRunStep)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveRunStepAlias).call(this,activeRunStep,runStepID);__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_handleRunStep).call(this,stableEvent,runStepID),__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveRunStepAlias).call(this,stableEvent.data,runStepID);let retainedRunStep=__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID];if(retainedRunStep)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveRunStepAlias).call(this,retainedRunStep,runStepID);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(messageID!==void 0&&__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveMessageAlias).call(this,__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"),messageID);if(__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_handleMessage).call(this,stableEvent),messageID!==void 0){__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveMessageAlias).call(this,stableEvent.data,messageID);let retainedMessage=__classPrivateFieldGet(this,_AssistantStream_messageSnapshots,"f")[messageID];if(retainedMessage)__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_reserveMessageAlias).call(this,retainedMessage,messageID)}break}case"error":throw new APIError(void 0,stableEvent.data,void 0,void 0);default:assertNever2(stableEvent)}},_AssistantStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");if(!__classPrivateFieldGet(this,_AssistantStream_finalRun,"f"))throw Error("Final run has not been received");return __classPrivateFieldGet(this,_AssistantStream_finalRun,"f")},_AssistantStream_validateRunStepEvent=function(event){let descriptor=Object.getOwnPropertyDescriptor(event.data,"id"),runStepID=descriptor&&"value"in descriptor?descriptor.value:void 0;if(typeof runStepID!=="string"||runStepID.length===0)throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");if(event.event==="thread.run.step.delta"){let delta=event.data.delta;if(delta&&hasOwn(delta,"id"))throw new OpenAIError("Run-step deltas must not contain an id field")}if(event.event==="thread.run.step.created"){if(__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f")!==void 0)throw new OpenAIError(`Received run-step creation for "${runStepID}" before the active run step "${__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f")}" reached a terminal state`);if(hasOwn(__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f"),runStepID)||__classPrivateFieldGet(this,_AssistantStream_runStepIDOwners,"f").has(runStepID))throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);return __classPrivateFieldSet(this,_AssistantStream_activeRunStepID,runStepID,"f"),__classPrivateFieldGet(this,_AssistantStream_runStepIDOwners,"f").set(runStepID,runStepID),runStepID}if(__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f")!==void 0){if(runStepID!==__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f"))throw new OpenAIError(`Received ${event.event} for run step "${runStepID}", which does not match the active run step "${__classPrivateFieldGet(this,_AssistantStream_activeRunStepID,"f")}"`);return runStepID}if(event.event==="thread.run.step.delta"){if(!hasOwn(__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f"),runStepID))throw new OpenAIError("Received a RunStepDelta before creation of a snapshot");throw new OpenAIError(`Received run-step delta for "${runStepID}" with no active run step`)}if(hasOwn(__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f"),runStepID)||__classPrivateFieldGet(this,_AssistantStream_runStepIDOwners,"f").has(runStepID))throw new OpenAIError(`Received run-step event for run step "${runStepID}", which has already been created`);if(__classPrivateFieldGet(this,_AssistantStream_runStepIDOwners,"f").set(runStepID,runStepID),event.event==="thread.run.step.in_progress")__classPrivateFieldSet(this,_AssistantStream_activeRunStepID,runStepID,"f");return runStepID},_AssistantStream_reserveRunStepAlias=function(data,canonicalID){let descriptor=Object.getOwnPropertyDescriptor(data,"id"),runStepID=descriptor&&"value"in descriptor?descriptor.value:void 0;if(typeof runStepID!=="string"||runStepID.length===0)throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");let owner=__classPrivateFieldGet(this,_AssistantStream_runStepIDOwners,"f").get(runStepID);if(owner!==void 0&&owner!==canonicalID)throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);__classPrivateFieldGet(this,_AssistantStream_runStepIDOwners,"f").set(runStepID,canonicalID)},_AssistantStream_validateMessageEvent=function(event){let descriptor=Object.getOwnPropertyDescriptor(event.data,"id"),messageID=descriptor&&"value"in descriptor?descriptor.value:void 0;if(typeof messageID!=="string"||messageID.length===0)throw new OpenAIError("Received assistant message event with an invalid message ID");if(event.event==="thread.message.created"){if(__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"))throw new OpenAIError(`Received message creation for "${messageID}" before the active message "${__classPrivateFieldGet(this,_AssistantStream_activeMessageID,"f")}" reached a terminal state`);if(hasOwn(__classPrivateFieldGet(this,_AssistantStream_messageSnapshots,"f"),messageID)||__classPrivateFieldGet(this,_AssistantStream_messageIDOwners,"f").has(messageID))throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);return __classPrivateFieldSet(this,_AssistantStream_activeMessageID,messageID,"f"),__classPrivateFieldGet(this,_AssistantStream_messageIDOwners,"f").set(messageID,messageID),messageID}if(!__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f")){if(event.event==="thread.message.delta")throw new OpenAIError("Received a delta with no existing snapshot (there should be one from message creation)");throw new OpenAIError("Received thread message event with no existing snapshot")}if(messageID!==__classPrivateFieldGet(this,_AssistantStream_activeMessageID,"f"))throw new OpenAIError(`Received ${event.event} for message "${messageID}", which does not match the active message "${__classPrivateFieldGet(this,_AssistantStream_activeMessageID,"f")}"`);return messageID},_AssistantStream_reserveMessageAlias=function(data,canonicalID){let descriptor=Object.getOwnPropertyDescriptor(data,"id"),messageID=descriptor&&"value"in descriptor?descriptor.value:void 0;if(typeof messageID!=="string"||messageID.length===0)throw new OpenAIError("Received assistant message event with an invalid message ID");let owner=__classPrivateFieldGet(this,_AssistantStream_messageIDOwners,"f").get(messageID);if(owner!==void 0&&owner!==canonicalID)throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);__classPrivateFieldGet(this,_AssistantStream_messageIDOwners,"f").set(messageID,canonicalID)},_AssistantStream_handleMessage=function(event){let[accumulatedMessage,newContent]=__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_accumulateMessage).call(this,event,__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"));if(__classPrivateFieldSet(this,_AssistantStream_messageSnapshot,accumulatedMessage,"f"),!__classPrivateFieldGet(this,_AssistantStream_activeMessageID,"f"))throw new OpenAIError("Received thread message event with no active message ID");__classPrivateFieldGet(this,_AssistantStream_messageSnapshots,"f")[__classPrivateFieldGet(this,_AssistantStream_activeMessageID,"f")]=accumulatedMessage;for(let content of newContent){let snapshotContent=accumulatedMessage.content[content.index];if(snapshotContent?.type==="text")__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"textCreated",snapshotContent.text)}switch(event.event){case"thread.message.created":{__classPrivateFieldSet(this,_AssistantStream_currentContentIndex,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_currentContent,void 0,"f"),__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"messageCreated",event.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"messageDelta",event.data.delta,accumulatedMessage),event.data.delta.content)for(let content of event.data.delta.content){if(content.type==="text"&&content.text){let textDelta=content.text,snapshot=accumulatedMessage.content[content.index];if(snapshot&&snapshot.type==="text")__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"textDelta",textDelta,snapshot.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(content.index!==__classPrivateFieldGet(this,_AssistantStream_currentContentIndex,"f")){if(__classPrivateFieldGet(this,_AssistantStream_currentContent,"f"))switch(__classPrivateFieldGet(this,_AssistantStream_currentContent,"f").type){case"text":{__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"textDone",__classPrivateFieldGet(this,_AssistantStream_currentContent,"f").text,__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"));break}case"image_file":{__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"imageFileDone",__classPrivateFieldGet(this,_AssistantStream_currentContent,"f").image_file,__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"));break}}__classPrivateFieldSet(this,_AssistantStream_currentContentIndex,content.index,"f")}__classPrivateFieldSet(this,_AssistantStream_currentContent,accumulatedMessage.content[content.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(__classPrivateFieldGet(this,_AssistantStream_currentContentIndex,"f")!==void 0){let currentContent=event.data.content[__classPrivateFieldGet(this,_AssistantStream_currentContentIndex,"f")];if(currentContent)switch(currentContent.type){case"image_file":{__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"imageFileDone",currentContent.image_file,__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"));break}case"text":{__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"textDone",currentContent.text,__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"));break}}}if(__classPrivateFieldGet(this,_AssistantStream_messageSnapshot,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"messageDone",event.data);__classPrivateFieldSet(this,_AssistantStream_currentContentIndex,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_currentContent,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_messageSnapshot,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_activeMessageID,void 0,"f")}}},_AssistantStream_handleRunStep=function(event,runStepID){let accumulatedRunStep=__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_accumulateRunStep).call(this,event,runStepID);switch(__classPrivateFieldSet(this,_AssistantStream_currentRunStepSnapshot,accumulatedRunStep,"f"),event.event){case"thread.run.step.created":{__classPrivateFieldSet(this,_AssistantStream_currentToolCallIndex,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_currentToolCall,void 0,"f"),__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"runStepCreated",event.data);break}case"thread.run.step.delta":{let delta=event.data.delta;if(delta.step_details&&delta.step_details.type==="tool_calls"&&delta.step_details.tool_calls&&accumulatedRunStep.step_details.type==="tool_calls")for(let toolCall of delta.step_details.tool_calls)if(toolCall.index===__classPrivateFieldGet(this,_AssistantStream_currentToolCallIndex,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"toolCallDelta",toolCall,accumulatedRunStep.step_details.tool_calls[toolCall.index]);else{if(__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"toolCallDone",__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"));if(__classPrivateFieldSet(this,_AssistantStream_currentToolCallIndex,toolCall.index,"f"),__classPrivateFieldSet(this,_AssistantStream_currentToolCall,accumulatedRunStep.step_details.tool_calls[toolCall.index],"f"),__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"toolCallCreated",__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"))}__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"runStepDelta",event.data.delta,accumulatedRunStep);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(__classPrivateFieldSet(this,_AssistantStream_currentRunStepSnapshot,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_activeRunStepID,void 0,"f"),event.data.step_details.type==="tool_calls"&&__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"toolCallDone",__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"));__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"runStepDone",event.data,accumulatedRunStep),__classPrivateFieldSet(this,_AssistantStream_currentToolCallIndex,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_currentToolCall,void 0,"f");break}case"thread.run.step.in_progress":break}},_AssistantStream_emitExposed=function(event,...args){if(this._hasListeners(event))for(let value of args)markAssistantStreamValueExternallyMutable(value);this._emit(event,...args)},_AssistantStream_handleEvent=function(event){__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"event",event)},_AssistantStream_accumulateRunStep=function(event,runStepID){switch(event.event){case"thread.run.step.created":return __classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID]=event.data,event.data;case"thread.run.step.delta":{let snapshot=__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID];if(!snapshot)throw Error("Received a RunStepDelta before creation of a snapshot");let delta=event.data.delta;if(delta){if(hasOwn(delta,"id"))throw new OpenAIError("Run-step deltas must not contain an id field");let accumulated=accumulateAssistantStreamDelta(snapshot,delta,!0);__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID]=accumulated}return __classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID]}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":{__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID]=event.data;break}}if(__classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID])return __classPrivateFieldGet(this,_AssistantStream_runStepSnapshots,"f")[runStepID];throw Error("No snapshot available")},_AssistantStream_accumulateMessage=function(event,snapshot){let newContent=[];switch(event.event){case"thread.message.created":return[event.data,newContent];case"thread.message.delta":{if(!snapshot)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let data=event.data;if(data.delta.content){assertSafeAssistantStreamDelta(data.delta);let cacheArrays=!isAssistantStreamValueExternallyMutable(snapshot),commitProjection=createAssistantStreamArrayDeltaCommit(snapshot.content,data.delta.content,"content",cacheArrays);for(let contentElement of data.delta.content)if(hasOwn(snapshot.content,contentElement.index)){let currentContent=snapshot.content[contentElement.index];snapshot.content[contentElement.index]=__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_accumulateContent).call(this,contentElement,currentContent,cacheArrays)}else defineAssistantStreamArrayEntry(snapshot.content,contentElement.index,contentElement),newContent.push(contentElement);commitProjection()}return[snapshot,newContent]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":{if(snapshot)return[event.event==="thread.message.in_progress"?snapshot:event.data,newContent];throw Error("Received thread message event with no existing snapshot")}}throw Error("Tried to accumulate a non-message event")},_AssistantStream_accumulateContent=function(contentElement,currentContent,cacheArrays){return accumulateAssistantStreamDelta(currentContent,contentElement,cacheArrays)},_AssistantStream_handleRun=function(event){switch(__classPrivateFieldSet(this,_AssistantStream_currentRunSnapshot,event.data,"f"),event.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":{if(__classPrivateFieldSet(this,_AssistantStream_finalRun,event.data,"f"),__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"))__classPrivateFieldGet(this,_AssistantStream_instances,"m",_AssistantStream_emitExposed).call(this,"toolCallDone",__classPrivateFieldGet(this,_AssistantStream_currentToolCall,"f"));__classPrivateFieldSet(this,_AssistantStream_currentToolCallIndex,void 0,"f"),__classPrivateFieldSet(this,_AssistantStream_currentToolCall,void 0,"f");break}case"thread.run.cancelling":break}}});function resolveResourceRequestOptions68(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization5(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery45(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys45.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys45.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys45,Runs;var init_runs=__esm(()=>{init_steps();init_steps();init_pagination();init_headers();init_assistant_run_polling();init_path();init_AssistantStream();normalizeRequestOptionsForQueryKeys45=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Runs=class Runs extends APIResource{constructor(){super(...arguments);this.steps=new Steps(this._client)}create(threadID,params,options){let{include,...body}=params;return this._client.post(path`/threads/${threadID}/runs`,resolveResourceRequestOptions68(options,(options)=>withBodyFinalization5({query:{include},body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),stream:params.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async createAndPoll(threadId,body,options){let created=await this.create(threadId,body,options);return await this.poll(created.id,{thread_id:threadId},options)}createAndStream(threadId,body,options){return AssistantStream.createAssistantStream(threadId,this._client.beta.threads.runs,body,options)}retrieve(runID,params,options){let{thread_id}=params;return this._client.get(path`/threads/${thread_id}/runs/${runID}`,resolveResourceRequestOptions68(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}update(runID,params,options){let{thread_id,...body}=params;return this._client.post(path`/threads/${thread_id}/runs/${runID}`,resolveResourceRequestOptions68(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}list(threadID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery45(query,["after","before","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/threads/${threadID}/runs`,CursorPage,resolveResourceRequestOptions68(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}cancel(runID,params,options){let{thread_id}=params;return this._client.post(path`/threads/${thread_id}/runs/${runID}/cancel`,resolveResourceRequestOptions68(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}async poll(runId,params,options){return await pollAssistantRun(this,runId,params,options)}stream(threadId,body,options){return AssistantStream.createAssistantStream(threadId,this._client.beta.threads.runs,body,options)}submitToolOutputs(runID,params,options){let{thread_id,...body}=params;return this._client.post(path`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`,resolveResourceRequestOptions68(options,(options)=>withBodyFinalization5({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),stream:params.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async submitToolOutputsAndPoll(runId,params,options){let completed=await this.submitToolOutputs(runId,params,options);return await this.poll(completed.id,params,options)}submitToolOutputsStream(runId,params,options){return AssistantStream.createToolAssistantStream(runId,this._client.beta.threads.runs,params,options)}};Runs.Steps=Steps});function resolveResourceRequestOptions69(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization6(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}var Threads2;var init_threads2=__esm(()=>{init_messages2();init_messages2();init_runs();init_runs();init_headers();init_path();init_AssistantStream();Threads2=class Threads2 extends APIResource{constructor(){super(...arguments);this.runs=new Runs(this._client),this.messages=new Messages2(this._client)}create(body={},options){return this._client.post("/threads",resolveResourceRequestOptions69(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(threadID,options){return this._client.get(path`/threads/${threadID}`,resolveResourceRequestOptions69(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}update(threadID,body,options){return this._client.post(path`/threads/${threadID}`,resolveResourceRequestOptions69(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}delete(threadID,options){return this._client.delete(path`/threads/${threadID}`,resolveResourceRequestOptions69(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}createAndRun(body,options){return this._client.post("/threads/runs",resolveResourceRequestOptions69(options,(options)=>withBodyFinalization6({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),stream:body.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async createAndRunPoll(body,options){let run=await this.createAndRun(body,options);return await this.runs.poll(run.id,{thread_id:run.thread_id},options)}createAndRunStream(body,options){return AssistantStream.createThreadAssistantStream(body,this._client.beta.threads,options)}};Threads2.Runs=Runs;Threads2.Messages=Messages2});var Sessions3;var init_sessions3=__esm(()=>{init_headers();Sessions3=class Sessions3 extends APIResource{create(body,options){return this._client.post("/realtime/sessions",{body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})}}});var TranscriptionSessions;var init_transcription_sessions=__esm(()=>{init_headers();TranscriptionSessions=class TranscriptionSessions extends APIResource{create(body,options){return this._client.post("/realtime/transcription_sessions",{body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})}}});var Realtime;var init_realtime=__esm(()=>{init_sessions3();init_sessions3();init_transcription_sessions();init_transcription_sessions();Realtime=class Realtime extends APIResource{constructor(){super(...arguments);this.sessions=new Sessions3(this._client),this.transcriptionSessions=new TranscriptionSessions(this._client)}};Realtime.Sessions=Sessions3;Realtime.TranscriptionSessions=TranscriptionSessions});var Beta;var init_beta=__esm(()=>{init_assistants();init_assistants();init_agents();init_agents();init_chatkit();init_chatkit();init_responses();init_responses();init_threads2();init_threads2();init_realtime();init_realtime();Beta=class Beta extends APIResource{constructor(){super(...arguments);this.realtime=new Realtime(this._client),this.agents=new Agents(this._client),this.responses=new Responses(this._client),this.chatkit=new ChatKit(this._client),this.assistants=new Assistants(this._client),this.threads=new Threads2(this._client)}};Beta.Realtime=Realtime;Beta.Agents=Agents;Beta.Responses=Responses;Beta.ChatKit=ChatKit;Beta.Assistants=Assistants;Beta.Threads=Threads2});function resolveResourceRequestOptions70(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization7(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}var Completions2;var init_completions3=__esm(()=>{Completions2=class Completions2 extends APIResource{create(body,options){return this._client.post("/completions",resolveResourceRequestOptions70(options,(options)=>withBodyFinalization7({body,...options,stream:body.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}}});function resolveResourceRequestOptions71(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Content;var init_content=__esm(()=>{init_headers();init_path();Content=class Content extends APIResource{retrieve(fileID,params,options){let{container_id}=params;return this._client.get(path`/containers/${container_id}/files/${fileID}/content`,resolveResourceRequestOptions71(options,(options)=>({...options,headers:buildHeaders([{Accept:"application/binary"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}}});function resolveResourceRequestOptions72(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization8(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery46(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys46.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys46.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys46,Files2;var init_files3=__esm(()=>{init_content();init_content();init_pagination();init_headers();init_uploads();init_path();normalizeRequestOptionsForQueryKeys46=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Files2=class Files2 extends APIResource{constructor(){super(...arguments);this.content=new Content(this._client)}create(containerID,body,options){return this._client.post(path`/containers/${containerID}/files`,resolveResourceRequestOptions72(options,(options)=>maybeMultipartFormRequestOptions(withBodyFinalization8({body,...options,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client)))}retrieve(fileID,params,options){let{container_id}=params;return this._client.get(path`/containers/${container_id}/files/${fileID}`,resolveResourceRequestOptions72(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(containerID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery46(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/containers/${containerID}/files`,CursorPage,resolveResourceRequestOptions72(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(fileID,params,options){let{container_id}=params;return this._client.delete(path`/containers/${container_id}/files/${fileID}`,resolveResourceRequestOptions72(options,(options)=>({...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}};Files2.Content=Content});function resolveResourceRequestOptions73(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery47(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys47.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys47.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys47,Containers;var init_containers=__esm(()=>{init_files3();init_files3();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys47=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Containers=class Containers extends APIResource{constructor(){super(...arguments);this.files=new Files2(this._client)}create(body,options){return this._client.post("/containers",resolveResourceRequestOptions73(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(containerID,options){return this._client.get(path`/containers/${containerID}`,resolveResourceRequestOptions73(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery47(query,["after","limit","name","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/containers",CursorPage,resolveResourceRequestOptions73(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(containerID,options){return this._client.delete(path`/containers/${containerID}`,resolveResourceRequestOptions73(options,(options)=>({...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}};Containers.Files=Files2});function resolveResourceRequestOptions74(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var ContentProvenanceChecks;var init_content_provenance_checks=__esm(()=>{init_uploads();ContentProvenanceChecks=class ContentProvenanceChecks extends APIResource{create(body,options){return this._client.post("/content_provenance_checks",resolveResourceRequestOptions74(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}}});function resolveResourceRequestOptions75(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery48(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys48.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys48.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys48,Items5;var init_items5=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys48=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Items5=class Items5 extends APIResource{create(conversationID,params,options){let{include,...body}=params;return this._client.post(path`/conversations/${conversationID}/items`,resolveResourceRequestOptions75(options,(options)=>({query:{include},body,...options,__security:{bearerAuth:!0}})))}retrieve(itemID,params,options){let{conversation_id,...query}=params;return this._client.get(path`/conversations/${conversation_id}/items/${itemID}`,resolveResourceRequestOptions75(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}list(conversationID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery48(query,["after","include","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/conversations/${conversationID}/items`,ConversationCursorPage,resolveResourceRequestOptions75(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(itemID,params,options){let{conversation_id}=params;return this._client.delete(path`/conversations/${conversation_id}/items/${itemID}`,resolveResourceRequestOptions75(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions76(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Conversations;var init_conversations=__esm(()=>{init_items5();init_items5();init_path();Conversations=class Conversations extends APIResource{constructor(){super(...arguments);this.items=new Items5(this._client)}create(body={},options){return this._client.post("/conversations",resolveResourceRequestOptions76(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(conversationID,options){return this._client.get(path`/conversations/${conversationID}`,resolveResourceRequestOptions76(options,(options)=>({...options,__security:{bearerAuth:!0}})))}update(conversationID,body,options){return this._client.post(path`/conversations/${conversationID}`,resolveResourceRequestOptions76(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}delete(conversationID,options){return this._client.delete(path`/conversations/${conversationID}`,resolveResourceRequestOptions76(options,(options)=>({...options,__security:{bearerAuth:!0}})))}};Conversations.Items=Items5});function resolveResourceRequestOptions77(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Decisions;var init_decisions=__esm(()=>{Decisions=class Decisions extends APIResource{create(body,options){return this._client.post("/decisions",resolveResourceRequestOptions77(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}}});function createEmbedding(client,body,options){let hasUserProvidedEncodingFormat=!!body.encoding_format,encodingFormat=hasUserProvidedEncodingFormat?body.encoding_format:"base64";if(hasUserProvidedEncodingFormat)loggerFor(client).debug("embeddings/user defined encoding_format:",body.encoding_format);let requestOptions={body:{...body,encoding_format:encodingFormat},...options,__security:{bearerAuth:!0}},response=client.post("/embeddings",requestOptions);if(hasUserProvidedEncodingFormat)return response;return loggerFor(client).debug("embeddings/decoding base64 embeddings from base64"),response._thenUnwrap((data)=>{let embeddings=data?.data;if(embeddings!==void 0){if(!Array.isArray(embeddings))throw TypeError("Expected embeddings response data to be an array");let{length}=embeddings;for(let index=0;index<length;index+=1)if(index in embeddings){let embeddingBase64Obj=embeddings[index],{embedding}=embeddingBase64Obj;if(Array.isArray(embedding))continue;embeddingBase64Obj.embedding=toFloat32Array(embedding)}}return data})}var init_embeddings=__esm(()=>{init_utils2()});var Embeddings;var init_embeddings2=__esm(()=>{init_embeddings();Embeddings=class Embeddings extends APIResource{create(body,options){return createEmbedding(this._client,body,options)}}});function resolveResourceRequestOptions78(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var OutputItems;var init_output_items=__esm(()=>{init_pagination();init_path();OutputItems=class OutputItems extends APIResource{retrieve(outputItemID,params,options){let{eval_id,run_id}=params;return this._client.get(path`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`,resolveResourceRequestOptions78(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(runID,params,options){let{eval_id,...query}=params;return this._client.getAPIList(path`/evals/${eval_id}/runs/${runID}/output_items`,CursorPage,resolveResourceRequestOptions78(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions79(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery49(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys49.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys49.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys49,Runs2;var init_runs2=__esm(()=>{init_output_items();init_output_items();init_pagination();init_path();normalizeRequestOptionsForQueryKeys49=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Runs2=class Runs2 extends APIResource{constructor(){super(...arguments);this.outputItems=new OutputItems(this._client)}create(evalID,body,options){return this._client.post(path`/evals/${evalID}/runs`,resolveResourceRequestOptions79(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(runID,params,options){let{eval_id}=params;return this._client.get(path`/evals/${eval_id}/runs/${runID}`,resolveResourceRequestOptions79(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(evalID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery49(query,["after","limit","order","status"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/evals/${evalID}/runs`,CursorPage,resolveResourceRequestOptions79(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(runID,params,options){let{eval_id}=params;return this._client.delete(path`/evals/${eval_id}/runs/${runID}`,resolveResourceRequestOptions79(options,(options)=>({...options,__security:{bearerAuth:!0}})))}cancel(runID,params,options){let{eval_id}=params;return this._client.post(path`/evals/${eval_id}/runs/${runID}/cancel`,resolveResourceRequestOptions79(options,(options)=>({...options,__security:{bearerAuth:!0}})))}};Runs2.OutputItems=OutputItems});function resolveResourceRequestOptions80(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery50(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys50.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys50.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys50,Evals;var init_evals=__esm(()=>{init_runs2();init_runs2();init_pagination();init_path();normalizeRequestOptionsForQueryKeys50=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Evals=class Evals extends APIResource{constructor(){super(...arguments);this.runs=new Runs2(this._client)}create(body,options){return this._client.post("/evals",resolveResourceRequestOptions80(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(evalID,options){return this._client.get(path`/evals/${evalID}`,resolveResourceRequestOptions80(options,(options)=>({...options,__security:{bearerAuth:!0}})))}update(evalID,body,options){return this._client.post(path`/evals/${evalID}`,resolveResourceRequestOptions80(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery50(query,["after","limit","order","order_by"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/evals",CursorPage,resolveResourceRequestOptions80(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(evalID,options){return this._client.delete(path`/evals/${evalID}`,resolveResourceRequestOptions80(options,(options)=>({...options,__security:{bearerAuth:!0}})))}};Evals.Runs=Runs2});async function waitForFileProcessing(resource,id,pollInterval,maxWait){let terminalStates=new Set(["processed","error","deleted"]),start=performance.now(),file=await resource.retrieve(id);while(!file.status||!terminalStates.has(file.status))if(await sleep(pollInterval),file=await resource.retrieve(id),performance.now()-start>maxWait)throw new APIConnectionTimeoutError({message:`Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`});return file}var init_file_processing=__esm(()=>{init_error2()});function resolveResourceRequestOptions81(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery51(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys51.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys51.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys51,Files3;var init_files4=__esm(()=>{init_pagination();init_headers();init_uploads();init_file_processing();init_path();normalizeRequestOptionsForQueryKeys51=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Files3=class Files3 extends APIResource{create(body,options){return this._client.post("/files",resolveResourceRequestOptions81(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}retrieve(fileID,options){return this._client.get(path`/files/${fileID}`,resolveResourceRequestOptions81(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery51(query,["after","limit","order","purpose"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/files",CursorPage,resolveResourceRequestOptions81(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(fileID,options){return this._client.delete(path`/files/${fileID}`,resolveResourceRequestOptions81(options,(options)=>({...options,__security:{bearerAuth:!0}})))}content(fileID,options){return this._client.get(path`/files/${fileID}/content`,resolveResourceRequestOptions81(options,(options)=>({...options,headers:buildHeaders([{Accept:"application/binary"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}async waitForProcessing(id,{pollInterval=5000,maxWait=1800000}={}){return await waitForFileProcessing(this,id,pollInterval,maxWait)}}});var Methods;var init_methods=__esm(()=>{Methods=class Methods extends APIResource{}});function resolveResourceRequestOptions82(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Graders;var init_graders=__esm(()=>{Graders=class Graders extends APIResource{run(body,options){return this._client.post("/fine_tuning/alpha/graders/run",resolveResourceRequestOptions82(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}validate(body,options){return this._client.post("/fine_tuning/alpha/graders/validate",resolveResourceRequestOptions82(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}}});var Alpha;var init_alpha=__esm(()=>{init_graders();init_graders();Alpha=class Alpha extends APIResource{constructor(){super(...arguments);this.graders=new Graders(this._client)}};Alpha.Graders=Graders});function resolveResourceRequestOptions83(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery52(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys52.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys52.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys52,Permissions;var init_permissions=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys52=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Permissions=class Permissions extends APIResource{create(fineTunedModelCheckpoint,body,options){return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,Page,resolveResourceRequestOptions83(options,(options)=>({body,method:"post",...options,__security:{adminAPIKeyAuth:!0}})))}retrieve(fineTunedModelCheckpoint,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery52(query,["after","limit","order","project_id"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.get(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,resolveResourceRequestOptions83(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}list(fineTunedModelCheckpoint,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery52(query,["after","limit","order","project_id"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,ConversationCursorPage,resolveResourceRequestOptions83(options,(options)=>({query,...options,__security:{adminAPIKeyAuth:!0}})))}delete(permissionID,params,options){let{fine_tuned_model_checkpoint}=params;return this._client.delete(path`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`,resolveResourceRequestOptions83(options,(options)=>({...options,__security:{adminAPIKeyAuth:!0}})))}}});var Checkpoints;var init_checkpoints=__esm(()=>{init_permissions();init_permissions();Checkpoints=class Checkpoints extends APIResource{constructor(){super(...arguments);this.permissions=new Permissions(this._client)}};Checkpoints.Permissions=Permissions});function resolveResourceRequestOptions84(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery53(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys53.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys53.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys53,Checkpoints2;var init_checkpoints2=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys53=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Checkpoints2=class Checkpoints2 extends APIResource{list(fineTuningJobID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery53(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`,CursorPage,resolveResourceRequestOptions84(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions85(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery54(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys54.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys54.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys54,Jobs;var init_jobs=__esm(()=>{init_checkpoints2();init_checkpoints2();init_pagination();init_path();normalizeRequestOptionsForQueryKeys54=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Jobs=class Jobs extends APIResource{constructor(){super(...arguments);this.checkpoints=new Checkpoints2(this._client)}create(body,options){return this._client.post("/fine_tuning/jobs",resolveResourceRequestOptions85(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(fineTuningJobID,options){return this._client.get(path`/fine_tuning/jobs/${fineTuningJobID}`,resolveResourceRequestOptions85(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery54(query,["after","limit","metadata"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/fine_tuning/jobs",CursorPage,resolveResourceRequestOptions85(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}cancel(fineTuningJobID,options){return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/cancel`,resolveResourceRequestOptions85(options,(options)=>({...options,__security:{bearerAuth:!0}})))}listEvents(fineTuningJobID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery54(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/events`,CursorPage,resolveResourceRequestOptions85(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}pause(fineTuningJobID,options){return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/pause`,resolveResourceRequestOptions85(options,(options)=>({...options,__security:{bearerAuth:!0}})))}resume(fineTuningJobID,options){return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/resume`,resolveResourceRequestOptions85(options,(options)=>({...options,__security:{bearerAuth:!0}})))}};Jobs.Checkpoints=Checkpoints2});var FineTuning;var init_fine_tuning=__esm(()=>{init_methods();init_methods();init_alpha();init_alpha();init_checkpoints();init_checkpoints();init_jobs();init_jobs();FineTuning=class FineTuning extends APIResource{constructor(){super(...arguments);this.methods=new Methods(this._client),this.jobs=new Jobs(this._client),this.checkpoints=new Checkpoints(this._client),this.alpha=new Alpha(this._client)}};FineTuning.Methods=Methods;FineTuning.Jobs=Jobs;FineTuning.Checkpoints=Checkpoints;FineTuning.Alpha=Alpha});var GraderModels;var init_grader_models=__esm(()=>{GraderModels=class GraderModels extends APIResource{}});var Graders2;var init_graders2=__esm(()=>{init_grader_models();init_grader_models();Graders2=class Graders2 extends APIResource{constructor(){super(...arguments);this.graderModels=new GraderModels(this._client)}};Graders2.GraderModels=GraderModels});function resolveResourceRequestOptions86(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization9(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}var Images;var init_images=__esm(()=>{init_uploads();Images=class Images extends APIResource{createVariation(body,options){return this._client.post("/images/variations",resolveResourceRequestOptions86(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}edit(body,options){return this._client.post("/images/edits",resolveResourceRequestOptions86(options,(options)=>multipartFormRequestOptions(withBodyFinalization9(((requestOptions)=>({...requestOptions,body:Object.fromEntries(Object.entries(requestOptions.body??{}).map(([key,value])=>[key,key==="safety_identifier"&&value===null?void 0:value]))}))({body,...options,stream:body.stream??!1,__metadata:{...options?.__metadata,...body.model==null?{}:{model:body.model}},__security:{bearerAuth:!0}}),{streamFromBody:!0}),this._client)))}generate(body,options){return this._client.post("/images/generations",resolveResourceRequestOptions86(options,(options)=>withBodyFinalization9({body,...options,stream:body.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}}});function resolveResourceRequestOptions87(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Sessions4;var init_sessions4=__esm(()=>{init_headers();init_path();Sessions4=class Sessions4 extends APIResource{accept(sessionID,body,options){return this._client.post(path`/live/sessions/${sessionID}/accept`,resolveResourceRequestOptions87(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}downloadRecording(sessionID,options){return this._client.get(path`/live/sessions/${sessionID}/content`,resolveResourceRequestOptions87(options,(options)=>({...options,headers:buildHeaders([{Accept:"application/binary"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}fork(sessionID,body,options){return this._client.post(path`/live/sessions/${sessionID}/fork`,resolveResourceRequestOptions87(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}hangup(sessionID,options){return this._client.post(path`/live/sessions/${sessionID}/hangup`,resolveResourceRequestOptions87(options,(options)=>({...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}refer(sessionID,body,options){return this._client.post(path`/live/sessions/${sessionID}/refer`,resolveResourceRequestOptions87(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}reject(sessionID,body,options){return this._client.post(path`/live/sessions/${sessionID}/reject`,resolveResourceRequestOptions87(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}}});var Forks;var init_forks=__esm(()=>{Forks=class Forks extends APIResource{}});var Sideband;var init_sideband=__esm(()=>{Sideband=class Sideband extends APIResource{}});function resolveResourceRequestOptions88(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Live;var init_live=__esm(()=>{init_sessions4();init_sessions4();init_forks();init_forks();init_sideband();init_sideband();Live=class Live extends APIResource{constructor(){super(...arguments);this.sideband=new Sideband(this._client),this.forks=new Forks(this._client),this.sessions=new Sessions4(this._client)}create(body,options){return this._client.post("/live/sessions",resolveResourceRequestOptions88(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}};Live.Sideband=Sideband;Live.Forks=Forks;Live.Sessions=Sessions4});function resolveResourceRequestOptions89(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Models;var init_models=__esm(()=>{init_pagination();init_path();Models=class Models extends APIResource{retrieve(model,options){return this._client.get(path`/models/${model}`,resolveResourceRequestOptions89(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(options){return this._client.getAPIList("/models",Page,resolveResourceRequestOptions89(options,(options)=>({...options,__security:{bearerAuth:!0}})))}delete(model,options){return this._client.delete(path`/models/${model}`,resolveResourceRequestOptions89(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions90(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Moderations;var init_moderations=__esm(()=>{Moderations=class Moderations extends APIResource{create(body,options){return this._client.post("/moderations",resolveResourceRequestOptions90(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}}});async function encodedMultipartFormRequestOptions(options,client,encodings,rawBodyField=null){if(options.body===null||typeof options.body!=="object"||Array.isArray(options.body))throw TypeError("Multipart request body must be an object");let body=Object.fromEntries(Object.entries(options.body).filter(([,value])=>value!==void 0));if(rawBodyField!==null&&Object.keys(body).length===1&&Object.prototype.hasOwnProperty.call(body,rawBodyField)){let value=body[rawBodyField];if(typeof value!=="string")throw TypeError("Raw multipart alternative must be a string");return{...options,body:value,headers:buildHeaders([options.headers,{"content-type":encodings[rawBodyField].content_type}])}}let encoded=[];for(let[name,encoding]of Object.entries(encodings)){if(!Object.prototype.hasOwnProperty.call(body,name))continue;let value=body[name],data=encoding.json?JSON.stringify(value):value;if(typeof data!=="string")throw TypeError(`Multipart field ${name} must encode as a string`);encoded.push([name,makeFile([data],"",{type:encoding.content_type})]),delete body[name]}let form=(await multipartFormRequestOptions({...options,body},client)).body;if(!(form instanceof FormData))throw await form.cancel(),TypeError("Unexpected streaming upload in typed multipart request body");for(let[name,part]of encoded)form.append(name,part,"");return{...options,body:form,headers:buildHeaders([options.headers,{"content-type":null}])}}var init_multipart_encoding=__esm(()=>{init_uploads();init_headers()});function resolveResourceRequestOptions91(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Calls;var init_calls=__esm(()=>{init_headers();init_path();init_multipart_encoding();Calls=class Calls extends APIResource{create(body,options){return this._client.post("/realtime/calls",resolveResourceRequestOptions91(options,(options)=>encodedMultipartFormRequestOptions({body,...options,headers:buildHeaders([{Accept:"application/sdp"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp")))}accept(callID,body,options){return this._client.post(path`/realtime/calls/${callID}/accept`,resolveResourceRequestOptions91(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}hangup(callID,options){return this._client.post(path`/realtime/calls/${callID}/hangup`,resolveResourceRequestOptions91(options,(options)=>({...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}refer(callID,body,options){return this._client.post(path`/realtime/calls/${callID}/refer`,resolveResourceRequestOptions91(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}reject(callID,body={},options){return this._client.post(path`/realtime/calls/${callID}/reject`,resolveResourceRequestOptions91(options,(options)=>({body,...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions92(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var ClientSecrets;var init_client_secrets=__esm(()=>{ClientSecrets=class ClientSecrets extends APIResource{create(body,options){return this._client.post("/realtime/client_secrets",resolveResourceRequestOptions92(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions93(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var ClientSecrets2;var init_client_secrets2=__esm(()=>{ClientSecrets2=class ClientSecrets2 extends APIResource{create(body,options){return this._client.post("/realtime/translations/client_secrets",resolveResourceRequestOptions93(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}}});var Translations2;var init_translations2=__esm(()=>{init_client_secrets2();init_client_secrets2();Translations2=class Translations2 extends APIResource{constructor(){super(...arguments);this.clientSecrets=new ClientSecrets2(this._client)}};Translations2.ClientSecrets=ClientSecrets2});var Realtime2;var init_realtime2=__esm(()=>{init_calls();init_calls();init_client_secrets();init_client_secrets();init_translations2();init_translations2();Realtime2=class Realtime2 extends APIResource{constructor(){super(...arguments);this.clientSecrets=new ClientSecrets(this._client),this.calls=new Calls(this._client),this.translations=new Translations2(this._client)}};Realtime2.ClientSecrets=ClientSecrets;Realtime2.Calls=Calls;Realtime2.Translations=Translations2});function resolveResourceRequestOptions94(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery55(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys55.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys55.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys55,InputItems2;var init_input_items2=__esm(()=>{init_pagination();init_path();normalizeRequestOptionsForQueryKeys55=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);InputItems2=class InputItems2 extends APIResource{list(responseID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery55(query,["after","include","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/responses/${responseID}/input_items`,CursorPage,resolveResourceRequestOptions94(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions95(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var InputTokens2;var init_input_tokens2=__esm(()=>{InputTokens2=class InputTokens2 extends APIResource{count(body={},options){return this._client.post("/responses/input_tokens",resolveResourceRequestOptions95(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}}});function isTextFormat(value){return isObj(value)&&typeof value.type==="string"}function effectiveTextFormat({body},parseAs){if(parseAs===null||!isObj(body))return parseAs??null;let{input}=body;if(Array.isArray(input))for(let index=input.length-1;index>=0;index-=1){let item=input[index];if(!isObj(item)||item.type!=="configuration_update")continue;let{text}=item;if(!isObj(text))continue;let{format}=text;if(!isTextFormat(format))continue;if(format.type==="text"&&parseAs!==void 0)throw new OpenAIError("Cannot use parseAs with a plain-text format update.");return parseAs??format}let{text}=body,format=isObj(text)?text.format:null;return parseAs??(isTextFormat(format)?format:null)}function resolveResponseParseOptions(params,options){let parseAs=options&&hasOwn(options,"parseAs")?options.parseAs:void 0;if(parseAs!=null)effectiveTextFormat({body:params},parseAs);let requestOptions={...options};delete requestOptions.parseAs;let captured;return requestOptions.__metadata={...options?.__metadata,captureResponseParser(prepared){let format=effectiveTextFormat(prepared,parseAs);captured=format===null?null:{type:format.type,$brand:"$brand"in format?format.$brand:void 0,$parseRaw:"$parseRaw"in format?format.$parseRaw:void 0}}},{getTextFormat:(prepared)=>captured===void 0?effectiveTextFormat(prepared,parseAs):captured,requestOptions}}function maybeParseResponse(response,params,format=params&&effectiveTextFormat({body:params})){if(!params||!hasAutoParseableInput2(params,format)){let parsed={...response,output_parsed:null,output:response.output.map((item)=>{if(item.type==="function_call")return{...item,parsed_arguments:null};if(item.type==="message")return{...item,content:item.content.map((content)=>({...content,parsed:null}))};return item})};if(needsOutputText(response,parsed))addOutputText(parsed);return parsed}return parseResponse(response,params,format)}function parseResponse(response,params,format=effectiveTextFormat({body:params})){let shouldParse=!response.status||response.status==="completed",output=response.output.map((item)=>{if(item.type==="function_call")return shouldParse?parseToolCall2(params,item):{...item,parsed_arguments:null};if(item.type==="message"){let content=item.content.map((content)=>{if(content.type==="output_text")return{...content,parsed:shouldParse&&(item.phase==null||item.phase==="final_answer")?parseResponseFormatContent(format,content.text):null};return content});return{...item,content}}return item}),parsed={...response,output};if(needsOutputText(response,parsed))addOutputText(parsed);return Object.defineProperty(parsed,"output_parsed",{enumerable:!0,get(){for(let output of parsed.output){if(output.type!=="message")continue;for(let content of output.content)if(content.type==="output_text"&&content.parsed!==null)return content.parsed}return null}}),parsed}function hasAutoParseableInput2(params,format=effectiveTextFormat({body:params})){if(isParseableResponseFormat(format))return!0;return Array.isArray(params.tools)&&params.tools.some((tool)=>isAutoParsableTool2(tool)||tool.type==="function"&&tool.strict===!0||tool.type==="namespace"&&tool.tools.some((nested)=>nested.type==="function"&&(isAutoParsableTool2(nested)||nested.strict===!0)))}function isAutoParsableTool2(tool){return tool?.$brand==="auto-parseable-tool"}function getInputToolByName(input_tools,name,namespace){for(let tool of input_tools)if(namespace==null){if(tool.type==="function"&&tool.name===name)return tool}else if(tool.type==="namespace"&&tool.name===namespace)return tool.tools.find((nested)=>nested.type==="function"&&nested.name===name);if(namespace===name)return input_tools.find((tool)=>tool.type==="function"&&tool.name===name&&tool.defer_loading===!0);return}function parseToolCall2(params,toolCall){let inputTool=getInputToolByName(params.tools??[],toolCall.name,toolCall.namespace),parsedArguments=null;if(isAutoParsableTool2(inputTool))parsedArguments=inputTool.$parseRaw(toolCall.arguments);else if(inputTool?.strict)parsedArguments=parseResponseFormatContent({type:"json_schema",$parseRaw:void 0},toolCall.arguments);return{...toolCall,parsed_arguments:parsedArguments}}function needsOutputText(response,target){return!Object.getOwnPropertyDescriptor(response,"output_text")||target.output_text==null}function addOutputText(rsp){let texts=[];for(let output of rsp.output){if(output.type!=="message")continue;for(let content of output.content)if(content.type==="output_text")texts.push(content.text)}rsp.output_text=texts.join("")}var init_ResponsesParser=__esm(()=>{init_error2();init_values();init_parser()});class OutputTextIndex{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(value){if(this.size===this.capacity)this.grow();let index=this.size;this.size+=1,this.update(index,value)}update(index,value){if(!Number.isSafeInteger(index)||index<0||index>=this.size)throw RangeError(`missing output at index ${index}`);let node=this.capacity+index,difference=value-(this.values[node]??0);if(difference===0)return;while(node>=1)this.values[node]=(this.values[node]??0)+difference,node=Math.floor(node/2)}prefixSum(end){if(!Number.isSafeInteger(end)||end<0||end>this.size)throw RangeError(`missing output at index ${end}`);let start=this.capacity,stop=this.capacity+end,sum=0;while(start<stop){if(start%2===1)sum+=this.values[start]??0,start+=1;if(stop%2===1)stop-=1,sum+=this.values[stop]??0;start=Math.floor(start/2),stop=Math.floor(stop/2)}return sum}grow(){let previousCapacity=this.capacity;this.capacity*=2;let values=Array.from({length:this.capacity*2},()=>0);for(let index=0;index<this.size;index+=1)values[this.capacity+index]=this.values[previousCapacity+index]??0;for(let index=this.capacity-1;index>0;index-=1)values[index]=(values[index*2]??0)+(values[index*2+1]??0);this.values=values}}function createCanonicalResponseContext(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new OutputTextIndex}}function getOutputText(context,output){if(output.type!=="message")return"";let text="";for(let content of output.content)if(content.type==="output_text")text+=content.text;return context.outputTextLengths.set(output,text.length),text}function ensureCanonicalOutputText(context,snapshot){if(context.deferOutputText){context.canonicalSnapshot=void 0;return}if(context.canonicalSnapshot===snapshot)return;let outputTextIndex=new OutputTextIndex,text="";for(let output of snapshot.output){let outputText=getOutputText(context,output);text+=outputText,outputTextIndex.append(outputText.length)}snapshot.output_text=text,context.outputTextIndex=outputTextIndex,context.canonicalSnapshot=snapshot}function cloneResponse(context,response){context.canonicalSnapshot=void 0,context.outputTextLengths=new WeakMap,context.outputTextIndex=new OutputTextIndex;let snapshot=structuredClone(response);if(!Object.getOwnPropertyDescriptor(snapshot,"output_text")||snapshot.output_text===null||snapshot.output_text===void 0)ensureCanonicalOutputText(context,snapshot);else if(snapshot.output.length===0&&snapshot.output_text==="")context.canonicalSnapshot=snapshot;return snapshot}function updateCachedOutputTextLength(context,output,outputIndex,previousText,nextText){if(context.deferOutputText)return;let length=context.outputTextLengths.get(output);if(length!==void 0){let nextLength=length-previousText.length+nextText.length;context.outputTextLengths.set(output,nextLength),context.outputTextIndex.update(outputIndex,nextLength)}}function replaceOutputTextSuffix(snapshot,previousText,nextText){if(previousText.length===0){snapshot.output_text+=nextText;return}snapshot.output_text=snapshot.output_text.slice(0,snapshot.output_text.length-previousText.length)+nextText}function getPrecedingContentTextLength(context,output,contentIndex,nextText){if(contentIndex===void 0||output?.type!=="message")return 0;if(contentIndex<output.content.length-contentIndex-1){let precedingContentLength=0;for(let index=0;index<contentIndex;index+=1){let precedingContent=output.content[index];if(precedingContent?.type==="output_text")precedingContentLength+=precedingContent.text.length}return precedingContentLength}let followingContentLength=0;for(let index=contentIndex+1;index<output.content.length;index+=1){let followingContent=output.content[index];if(followingContent?.type==="output_text")followingContentLength+=followingContent.text.length}return(context.outputTextLengths.get(output)??getOutputText(context,output).length)-followingContentLength-nextText.length}function updateOutputText(context,snapshot,outputIndex,previousText,nextText,contentIndex){if(previousText===nextText)return;if(context.deferOutputText){context.outputTextDirty=!0;return}let output=snapshot.output[outputIndex];if(outputIndex===snapshot.output.length-1&&(contentIndex===void 0||output?.type==="message"&&contentIndex===output.content.length-1)){replaceOutputTextSuffix(snapshot,previousText,nextText);return}let precedingContentLength=getPrecedingContentTextLength(context,output,contentIndex,nextText),offset=context.outputTextIndex.prefixSum(outputIndex)+precedingContentLength;if(offset+previousText.length===snapshot.output_text.length){replaceOutputTextSuffix(snapshot,previousText,nextText);return}snapshot.output_text=snapshot.output_text.slice(0,offset)+nextText+snapshot.output_text.slice(offset+previousText.length)}var init_canonical_output_text=()=>{};function validateArrayIndex(collection,index,kind,allowAppend=!1){if(!Array.isArray(collection)||!Number.isSafeInteger(index)||index<0||index>collection.length||(index===collection.length?!allowAppend||index in collection:!hasOwn(collection,index)))throw new OpenAIError(`missing ${kind} at index ${index}`)}function validateArrayAppend(collection,index,kind){if(index!==collection.length)throw new OpenAIError(`missing ${kind} at index ${index}`);validateArrayIndex(collection,index,kind,!0)}function getOutput(snapshot,outputIndex){validateArrayIndex(snapshot.output,outputIndex,"output");let output=snapshot.output[outputIndex];if(!output)throw new OpenAIError(`missing output at index ${outputIndex}`);return output}function hasRoutedOutputCallIdentity(output){return output.type==="function_call"||output.type==="custom_tool_call"||output.type==="shell_call"||output.type==="shell_call_output"}function getOutputItemIdentityKeys(output,eventType){if(!hasOwn(output,"type")||typeof output.type!=="string")throw new OpenAIError(`expected an own output item type for ${eventType}`);let optionalPlatformID=output.type==="function_call"||output.type==="custom_tool_call",identities=[];if(hasOwn(output,"id")){if(typeof output.id!=="string"||output.id.length===0&&output.type!=="computer_call")throw new OpenAIError(`expected a non-empty output item id for ${eventType}`);identities.push(`id:${output.id}`)}else if(!optionalPlatformID)throw new OpenAIError(`expected a non-empty output item id for ${eventType}`);if(hasRoutedOutputCallIdentity(output)){if(!hasOwn(output,"call_id")||typeof output.call_id!=="string"||output.call_id.length===0&&output.type!=="function_call")throw new OpenAIError(`expected a non-empty output item call_id for ${eventType}`);identities.push(`call:${output.type}:${output.call_id}`)}return identities}function assertOutputItemIdentitiesAvailable(identities,keys){for(let key of keys)if(identities.has(key))throw new OpenAIError(`duplicate output item identity '${key}'`)}function addOutputItemIdentities(identities,keys){assertOutputItemIdentitiesAvailable(identities,keys);for(let key of keys)identities.add(key)}function createResponseOutputIdentityIndex(snapshot){let identityIndex={snapshot,output:snapshot.output,length:snapshot.output.length,identities:new Set};for(let index=0;index<snapshot.output.length;index+=1){let output=getOutput(snapshot,index);addOutputItemIdentities(identityIndex.identities,getOutputItemIdentityKeys(output,"response snapshot"))}return identityIndex}function getResponseOutputIdentityIndex(context,snapshot){let cached=responseOutputIdentityIndexes.get(context);if(cached&&cached.snapshot===snapshot&&cached.output===snapshot.output&&cached.length===snapshot.output.length)return cached;let identityIndex=createResponseOutputIdentityIndex(snapshot);return responseOutputIdentityIndexes.set(context,identityIndex),identityIndex}function cloneValidatedResponse(context,response){let nextContext=createCanonicalResponseContext(),snapshot=cloneResponse(nextContext,response),identityIndex=createResponseOutputIdentityIndex(snapshot);return context.canonicalSnapshot=nextContext.canonicalSnapshot,context.outputTextLengths=nextContext.outputTextLengths,context.outputTextIndex=nextContext.outputTextIndex,responseOutputIdentityIndexes.set(context,identityIndex),snapshot}function getExpectedOutputItemType(event){if(event.type==="response.content_part.added"||event.type==="response.content_part.done")return event.part.type==="reasoning_text"?"reasoning":"message";return expectedOutputItemTypes[event.type]}function validateResponseOutputItemIdentity(output,replacement,eventType){if(getOutputItemIdentityKeys(output,eventType),getOutputItemIdentityKeys(replacement,eventType),!hasOwn(replacement,"type")||output.type!==replacement.type)throw new OpenAIError(`expected output item type '${output.type}', got '${replacement.type}'`);let outputID=hasOwn(output,"id")?output.id:void 0,replacementID=hasOwn(replacement,"id")?replacement.id:void 0,addsOptionalID=outputID===void 0&&(output.type==="function_call"||output.type==="custom_tool_call");if(outputID!==replacementID&&!addsOptionalID)throw new OpenAIError(`expected output item id '${outputID}', got '${replacementID}'`);if(hasRoutedOutputCallIdentity(output)&&hasRoutedOutputCallIdentity(replacement)&&output.call_id!==replacement.call_id)throw new OpenAIError(`expected output item call_id '${output.call_id}', got '${replacement.call_id}'`)}function validateOutputItemIdentity(event,snapshot,rejectInvalidShellTargets){if(event.type==="response.output_item.done")return;if(rejectInvalidShellTargets&&(event.type==="response.shell_call_command.added"||event.type==="response.shell_call_command.delta"||event.type==="response.shell_call_command.done")){let output=getOutput(snapshot,event.output_index);if(!hasOwn(output,"type")||output.type!=="shell_call")throw new OpenAIError(`expected output item type 'shell_call', got '${output.type}'`);return}if(event.type!=="response.content_part.added"&&event.type!=="response.content_part.done"&&!hasOwn(expectedOutputItemTypes,event.type))return;let itemEvent=event;if(!hasOwn(event,"item_id")||typeof itemEvent.item_id!=="string"||itemEvent.item_id.length===0)throw new OpenAIError(`expected a non-empty item_id for ${event.type}`);let output=getOutput(snapshot,itemEvent.output_index),outputID=hasOwn(output,"id")?output.id:void 0;if(outputID!==itemEvent.item_id)throw new OpenAIError(`expected item_id '${outputID}', got '${itemEvent.item_id}'`);let expectedType=getExpectedOutputItemType(itemEvent);if(output.type!==expectedType)throw new OpenAIError(`expected output item type '${expectedType}', got '${output.type}'`)}function getContent(content,contentIndex){validateArrayIndex(content,contentIndex,"content");let part=content[contentIndex];if(!part)throw new OpenAIError(`missing content at index ${contentIndex}`);return part}function getShellOutputContent(snapshot,output,commandIndex){let shellCall=snapshot.output.find((item)=>item.type==="shell_call"&&item.call_id===output.call_id);if(shellCall)validateArrayIndex(shellCall.action.commands,commandIndex,"command");else validateArrayIndex(output.output,commandIndex,"content",!0);while(output.output.length<=commandIndex)output.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return getContent(output.output,commandIndex)}function createSupportedResponseEventTypes(eventTypes){return new Set(eventTypes)}function assertNever3(_value){throw new OpenAIError("Unhandled response stream event: unknown")}function sanitizeResponseEvent(event){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(event,"type")}catch{return assertNever3(event)}let type=descriptor?.value;if(typeof type!=="string"||!supportedResponseEventTypes.has(type))return assertNever3(event);let stableValues=new Map([["type",type]]);if(type==="response.output_item.added"||type==="response.output_item.done"||type==="response.content_part.added"||type==="response.content_part.done"||type==="response.shell_call_command.added"||type==="response.shell_call_command.delta"||type==="response.shell_call_command.done"||hasOwn(expectedOutputItemTypes,type))try{for(let field of responseEventRoutingFields){let routingDescriptor=Object.getOwnPropertyDescriptor(event,field);stableValues.set(field,routingDescriptor?event[field]:void 0)}if(type==="response.output_item.added"||type==="response.output_item.done")stableValues.set("item",structuredClone(event.item));else if(type==="response.content_part.added"||type==="response.content_part.done")stableValues.set("part",structuredClone(event.part))}catch{return assertNever3(event)}return new Proxy(event,{get(target,property){return stableValues.has(property)?stableValues.get(property):Reflect.get(target,property,target)}})}function replaceResponseOutputItem(context,snapshot,outputIndex,replacement,updateText=!0){let output=getOutput(snapshot,outputIndex);if(validateResponseOutputItemIdentity(output,replacement,"response.output_item.done"),!hasOwn(output,"id")&&hasOwn(replacement,"id")){let{identities}=getResponseOutputIdentityIndex(context,snapshot);addOutputItemIdentities(identities,[`id:${replacement.id}`])}if(!updateText){snapshot.output[outputIndex]=replacement;return}let previousText=getOutputText(context,output);if(output.type==="message"||replacement.type==="message")ensureCanonicalOutputText(context,snapshot);snapshot.output[outputIndex]=replacement;let nextText=getOutputText(context,replacement);if(context.canonicalSnapshot===snapshot)context.outputTextIndex.update(outputIndex,nextText.length);updateOutputText(context,snapshot,outputIndex,previousText,nextText)}function accumulateOutputItemEvent(event,snapshot,context){switch(event.type){case"response.output_item.added":{validateArrayAppend(snapshot.output,event.output_index,"output");let identityIndex=getResponseOutputIdentityIndex(context,snapshot),output=event.item,identities=getOutputItemIdentityKeys(output,event.type);if(assertOutputItemIdentitiesAvailable(identityIndex.identities,identities),output.type==="message")ensureCanonicalOutputText(context,snapshot);snapshot.output.push(output),addOutputItemIdentities(identityIndex.identities,identities),identityIndex.length=snapshot.output.length;let text=getOutputText(context,output);if(context.canonicalSnapshot===snapshot)context.outputTextIndex.append(text.length);if(text)if(context.deferOutputText)context.outputTextDirty=!0;else snapshot.output_text+=text;return!0}case"response.output_item.done":return replaceResponseOutputItem(context,snapshot,event.output_index,event.item),!0;default:return!1}}function accumulateContentPartAddedEvent(event,snapshot,context){switch(event.type){case"response.content_part.added":{let output=getOutput(snapshot,event.output_index),{type}=output,{part}=event;if(type==="message"&&part.type!=="reasoning_text"){validateArrayAppend(output.content,event.content_index,"content");let content=part;if(content.type==="output_text")ensureCanonicalOutputText(context,snapshot);if(output.content.push(content),content.type==="output_text")updateCachedOutputTextLength(context,output,event.output_index,"",content.text),updateOutputText(context,snapshot,event.output_index,"",content.text,event.content_index)}else if(type==="reasoning"&&part.type==="reasoning_text"){let content=output.content??[];if(validateArrayAppend(content,event.content_index,"content"),!output.content)output.content=content;content.push(part)}return!0}default:return!1}}function accumulateContentPartDoneEvent(event,snapshot,context){switch(event.type){case"response.content_part.done":{let output=getOutput(snapshot,event.output_index),{part}=event;if(output.type==="message"&&part.type!=="reasoning_text"){let content=getContent(output.content,event.content_index),previousText=content.type==="output_text"?content.text:"",replacement=part;if(content.type==="output_text"||replacement.type==="output_text")ensureCanonicalOutputText(context,snapshot);output.content[event.content_index]=replacement;let nextText=replacement.type==="output_text"?replacement.text:"";updateCachedOutputTextLength(context,output,event.output_index,previousText,nextText),updateOutputText(context,snapshot,event.output_index,previousText,nextText,event.content_index)}else if(output.type==="reasoning"&&part.type==="reasoning_text"){let{content}=output;if(!content)throw new OpenAIError(`missing content at index ${event.content_index}`);getContent(content,event.content_index),content[event.content_index]=part}return!0}default:return!1}}function isLogprobWithBytes(value){return isObj(value)&&typeof value.token==="string"&&typeof value.logprob==="number"&&Array.isArray(value.bytes)&&value.bytes.every((byte)=>typeof byte==="number")}function isOutputLogprobs(value){return Array.isArray(value)&&value.every((entry)=>isLogprobWithBytes(entry)&&("top_logprobs"in entry)&&Array.isArray(entry.top_logprobs)&&entry.top_logprobs.every(isLogprobWithBytes))}function accumulateOutputLogprobs(content,event){let logprobs=structuredClone(event.logprobs);if(!isOutputLogprobs(logprobs))return;if(event.type==="response.output_text.done"){if(logprobs.length>0||Array.isArray(content.logprobs)&&content.logprobs.length>0)content.logprobs=logprobs}else if(logprobs.length>0){if(!Array.isArray(content.logprobs))content.logprobs=[];for(let logprob of logprobs)content.logprobs.push(logprob)}}function accumulateOutputTextEvent(event,snapshot,context){switch(event.type){case"response.output_text.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="message"){let content=getContent(output.content,event.content_index);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);accumulateOutputLogprobs(content,event);let previousText=content.text;if(ensureCanonicalOutputText(context,snapshot),content.text=previousText+event.delta,updateCachedOutputTextLength(context,output,event.output_index,previousText,content.text),event.output_index===snapshot.output.length-1&&event.content_index===output.content.length-1)if(context.deferOutputText){if(event.delta!=="")context.outputTextDirty=!0}else snapshot.output_text+=event.delta;else updateOutputText(context,snapshot,event.output_index,previousText,content.text,event.content_index)}return!0}case"response.output_text.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="message"){let content=getContent(output.content,event.content_index);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);accumulateOutputLogprobs(content,event);let previousText=content.text;ensureCanonicalOutputText(context,snapshot),content.text=event.text,updateCachedOutputTextLength(context,output,event.output_index,previousText,event.text),updateOutputText(context,snapshot,event.output_index,previousText,event.text,event.content_index)}return!0}case"response.output_text.annotation.added":{let output=getOutput(snapshot,event.output_index);if(output.type==="message"){let content=getContent(output.content,event.content_index);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);validateArrayIndex(content.annotations,event.annotation_index,"annotation",!0),content.annotations[event.annotation_index]=structuredClone(event.annotation)}return!0}default:return!1}}function accumulateRefusalAndArgumentsEvent(event,snapshot){switch(event.type){case"response.refusal.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="message"){let content=getContent(output.content,event.content_index);if(content.type!=="refusal")throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);content.refusal+=event.delta}return!0}case"response.refusal.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="message"){let content=getContent(output.content,event.content_index);if(content.type!=="refusal")throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);content.refusal=event.refusal}return!0}case"response.function_call_arguments.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="function_call")output.arguments+=event.delta;return!0}case"response.function_call_arguments.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="function_call")output.arguments=event.arguments;return!0}case"response.custom_tool_call_input.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="custom_tool_call")output.input+=event.delta;return!0}case"response.custom_tool_call_input.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="custom_tool_call")output.input=event.input;return!0}case"response.mcp_call_arguments.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="mcp_call")output.arguments+=event.delta;return!0}case"response.mcp_call_arguments.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="mcp_call")output.arguments=event.arguments;return!0}default:return!1}}function accumulateShellEvent(event,snapshot){switch(event.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="shell_call"){let allowAppend=event.type==="response.shell_call_command.added";validateArrayIndex(output.action.commands,event.command_index,"command",allowAppend),output.action.commands[event.command_index]=event.command}return!0}case"response.shell_call_command.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="shell_call")validateArrayIndex(output.action.commands,event.command_index,"command"),output.action.commands[event.command_index]+=event.delta;return!0}case"response.shell_call_output_content.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="shell_call_output"){let content=getShellOutputContent(snapshot,output,event.command_index);content.stdout+=event.delta.stdout??"",content.stderr+=event.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="shell_call_output"){let content=getContent(event.output,0);getShellOutputContent(snapshot,output,event.command_index),output.output[event.command_index]=structuredClone(content)}return!0}default:return!1}}function accumulateReasoningEvent(event,snapshot){switch(event.type){case"response.reasoning_text.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="reasoning"){if(!output.content)throw new OpenAIError(`missing content at index ${event.content_index}`);let content=getContent(output.content,event.content_index);if(content.type!=="reasoning_text")throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);content.text+=event.delta}return!0}case"response.reasoning_text.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="reasoning"){if(!output.content)throw new OpenAIError(`missing content at index ${event.content_index}`);let content=getContent(output.content,event.content_index);if(content.type!=="reasoning_text")throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);content.text=event.text}return!0}case"response.reasoning_summary_part.added":{let output=getOutput(snapshot,event.output_index);if(output.type==="reasoning")validateArrayAppend(output.summary,event.summary_index,"content"),output.summary.push(structuredClone(event.part));return!0}case"response.reasoning_summary_part.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="reasoning")getContent(output.summary,event.summary_index),output.summary[event.summary_index]=structuredClone(event.part);return!0}case"response.reasoning_summary_text.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="reasoning"){let part=getContent(output.summary,event.summary_index);part.text+=event.delta}return!0}case"response.reasoning_summary_text.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="reasoning"){let part=getContent(output.summary,event.summary_index);part.text=event.text}return!0}default:return!1}}function accumulateCodeInterpreterEvent(event,snapshot){switch(event.type){case"response.code_interpreter_call_code.delta":{let output=getOutput(snapshot,event.output_index);if(output.type==="code_interpreter_call")output.code=(output.code??"")+event.delta;return!0}case"response.code_interpreter_call_code.done":{let output=getOutput(snapshot,event.output_index);if(output.type==="code_interpreter_call")output.code=event.code;return!0}case"response.code_interpreter_call.in_progress":{let output=getOutput(snapshot,event.output_index);if(output.type==="code_interpreter_call")output.status="in_progress";return!0}case"response.code_interpreter_call.interpreting":{let output=getOutput(snapshot,event.output_index);if(output.type==="code_interpreter_call")output.status="interpreting";return!0}case"response.code_interpreter_call.completed":{let output=getOutput(snapshot,event.output_index);if(output.type==="code_interpreter_call")output.status="completed";return!0}default:return!1}}function accumulateSearchStatusEvent(event,snapshot){switch(event.type){case"response.file_search_call.in_progress":{let output=getOutput(snapshot,event.output_index);if(output.type==="file_search_call")output.status="in_progress";return!0}case"response.file_search_call.searching":{let output=getOutput(snapshot,event.output_index);if(output.type==="file_search_call")output.status="searching";return!0}case"response.file_search_call.completed":{let output=getOutput(snapshot,event.output_index);if(output.type==="file_search_call")output.status="completed";return!0}case"response.web_search_call.in_progress":{let output=getOutput(snapshot,event.output_index);if(output.type==="web_search_call")output.status="in_progress";return!0}case"response.web_search_call.searching":{let output=getOutput(snapshot,event.output_index);if(output.type==="web_search_call")output.status="searching";return!0}case"response.web_search_call.completed":{let output=getOutput(snapshot,event.output_index);if(output.type==="web_search_call")output.status="completed";return!0}default:return!1}}function accumulateImageAndMcpStatusEvent(event,snapshot){switch(event.type){case"response.image_generation_call.in_progress":{let output=getOutput(snapshot,event.output_index);if(output.type==="image_generation_call")output.status="in_progress";return!0}case"response.image_generation_call.generating":{let output=getOutput(snapshot,event.output_index);if(output.type==="image_generation_call")output.status="generating";return!0}case"response.image_generation_call.completed":{let output=getOutput(snapshot,event.output_index);if(output.type==="image_generation_call")output.status="completed";return!0}case"response.mcp_call.in_progress":{let output=getOutput(snapshot,event.output_index);if(output.type==="mcp_call")output.status="in_progress";return!0}case"response.mcp_call.completed":{let output=getOutput(snapshot,event.output_index);if(output.type==="mcp_call")output.status="completed";return!0}case"response.mcp_call.failed":{let output=getOutput(snapshot,event.output_index);if(output.type==="mcp_call")output.status="failed";return!0}default:return!1}}function isResponseLifecycleEvent(event){switch(event.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}function isIgnoredResponseEvent(event){switch(event.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.compaction.compacting":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":return!0;default:return!1}}function createResponseContext(){return createCanonicalResponseContext()}function accumulateResponseOutput(dispatchEvent,snapshot,context,rejectInvalidShellTargets){if(validateOutputItemIdentity(dispatchEvent,snapshot,rejectInvalidShellTargets),accumulateOutputItemEvent(dispatchEvent,snapshot,context))return!0;if(accumulateContentPartAddedEvent(dispatchEvent,snapshot,context))return!0;if(accumulateContentPartDoneEvent(dispatchEvent,snapshot,context))return!0;if(accumulateOutputTextEvent(dispatchEvent,snapshot,context))return!0;if(accumulateRefusalAndArgumentsEvent(dispatchEvent,snapshot))return!0;if(accumulateShellEvent(dispatchEvent,snapshot))return!0;if(accumulateReasoningEvent(dispatchEvent,snapshot))return!0;if(accumulateCodeInterpreterEvent(dispatchEvent,snapshot))return!0;if(accumulateSearchStatusEvent(dispatchEvent,snapshot))return!0;if(accumulateImageAndMcpStatusEvent(dispatchEvent,snapshot))return!0;if(isIgnoredResponseEvent(dispatchEvent))return!0;return!1}function accumulateResponseWithContext(event,snapshot,context,rejectInvalidShellTargets=!1,prepareSanitizedEvent){let dispatchEvent=sanitizeResponseEvent(event);if(prepareSanitizedEvent&&dispatchEvent.type!=="keepalive"){let prepared=prepareSanitizedEvent(dispatchEvent);if(prepared===null){if(!snapshot)throw new OpenAIError("Cannot ignore a response event before response.created.");return snapshot}dispatchEvent=prepared}if(!snapshot){if(dispatchEvent.type!=="response.created")throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${dispatchEvent.type}`);return cloneValidatedResponse(context,dispatchEvent.response)}if(accumulateResponseOutput(dispatchEvent,snapshot,context,rejectInvalidShellTargets))return snapshot;if(isResponseLifecycleEvent(dispatchEvent))return cloneValidatedResponse(context,dispatchEvent.response);return assertNever3(dispatchEvent)}var responseOutputIdentityIndexes,expectedOutputItemTypes,supportedResponseEventTypes,responseEventRoutingFields;var init_response_accumulator=__esm(()=>{init_error2();init_utils2();init_values();init_canonical_output_text();responseOutputIdentityIndexes=new WeakMap;expectedOutputItemTypes={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools","response.compaction.compacting":"compaction"};supportedResponseEventTypes=createSupportedResponseEventTypes(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);responseEventRoutingFields=["item_id","output_index","content_index","annotation_index","command_index","summary_index"]});async function cancelUnconsumedBody(body){try{await CancelReadableStream(body)}catch{}}function outputIdentity(item){return JSON.stringify([item.type,!hasRoutedOutputCallIdentity(item)&&hasOwn(item,"id")?item.id:null,hasOwn(item,"call_id")&&"call_id"in item?item.call_id:null])}function finalizeResponse(snapshot,params,format){return maybeParseResponse(snapshot,params,format)}var _ResponseStream_instances,_ResponseStream_params,_ResponseStream_currentResponseSnapshot,_ResponseStream_finalResponse,_ResponseStream_accumulatorContext,_ResponseStream_outputPositions,_ResponseStream_wireByIdentity,_ResponseStream_interimOrderDirty,_ResponseStream_completedOutput,_ResponseStream_unfinishedOutput,_ResponseStream_beginRequest,_ResponseStream_prepareEvent,_ResponseStream_prepareOutputEvent,_ResponseStream_outputAtWireIndex,_ResponseStream_assertComplete,_ResponseStream_recordOutput,_ResponseStream_reorderInterimOutput,_ResponseStream_updateInterimResponse,_ResponseStream_addEvent,_ResponseStream_endRequest,nativeEventFields,ResponseStream;var init_ResponseStream=__esm(()=>{init_tslib();init_api_promise();init_error2();init_EventStream();init_response_accumulator();init_canonical_output_text();init_values();init_ResponsesParser();init_streaming2();nativeEventFields={annotation:!0,annotation_index:!0,arguments:!0,background:!0,code:!0,command:!0,command_index:!0,content_index:!0,delta:!0,input:!0,item:!0,item_id:!0,logprobs:!0,message:!0,obfuscation:!0,output:!0,output_format:!0,output_index:!0,param:!0,part:!0,partial_image_b64:!0,partial_image_index:!0,quality:!0,refusal:!0,response:!0,sequence_number:!0,size:!0,status:!0,summary_index:!0,text:!0,type:!0};ResponseStream=class ResponseStream extends EventStream{constructor(params){super();_ResponseStream_instances.add(this),_ResponseStream_params.set(this,void 0),_ResponseStream_currentResponseSnapshot.set(this,void 0),_ResponseStream_finalResponse.set(this,void 0),_ResponseStream_accumulatorContext.set(this,createResponseContext()),_ResponseStream_outputPositions.set(this,new Map),_ResponseStream_wireByIdentity.set(this,new Map),_ResponseStream_interimOrderDirty.set(this,!1),_ResponseStream_completedOutput.set(this,new Map),_ResponseStream_unfinishedOutput.set(this,new Map),__classPrivateFieldSet(this,_ResponseStream_params,params,"f"),this.once("end",()=>{__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").clear()})}static createResponse(client,params,options){let{getTextFormat,requestOptions}=resolveResponseParseOptions(params,options),runner=new ResponseStream(Array.isArray(params.tools)?{tools:params.tools}:{});return runner._run(()=>runner._createOrRetrieveResponse(client,params,{...requestOptions,__metadata:{...requestOptions?.__metadata,helperMethod:"stream"}},getTextFormat)),runner}static fromReadableStream(stream){let runner=new ResponseStream(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}async _createOrRetrieveResponse(client,params,options,getTextFormat=resolveResponseParseOptions(params).getTextFormat){this._listenForAbort(options?.signal),__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_beginRequest).call(this);let stream,format,starting_after=null;if("response_id"in params)format=getTextFormat({body:params}),stream=await client.responses.retrieve(params.response_id,{stream:!0},{...options,signal:this.controller.signal,stream:!0}),starting_after=params.starting_after??null;else{let body={...params,stream:!0},prepared={body},responseBody=null,request=client.responses.create(body,{...options,signal:this.controller.signal});if(request instanceof APIPromise)request=request._thenUnwrap((events,props)=>(prepared=props.options,responseBody=props.response.body,events));stream=await request;try{format=getTextFormat(prepared)}catch(error){throw this.abort(),stream.controller.abort(),cancelUnconsumedBody(responseBody),error}}this._connected();for await(let event of stream)__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_addEvent).call(this,event,starting_after);if(stream.controller.signal?.aborted)throw this._userAbortError();return __classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_endRequest).call(this,format)}async _fromReadableStream(readableStream,options){this._listenForAbort(options?.signal),__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_beginRequest).call(this),this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller);for await(let event of stream)__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_addEvent).call(this,event,null);if(stream.controller.signal?.aborted)throw this._userAbortError();return __classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_endRequest).call(this)}[(_ResponseStream_params=new WeakMap,_ResponseStream_currentResponseSnapshot=new WeakMap,_ResponseStream_finalResponse=new WeakMap,_ResponseStream_accumulatorContext=new WeakMap,_ResponseStream_outputPositions=new WeakMap,_ResponseStream_wireByIdentity=new WeakMap,_ResponseStream_interimOrderDirty=new WeakMap,_ResponseStream_completedOutput=new WeakMap,_ResponseStream_unfinishedOutput=new WeakMap,_ResponseStream_instances=new WeakSet,_ResponseStream_beginRequest=function(){if(this.ended)return;__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,void 0,"f"),__classPrivateFieldSet(this,_ResponseStream_accumulatorContext,createResponseContext(),"f"),__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").clear(),__classPrivateFieldSet(this,_ResponseStream_interimOrderDirty,!1,"f"),__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").clear()},_ResponseStream_prepareEvent=function(event){if(event.type==="response.created"||event.type==="response.queued"||event.type==="response.in_progress"||event.type==="response.completed"||event.type==="response.failed"||event.type==="response.incomplete"){if(!hasOwn(event,"response"))throw new OpenAIError("Lifecycle events require their own response field.");let{response:wireResponse,...fields}=event;if(!isObj(wireResponse))throw new OpenAIError("Lifecycle events require a response object.");let response=structuredClone(wireResponse);if(__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f")&&response.id!==__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f").id)throw new OpenAIError("Lifecycle response identity changed.");if(!hasOwn(response,"output")||response.output==null){let output;if(event.type==="response.completed")output=[...__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f")].sort(([left],[right])=>left-right).map(([,item])=>structuredClone(item));else if(event.type==="response.failed"||event.type==="response.incomplete")output=[...__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").keys()].sort((left,right)=>left-right).map((index)=>structuredClone(__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_outputAtWireIndex).call(this,index)));else output=[];if(response={...response,output},event.type==="response.completed"||event.type==="response.failed"||event.type==="response.incomplete")addOutputText(response)}if(event.type==="response.completed")__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_assertComplete).call(this,response);return{...fields,type:event.type,sequence_number:event.sequence_number,response}}return __classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_prepareOutputEvent).call(this,event)},_ResponseStream_prepareOutputEvent=function(event){if(!__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f")||!hasOwn(event,"output_index")||!("output_index"in event))return event;let index=event.output_index;if(!Number.isSafeInteger(index)||index<0)throw new OpenAIError("Invalid response output index.");let position;if(event.type==="response.output_item.added"){if(event.item==null)return null;if(__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").has(index)||__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").has(index))throw new OpenAIError(`Duplicate response output index ${index}.`);position=__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f").output.length}else{let existing=__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").get(index);if(existing===void 0)throw new OpenAIError(`missing output at index ${index}`);position=existing}return new Proxy(event,{get(target,property){return property==="output_index"?position:Reflect.get(target,property,target)}})},_ResponseStream_outputAtWireIndex=function(wireIndex){let position=__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").get(wireIndex);return __classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").get(wireIndex)??(position===void 0?void 0:__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f")?.output[position])},_ResponseStream_assertComplete=function(response){if(__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").size===0&&__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").size===0)return;let finalItems=new Map((response.output??[]).map((item)=>[outputIdentity(item),item]));for(let item of __classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").values()){let replacement=finalItems.get(outputIdentity(item));if(replacement)validateResponseOutputItemIdentity(item,replacement,"response.completed")}for(let[wireIndex,identity]of __classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f")){let replacement=finalItems.get(identity);if(!replacement)throw new OpenAIError("Cannot complete response with unfinished output items.");let previous=__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_outputAtWireIndex).call(this,wireIndex);if(!previous)throw new OpenAIError("Cannot complete response with a missing output identity.");validateResponseOutputItemIdentity(previous,replacement,"response.completed")}},_ResponseStream_recordOutput=function(event,response,position){if(event.type==="response.completed"){__classPrivateFieldSet(this,_ResponseStream_interimOrderDirty,!1,"f");return}if(response!==__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f")){let previous=new Map;for(let[wireIndex,item]of __classPrivateFieldGet(this,_ResponseStream_completedOutput,"f"))previous.set(outputIdentity(item),wireIndex);for(let[wireIndex,identity]of __classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f"))previous.set(identity,wireIndex);let positions=new Map;__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").clear();for(let[newPosition,item]of response.output.entries()){let identity=outputIdentity(item),wireIndex=previous.get(identity)??newPosition,done=__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").get(wireIndex),unfinished=__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").get(wireIndex);if(positions.has(wireIndex)||done&&outputIdentity(done)!==identity||unfinished!==void 0&&unfinished!==identity)throw new OpenAIError("Response snapshot has conflicting output positions.");let previousItem=__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_outputAtWireIndex).call(this,wireIndex);if(previousItem)validateResponseOutputItemIdentity(previousItem,item,event.type);if(positions.set(wireIndex,newPosition),__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").set(identity,wireIndex),done)__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").set(wireIndex,structuredClone(item));else __classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").set(wireIndex,identity)}if(__classPrivateFieldSet(this,_ResponseStream_outputPositions,positions,"f"),__classPrivateFieldSet(this,_ResponseStream_interimOrderDirty,!["response.failed","response.incomplete"].includes(event.type),"f"),["response.created","response.queued","response.in_progress"].includes(event.type))__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_reorderInterimOutput).call(this,response);return}if(position===void 0)return;if(event.type==="response.output_item.added"&&event.item!=null){__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").set(event.output_index,position);let identity=outputIdentity(event.item);__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").set(event.output_index,identity),__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").set(identity,event.output_index),__classPrivateFieldSet(this,_ResponseStream_interimOrderDirty,!0,"f")}else if(event.type==="response.output_item.done"){let item=response.output[position];if(!item)throw new OpenAIError(`missing output at index ${event.output_index}`);__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").set(event.output_index,structuredClone(item)),__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").delete(event.output_index)}},_ResponseStream_reorderInterimOutput=function(response){if(!__classPrivateFieldGet(this,_ResponseStream_interimOrderDirty,"f"))return;let ordered=[...__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f")];if(ordered.sort(([left],[right])=>left-right),ordered.some(([,oldPosition],newPosition)=>oldPosition!==newPosition)){let derivedText=__classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f").canonicalSnapshot===response;if(response.output=ordered.map(([,oldPosition])=>response.output[oldPosition]),__classPrivateFieldSet(this,_ResponseStream_outputPositions,new Map(ordered.map(([wireIndex],newPosition)=>[wireIndex,newPosition])),"f"),__classPrivateFieldSet(this,_ResponseStream_accumulatorContext,createResponseContext(),"f"),derivedText)ensureCanonicalOutputText(__classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f"),response)}__classPrivateFieldSet(this,_ResponseStream_interimOrderDirty,!1,"f")},_ResponseStream_updateInterimResponse=function(incoming,snapshot){if(!Array.isArray(incoming.output))return!1;let suppliedText=hasOwn(incoming,"output_text")?incoming.output_text:void 0;if(incoming.output.length!==0){let validated=cloneValidatedResponse(createResponseContext(),incoming),replacements=[];for(let item of validated.output){let wire=__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").get(outputIdentity(item)),position=wire===void 0?void 0:__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").get(wire);if(wire===void 0||position===void 0)return!1;replacements.push({wire,position,item})}let updateText=suppliedText==null;if(!updateText)__classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f").canonicalSnapshot=void 0;for(let{wire,position,item}of replacements)if(replaceResponseOutputItem(__classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f"),snapshot,position,item,updateText),__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").has(wire))__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").set(wire,structuredClone(item));__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_reorderInterimOutput).call(this,snapshot)}let{output}=snapshot,outputText=suppliedText;if(outputText==null)ensureCanonicalOutputText(__classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f"),snapshot),outputText=snapshot.output_text;else __classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f").canonicalSnapshot=void 0;for(let key of Object.keys(snapshot))if(!hasOwn(incoming,key))Reflect.deleteProperty(snapshot,key);return Object.defineProperties(snapshot,Object.getOwnPropertyDescriptors({...incoming,output,output_text:outputText})),!0},_ResponseStream_addEvent=function(event,starting_after){if(this.ended)return;let maybeEmit=(name,event)=>{if(starting_after==null||event.sequence_number>starting_after)this._emit(name,event)};if(event.type==="error"){let error="error"in event&&typeof event.error==="object"&&event.error!==null?event.error:event;throw new APIError(void 0,error,event.message,void 0)}let dispatchEvent=event,outputPosition,response=accumulateResponseWithContext(event,__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f"),__classPrivateFieldGet(this,_ResponseStream_accumulatorContext,"f"),!0,(sanitizedEvent)=>{dispatchEvent=sanitizedEvent;let prepared=__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_prepareEvent).call(this,sanitizedEvent);if(prepared){if(hasOwn(prepared,"output_index")&&"output_index"in prepared)outputPosition=prepared.output_index;else if(hasOwn(prepared,"response")&&"response"in prepared){if(dispatchEvent=prepared,(prepared.type==="response.created"||prepared.type==="response.queued"||prepared.type==="response.in_progress")&&__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f")){if(__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_updateInterimResponse).call(this,prepared.response,__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f")))return null;let identities=new Set(prepared.response.output.map(outputIdentity)),retained=__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f").output.filter((item)=>!identities.has(outputIdentity(item)));if(retained.length)return{...prepared,response:{...prepared.response,output:[...prepared.response.output,...retained]}}}}}return prepared});if(__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_recordOutput).call(this,dispatchEvent,response,outputPosition),__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,response,"f"),dispatchEvent.type==="response.output_item.added"&&dispatchEvent.item==null)return;let wireSnapshot={...dispatchEvent};for(let key of Object.keys(nativeEventFields)){let descriptor=Object.getOwnPropertyDescriptor(dispatchEvent,key);if(descriptor&&!descriptor.enumerable)Object.defineProperty(wireSnapshot,key,{value:Reflect.get(dispatchEvent,key,dispatchEvent),enumerable:!0})}let eventSnapshot=structuredClone(wireSnapshot);switch(maybeEmit("event",eventSnapshot),wireSnapshot.type){case"response.output_text.delta":{let output=response.output[outputPosition??wireSnapshot.output_index];if(!output)throw new OpenAIError(`missing output at index ${wireSnapshot.output_index}`);if(output.type==="message"){let content=output.content[wireSnapshot.content_index];if(!content)throw new OpenAIError(`missing content at index ${wireSnapshot.content_index}`);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);maybeEmit("response.output_text.delta",{...structuredClone(wireSnapshot),snapshot:content.text})}break}case"response.function_call_arguments.delta":{let output=response.output[outputPosition??wireSnapshot.output_index];if(!output)throw new OpenAIError(`missing output at index ${wireSnapshot.output_index}`);if(output.type==="function_call")maybeEmit("response.function_call_arguments.delta",{...structuredClone(wireSnapshot),snapshot:output.arguments});break}default:{maybeEmit(wireSnapshot.type,eventSnapshot);break}}},_ResponseStream_endRequest=function(format){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");let snapshot=__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f");if(!snapshot)throw new OpenAIError("request ended without sending any events");__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_reorderInterimOutput).call(this,snapshot),__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,void 0,"f"),__classPrivateFieldSet(this,_ResponseStream_accumulatorContext,createResponseContext(),"f"),__classPrivateFieldGet(this,_ResponseStream_outputPositions,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_wireByIdentity,"f").clear(),__classPrivateFieldSet(this,_ResponseStream_interimOrderDirty,!1,"f"),__classPrivateFieldGet(this,_ResponseStream_completedOutput,"f").clear(),__classPrivateFieldGet(this,_ResponseStream_unfinishedOutput,"f").clear();let parsedResponse=finalizeResponse(snapshot,__classPrivateFieldGet(this,_ResponseStream_params,"f"),format);return __classPrivateFieldSet(this,_ResponseStream_finalResponse,parsedResponse,"f"),parsedResponse},Symbol.asyncIterator)](){return this._createIterator((push)=>{let onEvent=(event)=>push(event);return this.on("event",onEvent),()=>this.off("event",onEvent)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let response=__classPrivateFieldGet(this,_ResponseStream_finalResponse,"f");if(!response)throw new OpenAIError("stream ended without producing a Response");return response}}});function resolveResourceRequestOptions96(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization10(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery56(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys56.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys56.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys56,Responses2;var init_responses2=__esm(()=>{init_input_items2();init_input_items2();init_input_tokens2();init_input_tokens2();init_headers();init_path();init_ResponsesParser();init_ResponseStream();normalizeRequestOptionsForQueryKeys56=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Responses2=class Responses2 extends APIResource{constructor(){super(...arguments);this.inputItems=new InputItems2(this._client),this.inputTokens=new InputTokens2(this._client)}create(body,options){return this._client.post("/responses",resolveResourceRequestOptions96(options,(options)=>withBodyFinalization10({body,...options,stream:body.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))._thenUnwrap((rsp)=>{if("object"in rsp&&rsp.object==="response")addOutputText(rsp);return rsp})}retrieve(responseID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery56(query,["include","include_obfuscation","starting_after","stream"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.get(path`/responses/${responseID}`,resolveResourceRequestOptions96(options,(options)=>({query,...options,stream:query?.stream??!1,__security:{bearerAuth:!0}})))._thenUnwrap((rsp)=>{if("object"in rsp&&rsp.object==="response")addOutputText(rsp);return rsp})}delete(responseID,options){return this._client.delete(path`/responses/${responseID}`,resolveResourceRequestOptions96(options,(options)=>({...options,headers:buildHeaders([{Accept:"*/*"},options?.headers]),__security:{bearerAuth:!0}})))}cancel(responseID,options){return this._client.post(path`/responses/${responseID}/cancel`,resolveResourceRequestOptions96(options,(options)=>({...options,__security:{bearerAuth:!0}})))}compact(body,options){return this._client.post("/responses/compact",resolveResourceRequestOptions96(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}parse(body,options){let{getTextFormat,requestOptions}=resolveResponseParseOptions(body,options);return this._client.responses.create(body,requestOptions)._thenUnwrap((response,{options:prepared})=>parseResponse(response,body,getTextFormat(prepared)))}stream(body,options){return ResponseStream.createResponse(this._client,body,options)}};Responses2.InputItems=InputItems2;Responses2.InputTokens=InputTokens2});function resolveResourceRequestOptions97(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Alerts;var init_alerts=__esm(()=>{init_path();Alerts=class Alerts extends APIResource{retrieve(id,options){return this._client.get(path`/safety/alerts/${id}`,resolveResourceRequestOptions97(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions98(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Cases;var init_cases=__esm(()=>{init_path();Cases=class Cases extends APIResource{retrieve(id,options){return this._client.get(path`/safety/cases/${id}`,resolveResourceRequestOptions98(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});var Safety;var init_safety=__esm(()=>{init_alerts();init_alerts();init_cases();init_cases();Safety=class Safety extends APIResource{constructor(){super(...arguments);this.cases=new Cases(this._client),this.alerts=new Alerts(this._client)}};Safety.Cases=Cases;Safety.Alerts=Alerts});function resolveResourceRequestOptions99(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Content2;var init_content2=__esm(()=>{init_headers();init_path();Content2=class Content2 extends APIResource{retrieve(skillID,options){return this._client.get(path`/skills/${skillID}/content`,resolveResourceRequestOptions99(options,(options)=>({...options,headers:buildHeaders([{Accept:"application/binary"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}}});function resolveResourceRequestOptions100(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Content3;var init_content3=__esm(()=>{init_headers();init_path();Content3=class Content3 extends APIResource{retrieve(version,params,options){let{skill_id}=params;return this._client.get(path`/skills/${skill_id}/versions/${version}/content`,resolveResourceRequestOptions100(options,(options)=>({...options,headers:buildHeaders([{Accept:"application/binary"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}}});function resolveResourceRequestOptions101(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization11(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery57(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys57.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys57.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys57,Versions;var init_versions=__esm(()=>{init_content3();init_content3();init_pagination();init_uploads();init_path();normalizeRequestOptionsForQueryKeys57=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Versions=class Versions extends APIResource{constructor(){super(...arguments);this.content=new Content3(this._client)}create(skillID,body={},options){return this._client.post(path`/skills/${skillID}/versions`,maybeMultipartFormRequestOptions(withBodyFinalization11({body,...options,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client,{stripFilenames:!1}))}retrieve(version,params,options){let{skill_id}=params;return this._client.get(path`/skills/${skill_id}/versions/${version}`,resolveResourceRequestOptions101(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(skillID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery57(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/skills/${skillID}/versions`,CursorPage,resolveResourceRequestOptions101(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(version,params,options){let{skill_id}=params;return this._client.delete(path`/skills/${skill_id}/versions/${version}`,resolveResourceRequestOptions101(options,(options)=>({...options,__security:{bearerAuth:!0}})))}};Versions.Content=Content3});function resolveResourceRequestOptions102(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization12(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery58(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys58.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys58.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys58,Skills;var init_skills=__esm(()=>{init_content2();init_content2();init_versions();init_versions();init_pagination();init_uploads();init_path();normalizeRequestOptionsForQueryKeys58=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Skills=class Skills extends APIResource{constructor(){super(...arguments);this.content=new Content2(this._client),this.versions=new Versions(this._client)}create(body={},options){return this._client.post("/skills",maybeMultipartFormRequestOptions(withBodyFinalization12({body,...options,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client,{stripFilenames:!1}))}retrieve(skillID,options){return this._client.get(path`/skills/${skillID}`,resolveResourceRequestOptions102(options,(options)=>({...options,__security:{bearerAuth:!0}})))}update(skillID,body,options){return this._client.post(path`/skills/${skillID}`,resolveResourceRequestOptions102(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery58(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/skills",CursorPage,resolveResourceRequestOptions102(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(skillID,options){return this._client.delete(path`/skills/${skillID}`,resolveResourceRequestOptions102(options,(options)=>({...options,__security:{bearerAuth:!0}})))}};Skills.Content=Content2;Skills.Versions=Versions});function resolveResourceRequestOptions103(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Parts;var init_parts=__esm(()=>{init_uploads();init_path();Parts=class Parts extends APIResource{create(uploadID,body,options){return this._client.post(path`/uploads/${uploadID}/parts`,resolveResourceRequestOptions103(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}}});function resolveResourceRequestOptions104(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var Uploads;var init_uploads3=__esm(()=>{init_parts();init_parts();init_path();Uploads=class Uploads extends APIResource{constructor(){super(...arguments);this.parts=new Parts(this._client)}create(body,options){return this._client.post("/uploads",resolveResourceRequestOptions104(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}cancel(uploadID,options){return this._client.post(path`/uploads/${uploadID}/cancel`,resolveResourceRequestOptions104(options,(options)=>({...options,__security:{bearerAuth:!0}})))}complete(uploadID,body,options){return this._client.post(path`/uploads/${uploadID}/complete`,resolveResourceRequestOptions104(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}};Uploads.Parts=Parts});function pollVectorStoreFile(resource,vectorStoreID,fileID,options){return pollWithResponse((headers)=>resource.retrieve(fileID,{vector_store_id:vectorStoreID},{...options,headers}),["in_progress"],["failed","cancelled","completed"],options)}function pollVectorStoreFileBatch(resource,vectorStoreID,batchID,options){return pollWithResponse((headers)=>resource.retrieve(batchID,{vector_store_id:vectorStoreID},{...options,headers}),["in_progress"],["failed","cancelled","completed"],options)}var init_vector_store_polling=__esm(()=>{init_polling()});var allSettledWithThrow=async(promises)=>{let results=await Promise.allSettled(promises),rejected=results.filter((result)=>result.status==="rejected");if(rejected.length)throw Object.defineProperty(Error(`${rejected.length} promise(s) failed`),"rejections",{configurable:!0,value:rejected.map(({reason})=>reason),writable:!0});let values=[];for(let result of results)if(result.status==="fulfilled")values.push(result.value);return values};async function uploadAndPollVectorStoreFileBatch(resource,client,vectorStoreId,files,fileIds,options){if(files===null||files===void 0||files.length===0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let configuredConcurrency=options?.maxConcurrency??5,concurrencyLimit=Math.min(configuredConcurrency,files.length);if(concurrencyLimit===0)throw RangeError("maxConcurrency must be greater than 0");let fileIterator=files.values(),allFileIds=[...fileIds];async function processFiles(iterator){for(let item of iterator){let fileObj=await client.files.create({file:item,purpose:"assistants"},options);allFileIds.push(fileObj.id)}}let workers=[];workers.length=concurrencyLimit;for(let index=0;index<workers.length;index+=1)workers[index]=processFiles(fileIterator);return await allSettledWithThrow(workers),await resource.createAndPoll(vectorStoreId,{file_ids:allFileIds},options)}var init_vector_store_upload=()=>{};function resolveResourceRequestOptions105(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var FileBatches;var init_file_batches=__esm(()=>{init_pagination();init_headers();init_vector_store_polling();init_path();init_vector_store_upload();FileBatches=class FileBatches extends APIResource{create(vectorStoreID,body,options){return this._client.post(path`/vector_stores/${vectorStoreID}/file_batches`,resolveResourceRequestOptions105(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(batchID,params,options){let{vector_store_id}=params;return this._client.get(path`/vector_stores/${vector_store_id}/file_batches/${batchID}`,resolveResourceRequestOptions105(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}cancel(batchID,params,options){let{vector_store_id}=params;return this._client.post(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`,resolveResourceRequestOptions105(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(vectorStoreId,body,options){let created=await this.create(vectorStoreId,body,options);return await this.poll(vectorStoreId,created.id,options)}listFiles(batchID,params,options){let{vector_store_id,...query}=params;return this._client.getAPIList(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`,CursorPage,resolveResourceRequestOptions105(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}async poll(vectorStoreID,batchID,options){return await pollVectorStoreFileBatch(this,vectorStoreID,batchID,options)}async uploadAndPoll(vectorStoreId,{files,fileIds=[]},options){return await uploadAndPollVectorStoreFileBatch(this,this._client,vectorStoreId,files,fileIds,options)}}});function resolveResourceRequestOptions106(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery59(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys59.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys59.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys59,Files4;var init_files5=__esm(()=>{init_pagination();init_headers();init_vector_store_polling();init_path();normalizeRequestOptionsForQueryKeys59=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Files4=class Files4 extends APIResource{create(vectorStoreID,body,options){return this._client.post(path`/vector_stores/${vectorStoreID}/files`,resolveResourceRequestOptions106(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(fileID,params,options){let{vector_store_id}=params;return this._client.get(path`/vector_stores/${vector_store_id}/files/${fileID}`,resolveResourceRequestOptions106(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}update(fileID,params,options){let{vector_store_id,...body}=params;return this._client.post(path`/vector_stores/${vector_store_id}/files/${fileID}`,resolveResourceRequestOptions106(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}list(vectorStoreID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery59(query,["after","before","filter","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList(path`/vector_stores/${vectorStoreID}/files`,CursorPage,resolveResourceRequestOptions106(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}delete(fileID,params,options){let{vector_store_id}=params;return this._client.delete(path`/vector_stores/${vector_store_id}/files/${fileID}`,resolveResourceRequestOptions106(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(vectorStoreId,body,options){let created=await this.create(vectorStoreId,body,options);return await this.poll(vectorStoreId,created.id,options)}async poll(vectorStoreID,fileID,options){return await pollVectorStoreFile(this,vectorStoreID,fileID,options)}async upload(vectorStoreId,file,options){let fileInfo=await this._client.files.create({file,purpose:"assistants"},options);return this.create(vectorStoreId,{file_id:fileInfo.id},options)}async uploadAndPoll(vectorStoreId,file,options){let fileInfo=await this.upload(vectorStoreId,file,options);return await this.poll(vectorStoreId,fileInfo.id,options)}content(fileID,params,options){let{vector_store_id}=params;return this._client.getAPIList(path`/vector_stores/${vector_store_id}/files/${fileID}/content`,Page,resolveResourceRequestOptions106(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}}});function resolveResourceRequestOptions107(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery60(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys60.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys60.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys60,VectorStores;var init_vector_stores=__esm(()=>{init_file_batches();init_file_batches();init_files5();init_files5();init_pagination();init_headers();init_path();normalizeRequestOptionsForQueryKeys60=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);VectorStores=class VectorStores extends APIResource{constructor(){super(...arguments);this.files=new Files4(this._client),this.fileBatches=new FileBatches(this._client)}create(body,options){return this._client.post("/vector_stores",resolveResourceRequestOptions107(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}retrieve(vectorStoreID,options){return this._client.get(path`/vector_stores/${vectorStoreID}`,resolveResourceRequestOptions107(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}update(vectorStoreID,body,options){return this._client.post(path`/vector_stores/${vectorStoreID}`,resolveResourceRequestOptions107(options,(options)=>({body,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery60(query,["after","before","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/vector_stores",CursorPage,resolveResourceRequestOptions107(options,(options)=>({query,...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}delete(vectorStoreID,options){return this._client.delete(path`/vector_stores/${vectorStoreID}`,resolveResourceRequestOptions107(options,(options)=>({...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}search(vectorStoreID,body,options){return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/search`,Page,resolveResourceRequestOptions107(options,(options)=>({body,method:"post",...options,headers:buildHeaders([{"OpenAI-Beta":"assistants=v2"},options?.headers]),__security:{bearerAuth:!0}})))}};VectorStores.Files=Files4;VectorStores.FileBatches=FileBatches});function resolveResourceRequestOptions108(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function withBodyFinalization13(options,finalization){return{...options,__metadata:{...options.__metadata,...finalization}}}function normalizeRequestOptionsForQuery61(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys61.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys61.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var normalizeRequestOptionsForQueryKeys61,Videos;var init_videos=__esm(()=>{init_pagination();init_headers();init_uploads();init_path();normalizeRequestOptionsForQueryKeys61=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Videos=class Videos extends APIResource{create(body,options){return this._client.post("/videos",resolveResourceRequestOptions108(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}retrieve(videoID,options){return this._client.get(path`/videos/${videoID}`,resolveResourceRequestOptions108(options,(options)=>({...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery61(query,["after","limit","order"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/videos",ConversationCursorPage,resolveResourceRequestOptions108(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(videoID,options){return this._client.delete(path`/videos/${videoID}`,resolveResourceRequestOptions108(options,(options)=>({...options,__security:{bearerAuth:!0}})))}createCharacter(body,options){return this._client.post("/videos/characters",resolveResourceRequestOptions108(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}downloadContent(videoID,query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery61(query,["variant"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.get(path`/videos/${videoID}/content`,resolveResourceRequestOptions108(options,(options)=>({query,...options,headers:buildHeaders([{Accept:"application/binary"},options?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}edit(body,options){return this._client.post("/videos/edits",resolveResourceRequestOptions108(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}extend(body,options){return this._client.post("/videos/extensions",resolveResourceRequestOptions108(options,(options)=>multipartFormRequestOptions({body,...options,__security:{bearerAuth:!0}},this._client)))}getCharacter(characterID,options){return this._client.get(path`/videos/characters/${characterID}`,resolveResourceRequestOptions108(options,(options)=>({...options,__security:{bearerAuth:!0}})))}remix(videoID,body,options){return this._client.post(path`/videos/${videoID}/remix`,resolveResourceRequestOptions108(options,(options)=>maybeMultipartFormRequestOptions(withBodyFinalization13({body,...options,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client)))}}});function resolveResourceRequestOptions109(options,buildOptions){return Promise.resolve(options).then(buildOptions)}var EventTypes;var init_event_types=__esm(()=>{EventTypes=class EventTypes extends APIResource{list(options){return this._client.get("/webhook_event_types",resolveResourceRequestOptions109(options,(options)=>({...options,__security:{bearerAuth:!0}})))}}});function webhookSignatureRequiresSigning(signatureHeader){return signatureHeader.split(" ",MAX_DIRECT_WEBHOOK_VERIFICATIONS+1).length>MAX_DIRECT_WEBHOOK_VERIFICATIONS}function*signatureCandidates(signatureHeader){let start=0;while(start<=signatureHeader.length){let separator=signatureHeader.indexOf(" ",start),candidate=signatureHeader.slice(start,separator===-1?void 0:separator);if(yield candidate.startsWith("v1,")?candidate.slice(3):candidate,separator===-1)break;start=separator+1}}function decodeSignature(signature){try{let signatureBytes=fromBase64(signature);return signatureBytes.byteLength===SHA256_SIGNATURE_LENGTH?signatureBytes:void 0}catch{return}}function firstValidLengthSignature(signatureHeader){for(let signature of signatureCandidates(signatureHeader)){let signatureBytes=decodeSignature(signature);if(signatureBytes)return signatureBytes}return}function selectMatchingSignature(signatureHeader,expectedSignature,firstSignature){let matchingSignature=firstSignature;for(let signature of signatureCandidates(signatureHeader)){let signatureBytes=decodeSignature(signature);if(!signatureBytes)continue;let difference=0;for(let[index,byte]of signatureBytes.entries())difference|=byte^(expectedSignature[index]??0);if(difference===0)matchingSignature=signatureBytes}return matchingSignature}async function verifyWebhookSignature(payload,signatureHeader,timestamp,webhookId,secret,tolerance){let timestampSeconds=Number.parseInt(timestamp,10);if(Number.isNaN(timestampSeconds))throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");let nowSeconds=Math.floor(Date.now()/1000);if(nowSeconds-timestampSeconds>tolerance)throw new InvalidWebhookSignatureError("Webhook timestamp is too old");if(timestampSeconds>nowSeconds+tolerance)throw new InvalidWebhookSignatureError("Webhook timestamp is too new");let useBoundedVerification=webhookSignatureRequiresSigning(signatureHeader),firstSignature=useBoundedVerification?firstValidLengthSignature(signatureHeader):void 0;if(useBoundedVerification&&!firstSignature)throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");let decodedSecret=Uint8Array.from(secret.startsWith("whsec_")?fromBase64(secret.slice(6)):encodeUTF8(secret)),signedPayload=webhookId?`${webhookId}.${timestamp}.${payload}`:`${timestamp}.${payload}`,signedPayloadBytes=Uint8Array.from(encodeUTF8(signedPayload)),key=await crypto.subtle.importKey("raw",decodedSecret,{name:"HMAC",hash:"SHA-256"},!1,useBoundedVerification?["sign","verify"]:["verify"]);if(useBoundedVerification&&firstSignature){let expectedSignature=new Uint8Array(await crypto.subtle.sign("HMAC",key,signedPayloadBytes)),signatureToVerify=selectMatchingSignature(signatureHeader,expectedSignature,firstSignature);try{if(await crypto.subtle.verify("HMAC",key,Uint8Array.from(signatureToVerify),signedPayloadBytes))return}catch{}throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature")}for(let signature of signatureCandidates(signatureHeader))try{let signatureBytes=Uint8Array.from(fromBase64(signature));if(await crypto.subtle.verify("HMAC",key,signatureBytes,signedPayloadBytes))return}catch{}throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature")}var MAX_DIRECT_WEBHOOK_VERIFICATIONS=32,SHA256_SIGNATURE_LENGTH=32;var init_webhook_signature=__esm(()=>{init_error2();init_base64()});function resolveResourceRequestOptions110(options,buildOptions){return Promise.resolve(options).then(buildOptions)}function normalizeRequestOptionsForQuery62(value,queryKeys,options){if(typeof value!=="object"||value===null)return;let entries=Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([,descriptor])=>descriptor.enumerable&&(!("value"in descriptor)||descriptor.value!==void 0)),keys=entries.map(([key])=>key);if(!keys.some((key)=>normalizeRequestOptionsForQueryKeys62.has(key)&&!queryKeys.includes(key)))return;if(options!==void 0||keys.some((key)=>!normalizeRequestOptionsForQueryKeys62.has(key)||queryKeys.includes(key)))throw TypeError("Query parameters and request options must be passed as separate arguments.");if(keys.some((key)=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(key)))throw TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(entries.map(([key,descriptor])=>{if("value"in descriptor)return[key,descriptor.value];return[key,descriptor.get?Reflect.apply(descriptor.get,value,[]):void 0]}))}var _Webhooks_instances,_Webhooks_validateSecret,_Webhooks_getRequiredHeader,normalizeRequestOptionsForQueryKeys62,Webhooks;var init_webhooks=__esm(()=>{init_tslib();init_event_types();init_event_types();init_pagination();init_path();init_headers();init_webhook_signature();normalizeRequestOptionsForQueryKeys62=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__security","__synthesizeEventData"]);Webhooks=class Webhooks extends APIResource{constructor(){super(...arguments);_Webhooks_instances.add(this),this.eventTypes=new EventTypes(this._client)}create(body,options){return this._client.post("/webhook_endpoints",resolveResourceRequestOptions110(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}retrieve(webhookEndpointID,options){return this._client.get(path`/webhook_endpoints/${webhookEndpointID}`,resolveResourceRequestOptions110(options,(options)=>({...options,__security:{bearerAuth:!0}})))}update(webhookEndpointID,body={},options){return this._client.post(path`/webhook_endpoints/${webhookEndpointID}`,resolveResourceRequestOptions110(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}list(query={},options){let normalizeRequestOptionsForQueryOptions=normalizeRequestOptionsForQuery62(query,["after","limit"],options);if(normalizeRequestOptionsForQueryOptions!==void 0)options=normalizeRequestOptionsForQueryOptions,query={};return query=query,this._client.getAPIList("/webhook_endpoints",CursorPage,resolveResourceRequestOptions110(options,(options)=>({query,...options,__security:{bearerAuth:!0}})))}delete(webhookEndpointID,options){return this._client.delete(path`/webhook_endpoints/${webhookEndpointID}`,resolveResourceRequestOptions110(options,(options)=>({...options,__security:{bearerAuth:!0}})))}rotateSecret(webhookEndpointID,body={},options){return this._client.post(path`/webhook_endpoints/${webhookEndpointID}/rotate_secret`,resolveResourceRequestOptions110(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}test(webhookEndpointID,body,options){return this._client.post(path`/webhook_endpoints/${webhookEndpointID}/test`,resolveResourceRequestOptions110(options,(options)=>({body,...options,__security:{bearerAuth:!0}})))}async unwrap(payload,headers,secret=this._client.webhookSecret,tolerance=300){return await this.verifySignature(payload,headers,secret,tolerance),JSON.parse(payload)}async verifySignature(payload,headers,secret=this._client.webhookSecret,tolerance=300){if(typeof crypto>"u"||typeof crypto.subtle?.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");__classPrivateFieldGet(this,_Webhooks_instances,"m",_Webhooks_validateSecret).call(this,secret);let headersObj=buildHeaders([headers]).values,signatureHeader=__classPrivateFieldGet(this,_Webhooks_instances,"m",_Webhooks_getRequiredHeader).call(this,headersObj,"webhook-signature"),timestamp=__classPrivateFieldGet(this,_Webhooks_instances,"m",_Webhooks_getRequiredHeader).call(this,headersObj,"webhook-timestamp"),webhookId=__classPrivateFieldGet(this,_Webhooks_instances,"m",_Webhooks_getRequiredHeader).call(this,headersObj,"webhook-id");if(webhookSignatureRequiresSigning(signatureHeader)&&typeof crypto.subtle.sign!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");return await verifyWebhookSignature(payload,signatureHeader,timestamp,webhookId,secret,tolerance)}};_Webhooks_instances=new WeakSet,_Webhooks_validateSecret=function(secret){if(typeof secret!=="string"||secret.length===0)throw 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")},_Webhooks_getRequiredHeader=function(headers,name){if(!headers)throw Error("Headers are required");let value=headers.get(name);if(value===null||value===void 0)throw Error(`Missing required header: ${name}`);return value};Webhooks.EventTypes=EventTypes});var init_resources=__esm(()=>{init_admin();init_audio();init_batches();init_beta();init_completions3();init_containers();init_content_provenance_checks();init_conversations();init_decisions();init_embeddings2();init_evals();init_files4();init_fine_tuning();init_graders2();init_images();init_live();init_models();init_moderations();init_realtime2();init_responses2();init_safety();init_skills();init_uploads3();init_vector_stores();init_videos();init_webhooks();init_chat2();init_shared()});function assertBedrockRequestOrigin(baseURL,requestURL){let expectedURL=new URL(baseURL),request=new URL(requestURL),expectedOrigin=expectedURL.origin,requestOrigin=request.origin;if(expectedURL.protocol!=="http:"&&expectedURL.protocol!=="https:"||request.protocol!=="http:"&&request.protocol!=="https:"||requestOrigin!==expectedOrigin)throw new OpenAIError(`Bedrock request origin \`${requestOrigin}\` does not match the configured base URL origin \`${expectedOrigin}\`.`)}function assertValidBedrockBearerCredential(credential){if(/^[\t ]|[\t ]$/.test(credential))throw TypeError("Bedrock bearer credential contains an invalid HTTP header value.");for(let character of credential){let value=character.codePointAt(0)??0;if(value<32&&value!==9||value===127||value>255)throw TypeError("Bedrock bearer credential contains an invalid HTTP header value.")}}var brand_privateBedrockClient;var init_bedrock=__esm(()=>{init_error2();init_utils2();brand_privateBedrockClient=Symbol.for("openai.privateBedrockClient")});function mergeWebSocketAuthHeaders(options,authHeaders,removedHeaders){let headers=new Map(Object.entries(authHeaders).map(([name,value])=>[name.toLowerCase(),value]));for(let name of removedHeaders)headers.delete(name);for(let[name,value]of Object.entries(options.headers??{}))headers.set(name,value);return{...options,headers:Object.fromEntries(headers)}}var webSocketHeaderRemovals;var init_ws=__esm(()=>{init_error();webSocketHeaderRemovals=new WeakMap});function getDeferredRealtimeAPIKeyCache(client){let deferred=client[realtimeCacheContext]?.getStore();return deferred?.client===client?deferred:void 0}function validateCapturedAPIKey(client,credential){if(credential!==null&&brand_privateBedrockClient in client)assertValidBedrockBearerCredential(credential);return credential}async function resolveRealtimeAPIKey(client,deferCache=!1){let apiKey,current={client,commit:()=>apiKey===void 0?client.apiKey:apiKey},capture=(resolved)=>{apiKey=resolved},invoke=()=>client._callApiKey(capture),context=client[realtimeCacheContext]??cacheContext;if(deferCache&&context&&!client[realtimeCacheContext])Object.defineProperty(client,realtimeCacheContext,{value:context});let isProvider=await(context?context.run(deferCache?current:void 0,invoke):invoke());return{apiKey:apiKey===void 0?client.apiKey:apiKey,isProvider,commit:()=>{let hookKey=current.providerKey!==void 0&&apiKey!==void 0&&apiKey!==current.providerKey?validateCapturedAPIKey(client,apiKey):void 0,cached=current.commit();return hookKey===void 0?validateCapturedAPIKey(client,cached):hookKey}}}var realtimeCacheContext,cacheContext;var init_realtime_credentials=__esm(()=>{init_bedrock();init_ws();realtimeCacheContext=Symbol.for("openai.realtimeAPIKeyCacheContext")});function isProviderTimeoutError(error){return error instanceof APIConnectionTimeoutError||error instanceof Error&&providerTimeoutKey in error&&error[providerTimeoutKey]===!0}function configureProvider(provider){let definition=providerDefinitions.get(provider);if(!definition)throw Error("Invalid provider. Providers must be created with createProvider().");return definition.configure()}var providerTimeoutKey,providerDefinitionsKey,providerGlobal,existingProviderDefinitions,providerDefinitions;var init_provider=__esm(()=>{init_error();providerTimeoutKey=Symbol.for("openai.node.providerTimeout.v1");providerDefinitionsKey=Symbol.for("openai.node.providerDefinitions.v1"),providerGlobal=globalThis,existingProviderDefinitions=providerGlobal[providerDefinitionsKey],providerDefinitions=existingProviderDefinitions??new WeakMap;if(!existingProviderDefinitions)Object.defineProperty(providerGlobal,providerDefinitionsKey,{value:providerDefinitions})});function isRunningInBrowserOrBrowserWorker(){if(isRunningInBrowser())return!0;let scope=globalThis;return typeof scope.WorkerGlobalScope==="function"&&scope instanceof scope.WorkerGlobalScope&&typeof scope.WorkerNavigator==="function"&&scope.navigator instanceof scope.WorkerNavigator&&typeof scope.navigator?.userAgent==="string"&&scope.navigator.userAgent!=="Cloudflare-Workers"&&scope.process?.versions?.node===void 0&&scope.Deno===void 0&&scope.Bun===void 0&&scope.EdgeRuntime===void 0&&scope.WebSocketPair===void 0}class OpenAI{constructor(clientOptions={}){_OpenAI_instances.add(this),_OpenAI_encoder.set(this,void 0),_OpenAI_x509Authentication.set(this,void 0),_OpenAI_x509Credential.set(this,void 0),_OpenAI_x509Fetch.set(this,void 0),_OpenAI_explicitDataResidency.set(this,!1),_OpenAI_responseAttempts.set(this,new WeakMap),this._apiKeyInvocation=0,this._lastCachedAPIKeyInvocation=0,this.decisions=new Decisions(this),this.completions=new Completions2(this),this.chat=new Chat(this),this.embeddings=new Embeddings(this),this.files=new Files3(this),this.images=new Images(this),this.contentProvenanceChecks=new ContentProvenanceChecks(this),this.audio=new Audio(this),this.moderations=new Moderations(this),this.models=new Models(this),this.fineTuning=new FineTuning(this),this.graders=new Graders2(this),this.vectorStores=new VectorStores(this),this.safety=new Safety(this),this.webhooks=new Webhooks(this),this.beta=new Beta(this),this.batches=new Batches(this),this.uploads=new Uploads(this),this.admin=new Admin(this),this.responses=new Responses2(this),this.live=new Live(this),this.realtime=new Realtime2(this),this.conversations=new Conversations(this),this.evals=new Evals(this),this.containers=new Containers(this),this.skills=new Skills(this),this.videos=new Videos(this);let{credential,options:normalizedOptions}=normalizeX509CredentialOptions(clientOptions);clientOptions=normalizedOptions;let residencyBaseURL=resolveDataResidency(clientOptions),provider=clientOptions.provider,{baseURL=provider?null:readEnv("OPENAI_BASE_URL"),dataResidency:_dataResidency,[inheritedDataResidencySelection]:inheritedResidencySelection=!1,apiKey=provider?null:readEnv("OPENAI_API_KEY")??null,adminAPIKey=provider?null:readEnv("OPENAI_ADMIN_KEY")??null,organization=provider?null:readEnv("OPENAI_ORG_ID")??null,project=provider?null:readEnv("OPENAI_PROJECT_ID")??null,webhookSecret=readEnv("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity,x509Transport,credential:_credential,...opts}=clientOptions;if(provider){let conflictingOptions=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter((key)=>(key==="workloadIdentity"?workloadIdentity:clientOptions[key])!=null);if(conflictingOptions.length)throw new OpenAIError(`The \`provider\` option cannot be used with ${conflictingOptions.map((key)=>`\`${key}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let identity=isX509WorkloadIdentity(workloadIdentity)?{x509:workloadIdentity,legacy:void 0}:{x509:void 0,legacy:workloadIdentity},x509Identity=identity.x509,usesX509Identity=x509Identity!==void 0,providerRuntime=provider?configureProvider(provider):void 0,options={apiKey,adminAPIKey,organization,project,webhookSecret,workloadIdentity,x509Transport,provider,...opts,baseURL:providerRuntime?.baseURL??residencyBaseURL??(baseURL||(usesX509Identity?X509_API_BASE_URL:"https://api.openai.com/v1"))};if(x509Transport&&!usesX509Identity)throw new OpenAIError("An X.509 transport requires an X.509 workload identity.");if(usesX509Identity){if(residencyBaseURL!==void 0||inheritedResidencySelection)throw new OpenAIError("X.509 workload identity does not support data residency selection.");if(clientOptions.fetch!==void 0)throw new OpenAIError("X.509 workload identity does not support a custom fetch implementation.");if(assertX509APIOrigin(options.baseURL),assertX509RequestOptions(options.fetchOptions),this.fetchWithAuth!==_a3.prototype.fetchWithAuth||this.fetchWithTimeout!==_a3.prototype.fetchWithTimeout)throw new OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(apiKey&&workloadIdentity)throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!providerRuntime&&!apiKey&&!adminAPIKey&&!workloadIdentity)throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!options.dangerouslyAllowBrowser&&isRunningInBrowserOrBrowserWorker())throw new OpenAIError(`It looks like you're running in a browser-like environment.
12
22
 
13
23
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
14
24
  If you understand the risks and have appropriate mitigations in place,
@@ -17,8 +27,9 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
17
27
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
18
28
 
19
29
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
20
- `);super({baseURL:options.baseURL,timeout:options.timeout??600000,httpAgent:options.httpAgent,maxRetries:options.maxRetries,fetch:options.fetch});this.completions=new Completions3(this),this.chat=new Chat(this),this.embeddings=new Embeddings(this),this.files=new Files2(this),this.images=new Images(this),this.audio=new Audio(this),this.moderations=new Moderations(this),this.models=new Models(this),this.fineTuning=new FineTuning(this),this.graders=new Graders2(this),this.vectorStores=new VectorStores(this),this.beta=new Beta(this),this.batches=new Batches(this),this.uploads=new Uploads(this),this.responses=new Responses(this),this.evals=new Evals(this),this.containers=new Containers(this),this._options=options,this.apiKey=apiKey,this.organization=organization,this.project=project}defaultQuery(){return this._options.defaultQuery}defaultHeaders(opts){return{...super.defaultHeaders(opts),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(opts){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(query){return stringify(query,{arrayFormat:"brackets"})}};_a=OpenAI;OpenAI.OpenAI=_a;OpenAI.DEFAULT_TIMEOUT=600000;OpenAI.OpenAIError=OpenAIError;OpenAI.APIError=APIError;OpenAI.APIConnectionError=APIConnectionError;OpenAI.APIConnectionTimeoutError=APIConnectionTimeoutError;OpenAI.APIUserAbortError=APIUserAbortError;OpenAI.NotFoundError=NotFoundError;OpenAI.ConflictError=ConflictError;OpenAI.RateLimitError=RateLimitError;OpenAI.BadRequestError=BadRequestError;OpenAI.AuthenticationError=AuthenticationError;OpenAI.InternalServerError=InternalServerError;OpenAI.PermissionDeniedError=PermissionDeniedError;OpenAI.UnprocessableEntityError=UnprocessableEntityError;OpenAI.toFile=toFile;OpenAI.fileFromPath=fileFromPath;OpenAI.Completions=Completions3;OpenAI.Chat=Chat;OpenAI.ChatCompletionsPage=ChatCompletionsPage;OpenAI.Embeddings=Embeddings;OpenAI.Files=Files2;OpenAI.FileObjectsPage=FileObjectsPage;OpenAI.Images=Images;OpenAI.Audio=Audio;OpenAI.Moderations=Moderations;OpenAI.Models=Models;OpenAI.ModelsPage=ModelsPage;OpenAI.FineTuning=FineTuning;OpenAI.Graders=Graders2;OpenAI.VectorStores=VectorStores;OpenAI.VectorStoresPage=VectorStoresPage;OpenAI.VectorStoreSearchResponsesPage=VectorStoreSearchResponsesPage;OpenAI.Beta=Beta;OpenAI.Batches=Batches;OpenAI.BatchesPage=BatchesPage;OpenAI.Uploads=Uploads;OpenAI.Responses=Responses;OpenAI.Evals=Evals;OpenAI.EvalListResponsesPage=EvalListResponsesPage;OpenAI.Containers=Containers;OpenAI.ContainerListResponsesPage=ContainerListResponsesPage;AzureOpenAI=class AzureOpenAI extends OpenAI{constructor({baseURL=readEnv("OPENAI_BASE_URL"),apiKey=readEnv("AZURE_OPENAI_API_KEY"),apiVersion=readEnv("OPENAI_API_VERSION"),endpoint,deployment,azureADTokenProvider,dangerouslyAllowBrowser,...opts}={}){if(!apiVersion)throw new OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof azureADTokenProvider==="function")dangerouslyAllowBrowser=!0;if(!azureADTokenProvider&&!apiKey)throw new OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(azureADTokenProvider&&apiKey)throw new OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(apiKey??(apiKey=API_KEY_SENTINEL),opts.defaultQuery={...opts.defaultQuery,"api-version":apiVersion},!baseURL){if(!endpoint)endpoint=process.env.AZURE_OPENAI_ENDPOINT;if(!endpoint)throw new OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");baseURL=`${endpoint}/openai`}else if(endpoint)throw new OpenAIError("baseURL and endpoint are mutually exclusive");super({apiKey,baseURL,...opts,...dangerouslyAllowBrowser!==void 0?{dangerouslyAllowBrowser}:{}});this.apiVersion="",this._azureADTokenProvider=azureADTokenProvider,this.apiVersion=apiVersion,this.deploymentName=deployment}buildRequest(options,props={}){if(_deployments_endpoints.has(options.path)&&options.method==="post"&&options.body!==void 0){if(!isObj(options.body))throw Error("Expected request body to be an object");let model=this.deploymentName||options.body.model||options.__metadata?.model;if(model!==void 0&&!this.baseURL.includes("/deployments"))options.path=`/deployments/${model}${options.path}`}return super.buildRequest(options,props)}async _getAzureADToken(){if(typeof this._azureADTokenProvider==="function"){let token=await this._azureADTokenProvider();if(!token||typeof token!=="string")throw new OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);return token}return}authHeaders(opts){return{}}async prepareOptions(opts){if(opts.headers?.["api-key"])return super.prepareOptions(opts);let token=await this._getAzureADToken();if(opts.headers??(opts.headers={}),token)opts.headers.Authorization=`Bearer ${token}`;else if(this.apiKey!==API_KEY_SENTINEL)opts.headers["api-key"]=this.apiKey;else throw new OpenAIError("Unable to handle auth");return super.prepareOptions(opts)}};_deployments_endpoints=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/images/edits"]),openai_default=OpenAI});import{mkdirSync}from"fs";import{tmpdir}from"os";import{join}from"path";import{Elysia as Elysia2}from"elysia";import{Elysia}from"elysia";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
21
- `);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}},BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};var CONTEXT_PROVIDER_TYPE="context",REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function registerContextProvider(provider,hostServices){if(!provider||typeof provider.name!=="string"||provider.name.length===0)throw Error("ContextProvider.name is required");if(typeof provider.getContext!=="function")throw Error("ContextProvider.getContext must be a function");getRegistry().set(provider.name,provider),hostServices?.serviceRegistry?.registerProvider?.(CONTEXT_PROVIDER_TYPE,provider,provider.name)}function listContextProviders(){return Array.from(getRegistry().values())}function getContextProvider(name){return getRegistry().get(name)}var ProviderRegistry=class{constructor(hostServices){this.hostServices=hostServices}hostServices;registerContextProvider(provider){registerContextProvider(provider,this.hostServices)}listContextProviders(){return listContextProviders()}getContextProvider(name){return getContextProvider(name)}getServiceRegistry(){return this.hostServices?.serviceRegistry}registerProvider(type,name,provider){this.hostServices?.serviceRegistry?.registerProvider?.(type,provider,name)}getProvider(type,name){let reg=this.hostServices?.serviceRegistry;if(!reg)return;if(name===void 0)return reg.getProvider?.(type);if(reg.getProviderByName)return reg.getProviderByName(type,name);if(!reg.listProvidersForType)return;if(!(reg.listProvidersForType(type)??[]).some((entry)=>typeof entry==="string"?entry===name:entry.pluginName===name))return;return reg.getProvider?.(type)}listProviders(type){return(this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]).map((entry)=>typeof entry==="string"?entry:entry.pluginName)}withCliContribution(contribution){let contributors=this.hostServices?.cliContributors;if(!contributors)return;for(let section of contribution.statusSections??[])contributors.addStatusSection?.(section);for(let check of contribution.doctorChecks??[])contributors.addDoctorCheck?.(check)}};var PROVIDER_NAME="codex",CLI_COMMAND="codex";function platformExeName(base){return process.platform==="win32"?`${base}.exe`:base}function resolveCliBin(){let found=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(CLI_COMMAND,{PATH:process.env.PATH}):null;if(found)return found;return platformExeName(CLI_COMMAND)}var CLI_BIN=resolveCliBin(),DISPLAY_NAME="OpenAI Codex",DEFAULT_MODEL="gpt-4.1-mini",DEFAULT_MAX_TOKENS=16384,API_PREFIX=`/api/ai-${PROVIDER_NAME}`,SUPPORTED_MODES=["sdk","cli"],CLI_NPM_PACKAGE="@openai/codex",CODEX_MODELS=[{id:"codex-mini-latest",name:"Codex Mini",provider:PROVIDER_NAME,contextWindow:200000,maxOutputTokens:1e5,supportsVision:!1,supportsStreaming:!0,inputPricePerMToken:1.5,outputPricePerMToken:6},{id:"gpt-4.1",name:"GPT-4.1",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:2,outputPricePerMToken:8},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:0.4,outputPricePerMToken:1.6},{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:0.1,outputPricePerMToken:0.4},{id:"o4-mini",name:"o4-mini",provider:PROVIDER_NAME,contextWindow:200000,maxOutputTokens:1e5,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:1.1,outputPricePerMToken:4.4}];class CodexSdkAdapter{mode="sdk";client=null;resolveApiKey;constructor(resolveApiKey){this.resolveApiKey=resolveApiKey}async getClient(){if(this.client)return this.client;let apiKey=(await this.resolveApiKey())?.trim();if(!apiKey)throw Error("OPENAI_API_KEY is required for SDK mode. Set it in the AI provider credentials (stored in the agent config) or export it in the agent environment.");let OpenAI2;try{let mod=await Promise.resolve().then(() => (init_openai(),exports_openai));OpenAI2=mod.default??mod}catch{throw Error("Failed to load openai SDK. Install it with: bun add openai")}return this.client=new OpenAI2({apiKey}),this.client}async sendPrompt(prompt,config,_signal){let client=await this.getClient(),startTime=Date.now(),params={model:config.model||DEFAULT_MODEL,input:prompt};if(config.systemPrompt)params.instructions=config.systemPrompt;if(config.maxTokens)params.max_output_tokens=config.maxTokens;let response=await client.responses.create(params),durationMs=Date.now()-startTime;return{content:this.extractResponseText(response),model:response.model,inputTokens:response.usage.input_tokens,outputTokens:response.usage.output_tokens,durationMs,metadata:{provider:PROVIDER_NAME,mode:"sdk"}}}async streamPrompt(prompt,config,onChunk,_signal){let client=await this.getClient(),startTime=Date.now(),model=config.model||DEFAULT_MODEL,params={model,input:prompt,stream:!0};if(config.systemPrompt)params.instructions=config.systemPrompt;if(config.maxTokens)params.max_output_tokens=config.maxTokens;let stream=client.responses.create(params),collectedText=[],finalModel=model,inputTokens=0,outputTokens=0;for await(let event of stream)if(event.type==="response.output_text.delta"&&event.delta)collectedText.push(event.delta),onChunk({type:"text",content:event.delta});else if(event.type==="response.completed"){let completed=event;if(completed.response)finalModel=completed.response.model,inputTokens=completed.response.usage.input_tokens,outputTokens=completed.response.usage.output_tokens}let durationMs=Date.now()-startTime,content=collectedText.join("");if(inputTokens===0&&outputTokens===0)inputTokens=Math.ceil(prompt.length/4),outputTokens=Math.ceil(content.length/4);return onChunk({type:"done",content:""}),{content,model:finalModel,inputTokens,outputTokens,durationMs,metadata:{provider:PROVIDER_NAME,mode:"sdk"}}}async healthCheck(){try{return await this.getClient(),{ok:!0,message:`${DISPLAY_NAME} SDK ready (API key configured)`}}catch(err){return{ok:!1,message:err instanceof Error?err.message:"SDK initialization failed"}}}extractResponseText(response){let parts=[];for(let output of response.output)if(output.type==="message"&&output.content){for(let block of output.content)if(block.type==="output_text"&&block.text)parts.push(block.text)}return parts.join("")}}function permissionFlags(mode){switch(mode){case"plan":return["--sandbox","read-only"];case"fullAuto":return["--dangerously-bypass-approvals-and-sandbox"];case"acceptEdits":default:return["--sandbox","workspace-write"]}}class CodexCliAdapter{mode="cli";resolveApiKey;loggedInKey=null;constructor(resolveApiKey){this.resolveApiKey=resolveApiKey}codexHome(){let home=process.env.CODEX_HOME?.trim()||join(tmpdir(),"vibe-codex-home");try{mkdirSync(home,{recursive:!0})}catch{}return home}async ensureAuth(home){let apiKey=(await this.resolveApiKey())?.trim();if(!apiKey||apiKey===this.loggedInKey)return;let proc=Bun.spawn([CLI_BIN,"login","--with-api-key"],{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:{...process.env,CODEX_HOME:home},timeout:30000});proc.stdin.write(apiKey),await proc.stdin.end();let exitCode=await proc.exited;if(exitCode===0)this.loggedInKey=apiKey;else{let stderr=await new Response(proc.stderr).text();throw Error(`Codex CLI login failed (exit ${exitCode}): ${stderr.trim()}`)}}buildCliArgs(config,prompt){let args=["exec","--skip-git-repo-check","--color","never",...permissionFlags(config.permissionMode)];if(config.model)args.push("--model",config.model);return args.push(prompt),args}async spawnEnv(home){let env={...process.env,CODEX_HOME:home},apiKey=(await this.resolveApiKey())?.trim();if(apiKey)env.OPENAI_API_KEY=apiKey;return env}async sendPrompt(prompt,config){let startTime=Date.now(),args=this.buildCliArgs(config,prompt),home=this.codexHome();await this.ensureAuth(home);let proc=Bun.spawn([CLI_BIN,...args],{stdout:"pipe",stderr:"pipe",cwd:config.workingDirectory||process.cwd(),env:await this.spawnEnv(home),timeout:config.providerConfig?.timeoutMs||300000}),stdout=await new Response(proc.stdout).text(),stderr=await new Response(proc.stderr).text(),exitCode=await proc.exited,durationMs=Date.now()-startTime;if(exitCode!==0&&!stdout)throw Error(`${DISPLAY_NAME} CLI exited with code ${exitCode}: ${stderr}`);let content=stdout.trim()||stderr.trim(),inputTokens=Math.ceil(prompt.length/4),outputTokens=Math.ceil(content.length/4),model=config.model||DEFAULT_MODEL;return{content,model,inputTokens,outputTokens,durationMs,metadata:{exitCode,provider:PROVIDER_NAME,mode:"cli"}}}async streamPrompt(prompt,config,onChunk){let result=await this.sendPrompt(prompt,config);return onChunk({type:"text",content:result.content}),onChunk({type:"done",content:""}),result}async healthCheck(){try{let proc=Bun.spawnSync([CLI_BIN,"--version"],{timeout:5000,stdout:"pipe",stderr:"ignore"});if(proc.exitCode===0)return{ok:!0,message:`${DISPLAY_NAME} CLI ${proc.stdout.toString().trim()}`};return{ok:!1,message:`${DISPLAY_NAME} CLI not available (exit code ${proc.exitCode})`}}catch{return{ok:!1,message:`${DISPLAY_NAME} CLI not installed or not in PATH`}}}}class CodexProvider{name=PROVIDER_NAME;sessions=new Map;logIngester=null;hostServices=null;logger=null;activeMode=null;adapter=null;cachedApiKey;setHostServices(hs){this.hostServices=hs,this.logger=new BoundLogger(hs.logger,`${PROVIDER_NAME}-provider`);let registry2=new ProviderRegistry(hs);this.logIngester=registry2.getProvider("ai","log-ingester")??null,Promise.resolve(hs.getConfig?.("OPENAI_API_KEY")).then((apiKey)=>{let trimmed=apiKey?.trim();if(trimmed)this.cachedApiKey=trimmed}).catch(()=>{})}async resolveApiKey(){let envKey=process.env.OPENAI_API_KEY?.trim();if(envKey)return envKey;if(this.cachedApiKey)return this.cachedApiKey;if(this.hostServices?.getConfig)try{let apiKey=(await this.hostServices.getConfig("OPENAI_API_KEY"))?.trim();if(apiKey)return this.cachedApiKey=apiKey,apiKey}catch{return}return}getSupportedModes(){return[...SUPPORTED_MODES]}getDisplayName(){return DISPLAY_NAME}getPrereqApiPrefix(){return API_PREFIX}getMode(){if(this.activeMode)return this.activeMode;return this.detectMode()}setMode(mode){if(!SUPPORTED_MODES.includes(mode))throw Error(`${DISPLAY_NAME} does not support ${mode} mode`);this.activeMode=mode,this.adapter=null,this.log("info",`Mode explicitly set to: ${mode}`)}detectMode(){if(process.env.OPENAI_API_KEY?.trim()||this.cachedApiKey)return"sdk";try{if(Bun.which(CLI_COMMAND,{PATH:process.env.PATH}))return"cli"}catch{}return"sdk"}getAdapter(){if(this.adapter)return this.adapter;let mode=this.getMode();return this.adapter=mode==="sdk"?new CodexSdkAdapter(()=>this.resolveApiKey()):new CodexCliAdapter(()=>this.resolveApiKey()),this.activeMode=mode,this.log("info",`Adapter initialized in ${mode} mode`),this.adapter}async createSession(config){let id=config.providerConfig?.sessionId||crypto.randomUUID(),now=new Date().toISOString(),existing=this.sessions.get(id);if(existing)return existing.status="active",existing.updatedAt=now,this.toAISession(existing);let session={id,config,status:"active",stats:{inputTokens:0,outputTokens:0,requestCount:0,estimatedCostUsd:0},abortController:null,files:[],createdAt:now,updatedAt:now};return this.sessions.set(id,session),this.log("info",`Session created: ${id} (${config.name})`),this.toAISession(session)}async sendPrompt(sessionId,prompt,context){let session=this.getSession(sessionId);session.status="processing",session.updatedAt=new Date().toISOString();let abortController=new AbortController;session.abortController=abortController;let fullPrompt=this.buildFullPrompt(prompt,context,session.files);this.logIngester?.append({sessionId,type:"input",content:prompt});try{let result=await this.getAdapter().sendPrompt(fullPrompt,session.config,abortController.signal);return this.updateSessionStats(session,result.inputTokens,result.outputTokens),this.logIngester?.append({sessionId,type:"output",content:result.content,tokenCount:result.outputTokens,model:result.model,durationMs:result.durationMs}),{content:result.content,model:result.model,inputTokens:result.inputTokens,outputTokens:result.outputTokens,durationMs:result.durationMs,metadata:result.metadata}}catch(err){session.status="error",session.updatedAt=new Date().toISOString();let errorMsg=err instanceof Error?err.message:"Unknown error";throw this.logIngester?.append({sessionId,type:"error",content:errorMsg}),err}finally{session.abortController=null}}async streamPrompt(sessionId,prompt,context,onChunk){let session=this.getSession(sessionId);session.status="processing",session.updatedAt=new Date().toISOString();let abortController=new AbortController;session.abortController=abortController;let fullPrompt=this.buildFullPrompt(prompt,context,session.files);this.logIngester?.append({sessionId,type:"input",content:prompt});try{let adapter=this.getAdapter(),chunkHandler=onChunk??((_c)=>{}),result=await adapter.streamPrompt(fullPrompt,session.config,chunkHandler,abortController.signal);return this.updateSessionStats(session,result.inputTokens,result.outputTokens),this.logIngester?.append({sessionId,type:"output",content:result.content,tokenCount:result.outputTokens,model:result.model,durationMs:result.durationMs}),{content:result.content,model:result.model,inputTokens:result.inputTokens,outputTokens:result.outputTokens,durationMs:result.durationMs,metadata:result.metadata}}catch(err){session.status="error",session.updatedAt=new Date().toISOString();let errorMsg=err instanceof Error?err.message:"Unknown error";throw this.logIngester?.append({sessionId,type:"error",content:errorMsg}),err}finally{session.abortController=null}}async listModels(){return[...CODEX_MODELS]}async cancelRequest(sessionId){let session=this.sessions.get(sessionId);if(!session)throw Error(`Session ${sessionId} not found`);if(session.abortController)session.abortController.abort(),session.abortController=null,session.status="active",session.updatedAt=new Date().toISOString(),this.log("info",`Request cancelled for session: ${sessionId}`)}getCapabilities(){let mode=this.getMode();return{streaming:mode==="sdk",vision:mode==="sdk",fileAttachments:!0,toolUse:!1,mcpSupport:!1,voiceMode:!1,cancelSupport:mode==="sdk",modelListing:!0}}async attachFiles(sessionId,files){let session=this.getSession(sessionId);session.files.push(...files),session.updatedAt=new Date().toISOString(),this.log("debug",`Attached ${files.length} file(s) to session ${sessionId}`)}async getSessionLogs(_sessionId,_filter){return[]}async getUsageStats(sessionId){return this.sessions.get(sessionId)?.stats??{inputTokens:0,outputTokens:0,requestCount:0,estimatedCostUsd:0}}async configureSession(sessionId,config){let session=this.getSession(sessionId);Object.assign(session.config,config),session.updatedAt=new Date().toISOString()}async destroySession(sessionId){let session=this.sessions.get(sessionId);if(session){if(session.abortController)session.abortController.abort(),session.abortController=null;session.status="terminated",session.files=[],session.updatedAt=new Date().toISOString(),this.log("info",`Session terminated: ${sessionId}`)}}async listSessions(){return Array.from(this.sessions.values()).map((s)=>this.toAISession(s))}async getSessionStatus(sessionId){return this.sessions.get(sessionId)?.status??"terminated"}async healthCheck(){return this.getAdapter().healthCheck()}getCliLaunchSpec(){let env={},apiKey=process.env.OPENAI_API_KEY?.trim()||this.cachedApiKey;if(apiKey)env.OPENAI_API_KEY=apiKey;return{binary:CLI_COMMAND,env}}async sdkOneShot(opts){let adapter=new CodexSdkAdapter(()=>this.resolveApiKey()),config={name:"vibe-ai-sdk",agentType:PROVIDER_NAME,model:opts.model??DEFAULT_MODEL,maxTokens:opts.maxTokens??DEFAULT_MAX_TOKENS,providerConfig:opts.extras},result=await adapter.sendPrompt(opts.prompt,config);return{text:result.content,usage:{inputTokens:result.inputTokens,outputTokens:result.outputTokens,model:result.model,durationMs:result.durationMs}}}getSession(sessionId){let session=this.sessions.get(sessionId);if(!session)throw Error(`Session ${sessionId} not found`);if(session.status==="terminated")throw Error("Session is terminated");return session}buildFullPrompt(prompt,context,files){let fullPrompt=prompt;if(context&&context.length>0){let contextStr=context.map((c)=>`--- Context (${c.type}): ---
30
+ `);this.baseURL=options.baseURL,__classPrivateFieldSet(this,_OpenAI_explicitDataResidency,residencyBaseURL!==void 0||inheritedResidencySelection,"f"),this.timeout=options.timeout??_a3.DEFAULT_TIMEOUT,this.logger=__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_sanitizeLogger).call(this,options.logger??console);let defaultLogLevel="warn";this.logLevel=defaultLogLevel,this.logLevel=parseLogLevel(options.logLevel,"ClientOptions.logLevel",this)??parseLogLevel(readEnv("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??defaultLogLevel,this.fetchOptions=options.fetchOptions,this.maxRetries=__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_normalizeRetries).call(this,options.maxRetries),this.fetch=options.fetch??getDefaultFetch(),__classPrivateFieldSet(this,_OpenAI_encoder,FallbackEncoder,"f");let customHeadersEnv=provider||credential?void 0:readEnv("OPENAI_CUSTOM_HEADERS");if(customHeadersEnv){let parsed={};for(let line of customHeadersEnv.split(`
31
+ `)){let colon=line.indexOf(":");if(colon>=0)parsed[line.substring(0,colon).trim()]=line.substring(colon+1).trim()}options.defaultHeaders=buildHeaders([parsed,options.defaultHeaders])}if(this._options=options,this._provider=providerRuntime,x509Identity){let authentication=new X509WorkloadIdentityAuth(x509Identity,x509Transport,organization,project);this._workloadIdentityAuth=authentication,__classPrivateFieldSet(this,_OpenAI_x509Authentication,authentication,"f"),__classPrivateFieldSet(this,_OpenAI_x509Credential,credential,"f"),__classPrivateFieldSet(this,_OpenAI_x509Fetch,authentication.fetch(),"f"),this.fetch=__classPrivateFieldGet(this,_OpenAI_x509Fetch,"f"),markApprovedX509Client2(this)}else if(identity.legacy)this._workloadIdentityAuth=new WorkloadIdentityAuth(identity.legacy,this.fetch);this.apiKey=typeof apiKey==="string"?apiKey:null,this.adminAPIKey=adminAPIKey,this.organization=organization,this.project=project,this.webhookSecret=webhookSecret}withOptions(options){let residencyBaseURL=resolveDataResidency(options),x509Authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f"),inheritedOptions={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:x509Authentication?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential,provider}=prepareX509ClientClone(inheritedOptions,options,__classPrivateFieldGet(this,_OpenAI_x509Credential,"f"),x509Authentication!==void 0);if(residencyBaseURL!==void 0)delete inheritedOptions.baseURL;let clientOptions={...inheritedOptions,...options,credential,provider,[inheritedDataResidencySelection]:__classPrivateFieldGet(this,_OpenAI_explicitDataResidency,"f")&&residencyBaseURL===void 0&&!hasOwn(options,"baseURL")&&options.credential===void 0&&!provider},client=new this.constructor(clientOptions);if(provider&&new URL(client.baseURL).origin!==new URL(this.baseURL).origin)Object.assign(client._options,{defaultHeaders:options.defaultHeaders,defaultQuery:options.defaultQuery,fetchOptions:options.fetchOptions,fetch:options.fetch}),client.fetchOptions=options.fetchOptions,client.fetch=options.fetch??getDefaultFetch(),client.organization=options.organization??null,client.project=options.project??null;if(__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")&&__classPrivateFieldGet(client,_OpenAI_x509Authentication,"f")&&this.baseURL===client.baseURL&&__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f").matches(__classPrivateFieldGet(client,_OpenAI_x509Authentication,"f")))client._workloadIdentityAuth=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f"),__classPrivateFieldSet(client,_OpenAI_x509Authentication,__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f"),"f"),__classPrivateFieldSet(client,_OpenAI_x509Fetch,__classPrivateFieldGet(this,_OpenAI_x509Fetch,"f"),"f");return client}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(authHeaders,removedHeaders){let context=webSocketHeaderRemovals.get(this);if(context?.baseHeaders)return mergeWebSocketAuthHeaders({headers:context.baseHeaders},authHeaders,context.removedHeaders??new Set).headers;let headers=buildHeaders([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},authHeaders,this._options.defaultHeaders]);headers.nulls.forEach((name)=>(removedHeaders??context?.removedHeaders)?.add(name));let result=Object.fromEntries(headers.values);if(context)context.baseHeaders={...result};return result}validateHeaders({values,nulls},schemes={bearerAuth:!0,adminAPIKeyAuth:!0}){if(values.get("authorization")||values.get("api-key"))return;if(nulls.has("authorization")||nulls.has("api-key"))return;if(this._workloadIdentityAuth&&schemes.bearerAuth)return;throw 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(opts,schemes={bearerAuth:!0,adminAPIKeyAuth:!0}){if((__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")??this._workloadIdentityAuth)instanceof X509WorkloadIdentityAuth&&schemes.adminAPIKeyAuth&&this.adminAPIKey!==null)return await this.adminAPIKeyAuth(opts);return buildHeaders([schemes.bearerAuth?await this.bearerAuth(opts):null,schemes.adminAPIKeyAuth?await this.adminAPIKeyAuth(opts):null])}async bearerAuth(opts){let authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")??this._workloadIdentityAuth;if(authentication){if(authentication instanceof X509WorkloadIdentityAuth){if(authentication===this._workloadIdentityAuth&&(this.fetchWithAuth!==_a3.prototype.fetchWithAuth||this.fetchWithTimeout!==_a3.prototype.fetchWithTimeout))throw new OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.");let snapshots=authentication.headerSnapshots();if(!X509WorkloadIdentityAuth.shouldAuthenticate(opts,snapshots.defaultHeaders,snapshots.requestHeaders))return}let token=authentication instanceof X509WorkloadIdentityAuth?await authentication.getToken(opts,{apiURL:authentication.requestAPIURL(),...authentication.headerSnapshots(),...authentication.requestSnapshot(),signal:authentication.effectiveSignal(),...authentication.tenantSnapshot()}):await authentication.getToken();return buildHeaders([{Authorization:`Bearer ${token}`}])}let{apiKey}=await resolveRealtimeAPIKey(this);if(apiKey==null)return;return buildHeaders([{Authorization:`Bearer ${apiKey}`}])}async adminAPIKeyAuth(opts){if(this.adminAPIKey==null)return;return buildHeaders([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(query){return stringifyQuery(query)}getUserAgent(){return`${this.constructor.name}/JS ${VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${uuid4()}`}makeStatusError(status,error,message,headers){let normalizedError=error&&typeof error==="object"&&error.error==null?{error}:error;return APIError.generate(status,normalizedError,message,headers)}_hasApiKeyProvider(){return typeof this._options.apiKey==="function"}async _callApiKey(capture){if(this._provider)return capture?.(this.apiKey),!1;let apiKey=this._options.apiKey;if(typeof apiKey!=="function")return capture?.(this.apiKey),!1;let deferredCache=getDeferredRealtimeAPIKeyCache(this),invocation=++this._apiKeyInvocation,token;try{token=await apiKey()}catch(err){if(err instanceof OpenAIError)throw err;throw new OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`,{cause:err})}if(typeof token!=="string"||!token)throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);let resolvedToken=token,commit=()=>{if(capture)validateCapturedAPIKey(this,resolvedToken);if(invocation<this._lastCachedAPIKeyInvocation)return resolvedToken;this.apiKey=resolvedToken;let cached=capture?this.apiKey:resolvedToken;return this._lastCachedAPIKeyInvocation=invocation,cached};if(deferredCache)deferredCache.providerKey=resolvedToken,deferredCache.commit=commit;let cached=deferredCache?validateCapturedAPIKey(this,resolvedToken):commit();return capture?.(cached),!0}buildURL(path,query,defaultBaseURL){let baseURL=!__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_baseURLOverridden).call(this)&&defaultBaseURL||this.baseURL,url,baseQuery={},baseParams;if(isAbsoluteURL(path))url=new URL(path);else if(baseURL.includes("?")){let base=new URL(baseURL);baseParams=new URLSearchParams(base.search),baseQuery=Object.fromEntries(baseParams),base.search="",base.hash="",url=new URL(base.toString()+(base.pathname.endsWith("/")&&path.startsWith("/")?path.slice(1):path))}else url=new URL(baseURL+(baseURL.endsWith("/")&&path.startsWith("/")?path.slice(1):path));let defaultQuery=this.defaultQuery(),pathQuery=Object.fromEntries(url.searchParams),overridingQuery;if(!isEmptyObj(baseQuery)||!isEmptyObj(defaultQuery)||!isEmptyObj(pathQuery))overridingQuery={...pathQuery,...defaultQuery,...query},query={...baseQuery,...overridingQuery};if(typeof query==="object"&&query&&!Array.isArray(query)){if(url.search=this.stringifyQuery(query),baseParams&&overridingQuery){let seen=new Set,repeated=new Set;for(let key of baseParams.keys()){if(seen.has(key)&&!hasOwn(overridingQuery,key))repeated.add(key);seen.add(key)}if(repeated.size){let merged=new URLSearchParams;for(let[key,value]of url.searchParams)if(!repeated.has(key))merged.append(key,value);for(let[key,value]of baseParams)if(repeated.has(key))merged.append(key,value);url.search=merged.toString()}}}return url.toString()}async prepareOptions(options){}async prepareRequest(request,{url,options}){}get(path,opts){return this.methodRequest("get",path,opts)}post(path,opts){return this.methodRequest("post",path,opts)}patch(path,opts){return this.methodRequest("patch",path,opts)}put(path,opts){return this.methodRequest("put",path,opts)}delete(path,opts){return this.methodRequest("delete",path,opts)}methodRequest(method,path,opts){return this.request(Promise.resolve(opts).then((opts)=>({method,path,...opts})))}request(options,remainingRetries=null){let authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")??this._workloadIdentityAuth,request=authentication instanceof X509WorkloadIdentityAuth?Promise.resolve(options).then((resolved)=>authentication.runRequest(()=>this.makeRequest(resolved,remainingRetries,void 0),this)):this.makeRequest(options,remainingRetries,void 0);return this.responsePromise(request)}responsePromise(request,parse=(client,props)=>this.parseResponseWithTimeout(client,props)){let promise=new APIPromise(this,request,(client,props)=>{let resume=__classPrivateFieldGet(this,_OpenAI_responseAttempts,"f").get(props.controller)?.continueRequest;return resume?resume(()=>parse(client,props)):parse(client,props)});return promise.withResponse=async()=>{let data=await promise,{response}=await request;return{data,response,request_id:response.headers.get("x-request-id")}},promise._thenUnwrap=(transform)=>this.responsePromise(request,async(client,props)=>addRequestID(transform(await parse(client,props),props),props.response)),promise}async parseResponseWithTimeout(client,props){if(props.options.stream||props.options.__binaryResponse||props.response.status===204||props.response.headers.get("content-length")==="0")return defaultParseResponse(client,props);while(!0){let attempt=__classPrivateFieldGet(this,_OpenAI_responseAttempts,"f").get(props.controller),timeout=attempt?.timeout??props.options.timeout??this.timeout,x509Authentication=attempt?.authentication,callerSignal=x509Authentication?props.controller.signal:props.options.signal,abortError=()=>x509Authentication&&callerSignal?this._makeUserAbortError(callerSignal):new APIUserAbortError,remaining;try{remaining=x509Authentication?.remainingTimeout(props.options,timeout)??Math.max(0,props.startTime+timeout-Date.now())}catch(error){let cancellation=callerSignal?.aborted?abortError():void 0;throw props.controller.abort(),CancelReadableStream(props.response.body).catch(()=>{return}),cancellation??error}let timer,abortListener,timedOut=!1;try{if(callerSignal?.aborted&&attempt?.helperMethod!=="runTools")throw abortError();let timeoutPromise=new Promise((_,reject)=>{if(timer=setTimeout(()=>{timedOut=!0,props.controller.abort(),reject(new APIConnectionTimeoutError)},remaining),callerSignal)abortListener=()=>{if(!timedOut)reject(abortError())},callerSignal.addEventListener("abort",abortListener,{once:!0})});return await Promise.race([defaultParseResponse(client,props),timeoutPromise])}catch(error){if(callerSignal?.aborted&&!timedOut)throw abortError();if(!timedOut){if(x509Authentication&&error instanceof SyntaxError)throw SyntaxError("X.509 workload identity API response contains invalid JSON.");if(x509Authentication&&!(error instanceof OpenAIError))throw new APIConnectionError({message:"X.509 workload identity API response body could not be read."});throw error}let retriesRemaining=attempt?.retriesRemaining??0;if(!retriesRemaining||attempt?.hasStreamingBody||props.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&props.options.body instanceof globalThis.ReadableStream||typeof props.options.body==="object"&&props.options.body!==null&&((Symbol.asyncIterator in props.options.body)||(Symbol.iterator in props.options.body)&&("next"in props.options.body)&&typeof props.options.body.next==="function"))throw new APIConnectionTimeoutError;if(timer!==void 0)clearTimeout(timer);if(abortListener)callerSignal?.removeEventListener("abort",abortListener);abortListener=void 0;let next=await this.retryRequest(props.options,retriesRemaining,props.retryOfRequestLogID??props.requestLogID,void 0,props.requestSignal);Object.assign(props,next)}finally{if(timer!==void 0)clearTimeout(timer);if(abortListener)callerSignal?.removeEventListener("abort",abortListener)}}}async readX509ResponseError(response,options,timeout,controller,authentication){let deadline=new AbortController,callerSignal=controller.signal,timedOut=!1,cancel=()=>deadline.abort(callerSignal.reason);if(callerSignal.addEventListener("abort",cancel,{once:!0}),callerSignal.aborted)cancel();try{let remaining=authentication.remainingTimeout(options,timeout),expiration=authentication.waitForRetry(remaining,deadline.signal).then(()=>{throw new APIConnectionTimeoutError}),body=await Promise.race([response.text().catch(()=>"X.509 workload identity API response body could not be read."),expiration]);if(callerSignal.aborted)throw this._makeUserAbortError(callerSignal);return body}catch(error){if(error instanceof APIConnectionTimeoutError)timedOut=!callerSignal.aborted,controller.abort(),CancelReadableStream(response.body).catch(()=>{return});if(callerSignal.aborted&&!timedOut)throw this._makeUserAbortError(callerSignal);throw error}finally{callerSignal.removeEventListener("abort",cancel),deadline.abort()}}async makeRequest(optionsInput,retriesRemaining,retryOfRequestLogID){let options=await optionsInput,maxRetries=__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_normalizeRetries).call(this,options.maxRetries??this.maxRetries);if(retriesRemaining==null)retriesRemaining=maxRetries;else retriesRemaining=Math.min(__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_normalizeRetries).call(this,retriesRemaining),maxRetries);let x509Authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f");x509Authentication?.beginRequestPreparation(),await this.prepareOptions(options),x509Authentication?.beginRequestPlanning();let built;try{let candidate=await this.buildRequest(options,{retryCount:maxRetries-retriesRemaining});if(built={req:candidate.req,url:candidate.url,timeout:candidate.timeout},x509Authentication){if(validatePositiveInteger("timeout",built.timeout),x509Authentication.authorizePlannedRequest(built.url,built.req,built.timeout),X509WorkloadIdentityAuth.isStreamingRequestBody(built.req.body))options.__metadata={...options.__metadata,hasStreamingBody:!0};if(await this.prepareRequest(built.req,{url:built.url,options}),await this._provider?.prepareRequest?.(built.req,{url:built.url,options,timeout:built.timeout}),x509Authentication.beginRequestPlanning(),x509Authentication.authorizePlannedRequest(built.url,built.req,built.timeout,!0),X509WorkloadIdentityAuth.isStreamingRequestBody(built.req.body))options.__metadata={...options.__metadata,hasStreamingBody:!0};let callerSignal=x509Authentication.requestSnapshot().signal;if(callerSignal?.aborted||built.req.signal?.aborted)throw this._makeUserAbortError(callerSignal?.aborted?callerSignal:built.req.signal);x509Authentication.setEffectiveSignal(built.req.signal||callerSignal?createRequestController(built.req.signal??callerSignal,callerSignal).signal:void 0),x509Authentication.beginRequestNetwork();let security=options.__security??{bearerAuth:!0},authenticationHeaders=await this.authHeaders(options,security),suppliedHeaders=x509Authentication.headerSnapshots(),supplied=buildHeaders([suppliedHeaders.defaultHeaders,suppliedHeaders.requestHeaders]);for(let[name,value]of authenticationHeaders?.values??[])if(!supplied.nulls.has(name)&&!built.req.headers.has(name))built.req.headers.set(name,value);this.validateHeaders(buildHeaders([supplied,built.req.headers]),security)}}catch(error){if(x509Authentication?.retireRequestBody(),x509Authentication&&retriesRemaining&&!options.__metadata?.hasStreamingBody&&X509WorkloadIdentityAuth.isRetryableFailure(error))return await this.retryRequest(options,retriesRemaining,retryOfRequestLogID??"x509-token-exchange",X509WorkloadIdentityAuth.retryHeaders(error));throw error}let{req,url}=built,timeout=x509Authentication?Math.min(built.timeout,x509Authentication.requestSnapshot().timeout):built.timeout;x509Authentication?.bindRequest(options,req,this.adminAPIKey);let hasStreamingBody=options.__metadata?.hasStreamingBody===!0,providerAuthStartedAt,providerAuthTimeout;if(!x509Authentication){if(await this.prepareRequest(req,{url,options}),this._provider?.timeoutIncludesAuth)providerAuthStartedAt={wallTime:Date.now(),monotonicTime:performance.now()};try{await this._provider?.prepareRequest?.(req,{url,options,timeout})}catch(error){if(!providerAuthStartedAt||!isProviderTimeoutError(error))throw error;providerAuthTimeout=error}}if(x509Authentication?.adoptRequestHeaders(req),x509Authentication&&X509WorkloadIdentityAuth.isStreamingRequestBody(req.body))hasStreamingBody=!0;let requestLogID="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),retryLogStr=retryOfRequestLogID===void 0?"":`, retryOf: ${retryOfRequestLogID}`,startTime=x509Authentication?.requestStartedAt(options)??providerAuthStartedAt?.wallTime??Date.now();if(this.logLevel==="debug"){let body=typeof req.body==="string"?{type:"string",length:req.body.length}:req.body;loggerFor(this).debug(`[${requestLogID}] sending request`,formatRequestDetails({retryOfRequestLogID,method:options.method,url,options:x509Authentication?{body,...x509Authentication.requestSnapshot()}:{...options,body},headers:req.headers}))}let callerSignal=x509Authentication?x509Authentication.requestSnapshot().signal:options.signal;if(callerSignal?.aborted||req.signal?.aborted)throw this._makeUserAbortError(callerSignal?.aborted?callerSignal:req.signal);let security=options.__security??{bearerAuth:!0},controller=x509Authentication||this.fetchWithTimeout===_a3.prototype.fetchWithTimeout?createRequestController(req.signal??(x509Authentication?callerSignal:void 0),x509Authentication?callerSignal:void 0):new AbortController,remainingTimeout=x509Authentication?.remainingTimeout(options,timeout)??(providerAuthStartedAt?timeout-(performance.now()-providerAuthStartedAt.monotonicTime):timeout);if(providerAuthStartedAt&&remainingTimeout<=0)providerAuthTimeout??(providerAuthTimeout=new APIConnectionTimeoutError);let fetchWithAuth=x509Authentication?_a3.prototype.fetchWithAuth:this.fetchWithAuth;x509Authentication?.releaseRequestBody(req.body);let response=providerAuthTimeout??await fetchWithAuth.call(this,url,req,remainingTimeout,controller,security).catch(castToError),headersTime=Date.now();if(response instanceof globalThis.Error){let retryMessage=`retrying, ${retriesRemaining} attempts remaining`;if(callerSignal?.aborted||req.signal?.aborted)throw this._makeUserAbortError(callerSignal?.aborted?callerSignal:req.signal);let isTimeout=isAbortError(response)||/timed? ?out/i.test(String(response)+("cause"in response?String(response.cause):""));if(retriesRemaining&&!hasStreamingBody&&(!x509Authentication||isTransientX509ConnectionError2(response)))return loggerFor(this).info(`[${requestLogID}] connection ${isTimeout?"timed out":"failed"} - ${retryMessage}`),loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout?"timed out":"failed"} (${retryMessage})`,formatRequestDetails({retryOfRequestLogID,url,durationMs:headersTime-startTime,message:x509Authentication?"X.509 workload identity API connection failed.":response.message})),this.retryRequest(options,retriesRemaining,retryOfRequestLogID??requestLogID,void 0,req.signal);let terminalMessage=hasStreamingBody?"error; streaming body cannot be retried":"error; no more retries left";if(loggerFor(this).info(`[${requestLogID}] connection ${isTimeout?"timed out":"failed"} - ${terminalMessage}`),loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout?"timed out":"failed"} (${terminalMessage})`,formatRequestDetails({retryOfRequestLogID,url,durationMs:headersTime-startTime,message:x509Authentication?"X.509 workload identity API connection failed.":response.message})),response instanceof OAuthError||response instanceof SubjectTokenProviderError)throw response;if(isTimeout){let transportCause="cause"in response?response.cause:void 0,timeoutError=typeof transportCause==="object"&&transportCause!==null&&"code"in transportCause&&transportCause.code==="UND_ERR_HEADERS_TIMEOUT"?new APIConnectionTimeoutError({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new APIConnectionTimeoutError;if(x509Authentication)throw new APIConnectionTimeoutError;throw Object.assign(timeoutError,{cause:response})}if(x509Authentication)throw new APIConnectionError({message:"X.509 workload identity API connection failed."});throw new APIConnectionError({message:getConnectionErrorMessage(response),cause:response})}let specialHeaders=[...response.headers.entries()].filter(([name])=>name==="x-request-id").map(([name,value])=>", "+name+": "+JSON.stringify(value)).join(""),responseInfo=`[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${redactURL(url)} ${response.ok?"succeeded":"failed"} with status ${response.status} in ${headersTime-startTime}ms`;if(!response.ok){let rejectedX509Credential=response.status===401&&x509Authentication&&security.bearerAuth&&x509Authentication.usedWorkloadToken(options);if(rejectedX509Credential)x509Authentication.invalidateToken();if(response.status===401&&(x509Authentication||this._workloadIdentityAuth)&&security.bearerAuth&&(!x509Authentication||x509Authentication.usedWorkloadToken(options))&&(!x509Authentication||retriesRemaining>0)&&!hasStreamingBody&&!options.__metadata?.workloadIdentityTokenRefreshed){if(x509Authentication)CancelReadableStream(response.body).catch(()=>{return});else await CancelReadableStream(response.body),this._workloadIdentityAuth?.invalidateToken();let replayOptions={...options,__metadata:{...options.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(replayOptions,x509Authentication?retriesRemaining-1:retriesRemaining,retryOfRequestLogID??requestLogID)}let shouldRetry=rejectedX509Credential&&options.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(response);if(retriesRemaining&&shouldRetry&&!hasStreamingBody){let retryMessage=`retrying, ${retriesRemaining} attempts remaining`;if(x509Authentication)CancelReadableStream(response.body).catch(()=>{return});else await CancelReadableStream(response.body);return loggerFor(this).info(`${responseInfo} - ${retryMessage}`),loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`,formatRequestDetails({retryOfRequestLogID,url:response.url,status:response.status,headers:response.headers,durationMs:headersTime-startTime})),this.retryRequest(options,retriesRemaining,retryOfRequestLogID??requestLogID,response.headers,req.signal)}let retryMessage=shouldRetry?hasStreamingBody?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";loggerFor(this).info(`${responseInfo} - ${retryMessage}`);let errText=x509Authentication?await this.readX509ResponseError(response,options,timeout,controller,x509Authentication):await response.text().catch((err)=>castToError(err).message),errJSON=safeJSON(errText),errMessage=errJSON?void 0:errText;throw loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`,formatRequestDetails({retryOfRequestLogID,url:response.url,status:response.status,headers:response.headers,message:errMessage,durationMs:Date.now()-startTime})),this.makeStatusError(response.status,errJSON,errMessage,response.headers)}loggerFor(this).info(responseInfo),loggerFor(this).debug(`[${requestLogID}] response start`,formatRequestDetails({retryOfRequestLogID,url:response.url,status:response.status,headers:response.headers,durationMs:headersTime-startTime}));let continueRequest=x509Authentication?.continuation();return x509Authentication?.releaseRequestCredentials(),__classPrivateFieldGet(this,_OpenAI_responseAttempts,"f").set(controller,{timeout,retriesRemaining,hasStreamingBody,...x509Authentication?{authentication:x509Authentication}:{},helperMethod:options.__metadata?.helperMethod,...continueRequest?{continueRequest}:{}}),{response,options,controller,requestSignal:req.signal,requestLogID,retryOfRequestLogID,startTime}}getAPIList(path,Page,opts){return this.requestAPIList(Page,opts&&"then"in opts?opts.then((opts)=>({method:"get",path,...opts})):{method:"get",path,...opts})}requestAPIList(Page,options){let authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")??this._workloadIdentityAuth,request=authentication instanceof X509WorkloadIdentityAuth?Promise.resolve(options).then((resolved)=>authentication.runRequest(()=>this.makeRequest(resolved,null,void 0),this)):this.makeRequest(options,null,void 0),page=new PagePromise(this,request,Page),guarded=this.responsePromise(request,async(client,props)=>{let body=await this.parseResponseWithTimeout(client,props);return new Page(client,props.response,body,props.options)});return page.then=guarded.then.bind(guarded),page.catch=guarded.catch.bind(guarded),page.finally=guarded.finally.bind(guarded),page.withResponse=guarded.withResponse.bind(guarded),page._thenUnwrap=guarded._thenUnwrap.bind(guarded),page}async fetchWithAuth(url,init,timeout,controller,schemes={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!__classPrivateFieldGet(this,_OpenAI_x509Fetch,"f")&&schemes.bearerAuth){let headers=init.headers;if(headers.get("Authorization")===`Bearer ${WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER}`){let token=await this._workloadIdentityAuth.getToken();headers.set("Authorization",`Bearer ${token}`)}}return await(__classPrivateFieldGet(this,_OpenAI_x509Fetch,"f")?_a3.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,url,init,timeout,controller)}async fetchWithTimeout(url,init,ms,controller){let{signal,method,...options}=init||{},abort=this._makeAbort(controller),composed=!!signal&&composedCallerSignals.get(controller)===signal,cleanup=signal&&!composed?addRequestAbortListener(signal,abort,controller.signal):void 0,timeout=setTimeout(abort,ms),isReadableBody=globalThis.ReadableStream&&options.body instanceof globalThis.ReadableStream||typeof options.body==="object"&&options.body!==null&&Symbol.asyncIterator in options.body,fetchOptions={signal:controller.signal,...isReadableBody?{duplex:"half"}:{},method:"GET",...options};if(method)fetchOptions.method=method.toUpperCase();try{let response=await(__classPrivateFieldGet(this,_OpenAI_x509Fetch,"f")??this.fetch).call(void 0,url,fetchOptions);if(cleanup)retainRequestAbortCallback(response.body??response,abort,controller.signal);return response}catch(err){throw cleanup?.(),err}finally{clearTimeout(timeout)}}async shouldRetry(response){let shouldRetryHeader=response.headers.get("x-should-retry");if(shouldRetryHeader==="true")return!0;if(shouldRetryHeader==="false")return!1;if(response.status===408)return!0;if(response.status===409)return!0;if(response.status===429)return!0;if(response.status>=500)return!0;return!1}async retryRequest(options,retriesRemaining,requestLogID,responseHeaders,requestSignal=options.signal){let timeoutMillis,retryAfterMillisHeader=responseHeaders?.get("retry-after-ms");if(retryAfterMillisHeader){let timeoutMs=parseFloat(retryAfterMillisHeader);if(!Number.isNaN(timeoutMs))timeoutMillis=timeoutMs}let retryAfterHeader=responseHeaders?.get("retry-after");if(retryAfterHeader&&timeoutMillis===void 0){let timeoutSeconds=parseFloat(retryAfterHeader);if(!Number.isNaN(timeoutSeconds))timeoutMillis=timeoutSeconds*1000;else timeoutMillis=Date.parse(retryAfterHeader)-Date.now()}if(timeoutMillis===void 0||!Number.isFinite(timeoutMillis)||timeoutMillis<0||timeoutMillis>60000){let maxRetries=__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_normalizeRetries).call(this,options.maxRetries??this.maxRetries);timeoutMillis=this.calculateDefaultRetryTimeoutMillis(retriesRemaining,maxRetries)}let x509Authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f");if(x509Authentication){let remaining=x509Authentication.remainingTimeout(options,x509Authentication.requestSnapshot().timeout);if(timeoutMillis>=remaining)throw new APIConnectionTimeoutError}if(x509Authentication)await x509Authentication.waitForRetry(timeoutMillis,x509Authentication.effectiveSignal());else{let retrySignals=requestSignal===options.signal?[requestSignal]:[requestSignal,options.signal];try{await sleep(timeoutMillis,...retrySignals)}catch(error){let abortedSignal=retrySignals.find((signal)=>signal?.aborted);if(abortedSignal)throw this._makeUserAbortError(abortedSignal);throw error}}return this.makeRequest(options,retriesRemaining-1,requestLogID)}calculateDefaultRetryTimeoutMillis(retriesRemaining,maxRetries){let numRetries=maxRetries-retriesRemaining,sleepSeconds=Math.min(0.5*Math.pow(2,numRetries),8),jitter=1-Math.random()*0.25;return sleepSeconds*jitter*1000}async buildRequest(inputOptions,{retryCount=0}={}){if(__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")&&!__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f").inRequest(this)){let authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f");return await authentication.runRequest(async()=>{let built=await _a3.prototype.buildRequest.call(this,inputOptions,{retryCount});return authentication.releaseRequestBody(built.req.body),built},this)}let options={...inputOptions},x509Authentication=__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f"),x509Tenant=x509Authentication?.snapshotTenant(this.organization,this.project),x509Headers=x509Authentication?.snapshotHeaders(this._options.defaultHeaders,options.headers);if(x509Headers)options.headers=x509Headers.requestHeaders;let x509ClientFetchOptions=x509Authentication?snapshotX509RequestOptions(this.fetchOptions):void 0,x509RequestFetchOptions=x509Authentication?snapshotX509RequestOptions(options.fetchOptions):void 0,{method,path,query,defaultBaseURL}=options,url=this.buildURL(path,query,defaultBaseURL);x509Authentication?.snapshotAPIURL(url);let explicitTimeout="timeout"in options;if(explicitTimeout)validatePositiveInteger("timeout",options.timeout);if(options.timeout=options.timeout??this.timeout,x509Authentication&&x509RequestFetchOptions)x509Authentication.snapshotRequest(options.signal,options.timeout,x509RequestFetchOptions);if(x509Authentication){let snapshot=x509Authentication.requestSnapshot();if(options.timeout=snapshot.timeout,snapshot.signal===void 0)delete options.signal;else options.signal=snapshot.signal}let authenticationHeaders=this._provider||x509Authentication?void 0:await this.authHeaders(inputOptions,inputOptions.__security??{bearerAuth:!0});if(options.__metadata?.finalizeMultipart===!0&&hasUploadableValue(options.body)){let multipartHeaders=buildHeaders([options.headers]);multipartHeaders.values.delete("content-type"),multipartHeaders.nulls.delete("content-type");let finalized=await maybeMultipartFormRequestOptions({...options,headers:multipartHeaders},this,options.__metadata?.preserveMultipartFilenames===!0?{stripFilenames:!1}:void 0);inputOptions.body=options.body=finalized.body,options.headers=finalized.headers,inputOptions.__metadata=options.__metadata={...finalized.__metadata,finalizedMultipart:{body:finalized.body,contentType:buildHeaders([finalized.headers]).values.get("content-type")}}}if(options.__metadata?.streamFromBody===!0)finalizeStreamingFormRequestOptions(options),inputOptions.stream=options.stream;let isRawJSON=JSON.isRawJSON,jsonRoot,jsonRootVisited=!1,jsonStream=!1,jsonSerialized=!1,stopObserving=options.__metadata?.streamFromBody===!0&&typeof options.body==="object"&&options.body!==null?observeJSONRequestBody(options.body,{value(holder,key,value){if(!jsonRootVisited)jsonRootVisited=!0,jsonRoot=value;else if(holder===jsonRoot&&key==="stream"){if(jsonStream=value===!0,isRawJSON?.(value))jsonStream=value.rawJSON==="true";else if(value!==null&&typeof value==="object")try{jsonStream=Boolean.prototype.valueOf.call(value)}catch{}}return},complete(){jsonSerialized=!0}}):void 0,encodedBody;try{encodedBody=this.buildBody({options})}finally{stopObserving?.()}let{bodyHeaders,body,isStreamingBody}=encodedBody,captureResponseParser=options.__metadata?.captureResponseParser;if(typeof captureResponseParser==="function")captureResponseParser(options);if(options.__metadata?.streamFromBody===!0){if(body instanceof FormData)inputOptions.stream=options.stream=body.get("stream")==="true";else if(jsonSerialized&&jsonRoot!==null&&typeof jsonRoot==="object"&&!Array.isArray(jsonRoot)&&!isRawJSON?.(jsonRoot))inputOptions.stream=options.stream=jsonStream}if(isStreamingBody)inputOptions.__metadata={...inputOptions.__metadata,hasStreamingBody:!0},x509Authentication?.ownRequestBody(body,options.body);let finalizedContentType,finalizedMultipart=options.__metadata?.finalizedMultipart;if(typeof finalizedMultipart==="object"&&finalizedMultipart!==null&&"body"in finalizedMultipart&&"contentType"in finalizedMultipart){let{body:multipartBody,contentType}=finalizedMultipart;if(multipartBody===body){if(typeof contentType==="string")finalizedContentType=contentType;else if(contentType===null)finalizedContentType=null}}let reqHeaders=await this.buildHeaders({options:inputOptions,method,bodyHeaders,authenticationHeaders,retryCount,x509Headers,x509Timeout:explicitTimeout?options.timeout:void 0,x509Tenant});if(finalizedContentType===null)reqHeaders.delete("content-type");else if(finalizedContentType!==void 0)reqHeaders.set("content-type",finalizedContentType);return{req:{method,headers:reqHeaders,...options.signal&&{signal:options.signal},...globalThis.ReadableStream&&body instanceof globalThis.ReadableStream&&{duplex:"half"},...body&&{body},...(x509Authentication?x509ClientFetchOptions:this.fetchOptions)??{},...(x509Authentication?x509RequestFetchOptions:options.fetchOptions)??{}},url,timeout:options.timeout}}async buildHeaders({options,method,bodyHeaders,authenticationHeaders,retryCount,x509Headers,x509Timeout,x509Tenant}){let idempotencyHeaders={};if(this.idempotencyHeader&&method!=="get"){if(!options.idempotencyKey)options.idempotencyKey=this.defaultIdempotencyKey();idempotencyHeaders[this.idempotencyHeader]=options.idempotencyKey}let helperMethod=options.__metadata?.helperMethod,timeout=x509Headers?x509Timeout:options.timeout,headers=buildHeaders([idempotencyHeaders,{Accept:"application/json",...!isRunningInBrowserOrBrowserWorker()?{"User-Agent":this.getUserAgent()}:void 0,"X-Stainless-Retry-Count":String(retryCount),...timeout?{"X-Stainless-Timeout":String(Math.trunc(timeout/1000))}:{},...getPlatformHeaders(),...typeof helperMethod==="string"?{"X-Stainless-Helper-Method":helperMethod}:{},"OpenAI-Organization":x509Tenant?x509Tenant.organization:this.organization,"OpenAI-Project":x509Tenant?x509Tenant.project:this.project},__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")&&!__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f").isPlanningRequest()?await this.authHeaders(options,options.__security??{bearerAuth:!0}):authenticationHeaders,x509Headers?.defaultHeaders??this._options.defaultHeaders,bodyHeaders,x509Headers?.requestHeaders??options.headers]);if(!this._provider&&!__classPrivateFieldGet(this,_OpenAI_x509Authentication,"f")?.isPlanningRequest())this.validateHeaders(headers,options.__security??{bearerAuth:!0});return headers.values}_makeAbort(controller){return()=>controller.abort()}_makeUserAbortError(signal){let error=new APIUserAbortError;return Object.defineProperty(error,"cause",{value:signal.reason,writable:!0,configurable:!0}),error}buildBody({options}){let{body,headers:rawHeaders}=options;if(!body){if(body===void 0&&"body"in options)return{...__classPrivateFieldGet(this,_OpenAI_encoder,"f").call(this,{body,headers:buildHeaders([rawHeaders])}),isStreamingBody:!1};return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1}}let headers=buildHeaders([rawHeaders]),isReadableStream=typeof globalThis.ReadableStream<"u"&&body instanceof globalThis.ReadableStream,isRetryableBody=!isReadableStream&&(typeof body==="string"||body instanceof ArrayBuffer||ArrayBuffer.isView(body)||typeof globalThis.Blob<"u"&&body instanceof globalThis.Blob||body instanceof URLSearchParams||body instanceof FormData);if(ArrayBuffer.isView(body)||body instanceof ArrayBuffer||body instanceof DataView||typeof body==="string"&&headers.values.has("content-type")||globalThis.Blob&&body instanceof globalThis.Blob||body instanceof FormData||body instanceof URLSearchParams||isReadableStream)return{bodyHeaders:void 0,body,isStreamingBody:!isRetryableBody};else if(typeof body==="object"&&((Symbol.asyncIterator in body)||(Symbol.iterator in body)&&("next"in body)&&typeof body.next==="function"))return{bodyHeaders:void 0,body:ReadableStreamFrom(body),isStreamingBody:!0};else if(typeof body==="object"&&headers.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(body),isStreamingBody:!1};else return{...__classPrivateFieldGet(this,_OpenAI_encoder,"f").call(this,{body,headers}),isStreamingBody:!1}}}function createRequestController(callerSignal,originalSignal){let controller=new AbortController;if(!callerSignal)return controller;let nativeAbortSignal=globalThis.AbortSignal;if(typeof nativeAbortSignal?.any!=="function"||!(callerSignal instanceof nativeAbortSignal))return controller;try{let signals=[controller.signal,callerSignal];if(originalSignal&&originalSignal!==callerSignal)signals.push(originalSignal);let composed=nativeAbortSignal.any(signals);Object.defineProperty(controller,"signal",{value:composed,configurable:!0}),composedCallerSignals.set(controller,callerSignal)}catch{}return controller}function getConnectionErrorMessage(error){if(isUndiciDispatcherVersionMismatchError(error))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });";return}function isUndiciDispatcherVersionMismatchError(error){let current=error;for(let i=0;i<8&&current&&typeof current==="object";i++){let err=current;if(err.code==="UND_ERR_INVALID_ARG"&&typeof err.message==="string"&&err.message.includes("invalid onRequestStart method"))return!0;current=err.cause}return!1}var _OpenAI_instances,_a3,_OpenAI_encoder,_OpenAI_x509Authentication,_OpenAI_x509Credential,_OpenAI_x509Fetch,_OpenAI_explicitDataResidency,_OpenAI_responseAttempts,_OpenAI_sanitizedLoggers,_OpenAI_baseURLOverridden,_OpenAI_normalizeRetries,_OpenAI_isSensitiveLogKey,_OpenAI_sanitizeLogValue,_OpenAI_sanitizeLogger,WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER="workload-identity-auth",inheritedDataResidencySelection,composedCallerSignals;var init_client=__esm(()=>{init_tslib();init_values();init_abort();init_parse();init_detect_platform();init_request_options();init_query();init_data_residency();init_error();init_pagination();init_workload_identity_auth();init_x509_api_origin();init_x509_workload_identity_auth();init_x509_credential_options();init_x509_transport_state();init_error();init_uploads2();init_resources();init_batches();init_completions3();init_content_provenance_checks();init_decisions();init_embeddings2();init_files4();init_images();init_models();init_moderations();init_videos();init_admin();init_audio();init_beta();init_chat();init_containers();init_conversations();init_evals();init_fine_tuning();init_graders2();init_live();init_realtime2();init_responses2();init_safety();init_skills();init_uploads3();init_vector_stores();init_webhooks();init_api_promise();init_realtime_credentials();init_detect_platform();init_headers();init_ws();init_provider();init_uploads();init_log();init_values();inheritedDataResidencySelection=Symbol("inheritedDataResidencySelection");_a3=OpenAI,_OpenAI_encoder=new WeakMap,_OpenAI_x509Authentication=new WeakMap,_OpenAI_x509Credential=new WeakMap,_OpenAI_x509Fetch=new WeakMap,_OpenAI_explicitDataResidency=new WeakMap,_OpenAI_responseAttempts=new WeakMap,_OpenAI_instances=new WeakSet,_OpenAI_baseURLOverridden=function(){return __classPrivateFieldGet(this,_OpenAI_explicitDataResidency,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"},_OpenAI_normalizeRetries=function(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>=0?value:2},_OpenAI_isSensitiveLogKey=function(key){let normalized=key.replace(/[^a-z0-9]/gi,"").toLowerCase();if(/authorization|authentication|cookie|session|signature|assertion|connectionstring|devicecode|codeverifier|accountkey|mtlskey|proxyauth|^(?:auth|key|sig|sas|jwt|bearer|pfx|p12)$|(?:sid|token|secret|password|passwd|pwd|credential|passphrase|apikey|accesskey|privatekey|username)s?$/.test(normalized))return!0;let prefix=/api|access|secret|private|security|refresh|id|bearer|aws|azure|openai|admin|client|proxy|auth/.exec(normalized);return prefix!==null&&/key|token|secret|password|passwd|pwd|credential|auth/.test(normalized.slice(prefix.index+prefix[0].length))},_OpenAI_sanitizeLogValue=function(value,seen){let redactString=(entry)=>entry.replace(/(\/\/)([^/\s?#]*@)(?=[^/\s?#]+)/g,"$1[REDACTED]@").replace(/(^|[\s/])([^/\s]+)/g,(match,prefix,token)=>{let start=prefix==="/"?token.search(/[=(]/)+1:0;if(prefix==="/"&&start===0)return match;let colon=token.indexOf(":",start+1),at=token.length-2;while(at>=0&&(token[at]!=="@"||token[at+1]==="@"))at--;return colon>=0&&at>colon?`${prefix}${token.slice(0,start)}[REDACTED]${token.slice(at)}`:match}).replace(/(^|[\s,;])([a-z][a-z0-9_-]*)(\s*:\s*)([^\r\n,;]+)/gi,(match,prefix,key,separator)=>__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_isSensitiveLogKey).call(this,key)?`${prefix}${key}${separator}[REDACTED]`:match).replace(/(^|[?&#;])([^=&;\s?#/]+)=([^&;\s#]+)/g,(match,separator,key)=>{let decoded=key;try{decoded=globalThis.decodeURIComponent(key)}catch{}return __classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_isSensitiveLogKey).call(this,decoded)?`${separator}${key}=[REDACTED]`:match}),getLogString=(entry)=>{try{return globalThis.String.prototype.valueOf.call(entry)}catch{return}},isSensitiveLogLabel=(entry)=>{let label=getLogString(entry);if(label!==void 0)return __classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_isSensitiveLogKey).call(this,label);try{return entry instanceof globalThis.String}catch{return!0}},pending=[],pendingMaps=[],sanitizedValue,getOwnLogDescriptor=(entry,key)=>{try{return{descriptor:globalThis.Object.getOwnPropertyDescriptor(entry,key),failed:!1}}catch{return{descriptor:void 0,failed:!0}}},enqueue=(entry,depth,assign)=>{if(depth>64||pending.length>=4096){assign("[REDACTED]");return}pending.push({value:entry,depth,assign})};enqueue(value,0,(entry)=>{sanitizedValue=entry});for(let cursor=0;cursor<pending.length;cursor+=1){let{value:current,depth,assign}=pending[cursor];if(typeof current==="string"){assign(redactString(current));continue}if(typeof current==="function"||typeof current==="symbol"){assign("[REDACTED]");continue}if(typeof current!=="object"||current===null){assign(current);continue}let previous=seen.get(current);if(previous!==void 0){assign(previous);continue}try{let boxedString=getLogString(current);if(boxedString!==void 0){let sanitized=new globalThis.String(redactString(boxedString));seen.set(current,sanitized),assign(sanitized);continue}if(current instanceof globalThis.String){seen.set(current,"[REDACTED]"),assign("[REDACTED]");continue}let RuntimeHeaders=globalThis.Headers;if(typeof RuntimeHeaders==="function"&&current instanceof RuntimeHeaders){let sanitized=new RuntimeHeaders;seen.set(current,sanitized),assign(sanitized),RuntimeHeaders.prototype.forEach.call(current,(entry,key)=>{sanitized.set(key,__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_isSensitiveLogKey).call(this,key)?"[REDACTED]":redactString(entry))});continue}if(current instanceof URL){let sanitized=new URL(URL.prototype.toString.call(current));if(seen.set(current,sanitized),assign(sanitized),sanitized.username)sanitized.username="[REDACTED]";if(sanitized.password)sanitized.password="[REDACTED]";for(let[key]of sanitized.searchParams)if(__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_isSensitiveLogKey).call(this,key))sanitized.searchParams.set(key,"[REDACTED]");if(sanitized.hash)sanitized.hash=redactString(sanitized.hash);continue}if(Array.isArray(current)){let lengthDescriptor=getOwnLogDescriptor(current,"length");if(lengthDescriptor.failed||!lengthDescriptor.descriptor||!("value"in lengthDescriptor.descriptor)||typeof lengthDescriptor.descriptor.value!=="number"){seen.set(current,"[REDACTED]"),assign("[REDACTED]");continue}let sanitized=[];seen.set(current,sanitized),assign(sanitized);let limit=Math.min(lengthDescriptor.descriptor.value,4096),firstDescriptor=getOwnLogDescriptor(current,"0"),firstKey=!firstDescriptor.failed&&firstDescriptor.descriptor&&"value"in firstDescriptor.descriptor?firstDescriptor.descriptor.value:void 0;for(let index=0;index<limit;index+=1){let property=index===0?firstDescriptor:getOwnLogDescriptor(current,`${index}`);if(property.failed){sanitized[index]="[REDACTED]";continue}let descriptor=property.descriptor;if(!descriptor?.enumerable)continue;if(index===1&&(firstDescriptor.failed||firstDescriptor.descriptor&&!("value"in firstDescriptor.descriptor)||isSensitiveLogLabel(firstKey))){sanitized[index]="[REDACTED]";continue}if(!("value"in descriptor)){sanitized[index]="[REDACTED]";continue}enqueue(descriptor.value,depth+1,(entry)=>{sanitized[index]=entry})}if(sanitized.length=limit,lengthDescriptor.descriptor.value>limit)sanitized[limit]="[REDACTED]";continue}if(current instanceof globalThis.Map){let sanitized=new globalThis.Map,entries=[];pendingMaps.push({map:sanitized,entries}),seen.set(current,sanitized),assign(sanitized),globalThis.Map.prototype.forEach.call(current,(entry,key)=>{let pair=["[REDACTED]","[REDACTED]"];if(entries.push(pair),enqueue(key,depth+1,(safeKey)=>{if(typeof safeKey!=="function"&&typeof safeKey!=="symbol"&&!(typeof key==="object"&&key!==null&&safeKey===key))pair[0]=safeKey}),isSensitiveLogLabel(key))return;enqueue(entry,depth+1,(safeEntry)=>{pair[1]=safeEntry})});continue}if(current instanceof globalThis.Set){let sanitized=new globalThis.Set;seen.set(current,sanitized),assign(sanitized),globalThis.Set.prototype.forEach.call(current,(entry)=>{enqueue(entry,depth+1,(safeEntry)=>{sanitized.add(safeEntry)})});continue}if(current instanceof globalThis.Date){assign(new globalThis.Date(globalThis.Date.prototype.getTime.call(current)));continue}let RuntimeReadableStream=globalThis.ReadableStream;if(typeof RuntimeReadableStream==="function"&&current instanceof RuntimeReadableStream||current instanceof globalThis.ArrayBuffer||globalThis.ArrayBuffer.isView(current)){seen.set(current,"[REDACTED]"),assign("[REDACTED]");continue}let keys;try{keys=globalThis.Reflect.ownKeys(current)}catch{seen.set(current,"[REDACTED]"),assign("[REDACTED]");continue}let sanitized={};seen.set(current,sanitized),assign(sanitized);for(let key of keys){if(typeof key!=="string")continue;let property=getOwnLogDescriptor(current,key);if(property.failed){sanitized[key]="[REDACTED]";continue}let descriptor=property.descriptor;if(!descriptor?.enumerable)continue;if(__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_isSensitiveLogKey).call(this,key)){sanitized[key]="[REDACTED]";continue}if(!("value"in descriptor)){sanitized[key]="[REDACTED]";continue}enqueue(descriptor.value,depth+1,(safeEntry)=>{sanitized[key]=safeEntry})}}catch{seen.set(current,"[REDACTED]"),assign("[REDACTED]")}}for(let{map,entries}of pendingMaps)for(let[key,entry]of entries)map.set(key,entry);return sanitizedValue},_OpenAI_sanitizeLogger=function(logger){if(__classPrivateFieldGet(_a3,_a3,"f",_OpenAI_sanitizedLoggers).has(logger))return logger;let sanitized=new globalThis.Proxy(Object.create(null),{get:(_facade,property)=>{let value=globalThis.Reflect.get(logger,property,logger);if(typeof value!=="function")return value;if(typeof property!=="string"||!["debug","info","warn","error","trace","log"].includes(property))return value.bind(logger);return(...args)=>{let seen=new WeakMap;return globalThis.Reflect.apply(value,logger,args.map((entry)=>__classPrivateFieldGet(this,_OpenAI_instances,"m",_OpenAI_sanitizeLogValue).call(this,entry,seen)))}},set:(_facade,property,value)=>globalThis.Reflect.set(logger,property,value,logger)});return __classPrivateFieldGet(_a3,_a3,"f",_OpenAI_sanitizedLoggers).add(sanitized),sanitized};_OpenAI_sanitizedLoggers={value:new globalThis.WeakSet};OpenAI.OpenAI=_a3;OpenAI.DEFAULT_TIMEOUT=600000;OpenAI.OpenAIError=OpenAIError;OpenAI.APIError=APIError;OpenAI.APIConnectionError=APIConnectionError;OpenAI.APIConnectionTimeoutError=APIConnectionTimeoutError;OpenAI.APIUserAbortError=APIUserAbortError;OpenAI.NotFoundError=NotFoundError;OpenAI.ConflictError=ConflictError;OpenAI.RateLimitError=RateLimitError;OpenAI.BadRequestError=BadRequestError;OpenAI.AuthenticationError=AuthenticationError;OpenAI.InternalServerError=InternalServerError;OpenAI.PermissionDeniedError=PermissionDeniedError;OpenAI.UnprocessableEntityError=UnprocessableEntityError;OpenAI.InvalidWebhookSignatureError=InvalidWebhookSignatureError;OpenAI.toFile=toFile;OpenAI.toStreamingFile=toStreamingFile;OpenAI.Decisions=Decisions;OpenAI.Completions=Completions2;OpenAI.Chat=Chat;OpenAI.Embeddings=Embeddings;OpenAI.Files=Files3;OpenAI.Images=Images;OpenAI.ContentProvenanceChecks=ContentProvenanceChecks;OpenAI.Audio=Audio;OpenAI.Moderations=Moderations;OpenAI.Models=Models;OpenAI.FineTuning=FineTuning;OpenAI.Graders=Graders2;OpenAI.VectorStores=VectorStores;OpenAI.Safety=Safety;OpenAI.Webhooks=Webhooks;OpenAI.Beta=Beta;OpenAI.Batches=Batches;OpenAI.Uploads=Uploads;OpenAI.Admin=Admin;OpenAI.Responses=Responses2;OpenAI.Live=Live;OpenAI.Realtime=Realtime2;OpenAI.Conversations=Conversations;OpenAI.Evals=Evals;OpenAI.Containers=Containers;OpenAI.Skills=Skills;OpenAI.Videos=Videos;OpenAI.ConversationCursorPage=ConversationCursorPage;OpenAI.CursorPage=CursorPage;OpenAI.NextCursorPage=NextCursorPage;OpenAI.Page=Page;OpenAI.TokenPage=TokenPage;composedCallerSignals=new WeakMap});function toResponseInputItems(items){let inputItems=[];for(let item of items){let inputItem=toResponseInputItem(item);if(inputItem)inputItems.push(inputItem)}return inputItems}function toResponseInputItem(item){switch(item.type){case"message":{if(item.role!=="assistant"||!("id"in item)||!Array.isArray(item.content))return stripCreatedBy(item);let content=item.content.map((part)=>{if((part.type==="output_text"||part.type==="refusal")&&"parsed"in part){let{parsed:_parsed,...inputPart}=part;return inputPart}return part});if(content.every((part,index)=>part===item.content[index]))return stripCreatedBy(item);return{...stripCreatedBy(item),content}}case"function_call":{let inputItem=stripCreatedBy(item);if(!("parsed_arguments"in inputItem))return inputItem;let{parsed_arguments:_parsedArguments,...withoutParsedArguments}=inputItem;return withoutParsedArguments}case"additional_tools":{if(item.role!=="developer")return null;return stripCreatedBy(item)}case"shell_call_output":{let output=item.output.map((chunk)=>stripCreatedBy(chunk));return{...stripCreatedBy(item),output}}case"computer_call_output":{let{created_by:_createdBy,...withoutCreatedBy}=item;if(withoutCreatedBy.status==="failed")return null;return withoutCreatedBy}case"custom_tool_call_output":{if("status"in item&&item.status!=="completed")return null;let{created_by:_createdBy,status:_status,...inputItem}=item;return inputItem}case"apply_patch_call":case"apply_patch_call_output":case"code_interpreter_call":case"compaction":case"compaction_trigger":case"computer_call":case"configuration_update":case"custom_tool_call":case"file_search_call":case"function_call_output":case"image_generation_call":case"item_reference":case"local_shell_call":case"local_shell_call_output":case"mcp_approval_request":case"mcp_approval_response":case"mcp_call":case"mcp_list_tools":case"program":case"program_output":case"reasoning":case"shell_call":case"tool_search_call":case"tool_search_output":case"web_search_call":case null:case void 0:return stripCreatedBy(item);default:return assertNever4(item)}}function stripCreatedBy(item){if(!("created_by"in item))return item;let{created_by:_createdBy,...rest}=item;return rest}function assertNever4(value){let type=value.type;throw TypeError(`Unsupported response item type: ${String(type)}`)}async function settleDiagnostic(result){try{await result}catch{}}function reportDiagnostic(observer,event,started,nativeUsage){if(!observer)return;try{let usage=null;if(nativeUsage){let{input_tokens,output_tokens,total_tokens}=nativeUsage;if(Number.isSafeInteger(input_tokens)&&input_tokens>=0&&Number.isSafeInteger(output_tokens)&&output_tokens>=0&&Number.isSafeInteger(total_tokens)&&total_tokens>=0)usage={input_tokens,output_tokens,total_tokens}}let result=observer({...event,call_id:event.call_id??null,member:event.member??null,duration_ms:Math.max(0,performance.now()-started),usage});settleDiagnostic(result)}catch{}}var init_runner_diagnostics=()=>{};function overlayRequestOptions(original,changes){if(!original)return changes;let shadow=Object.create(Object.getPrototypeOf(original)),deleted=new Set;return new Proxy(shadow,{ownKeys(target){if(!Reflect.isExtensible(target))return Reflect.ownKeys(target);let virtual=[...Reflect.ownKeys(original),...Reflect.ownKeys(changes)].filter((key)=>!deleted.has(key));return[...new Set([...virtual,...Reflect.ownKeys(target)])]},getOwnPropertyDescriptor(target,key){let local=Object.getOwnPropertyDescriptor(target,key);if(local||deleted.has(key)||!Reflect.isExtensible(target))return local;let descriptor=Object.getOwnPropertyDescriptor(hasOwn(changes,key)?changes:original,key);return descriptor?{...descriptor,configurable:!0}:void 0},get(target,key,receiver){if(hasOwn(target,key))return Reflect.get(target,key,receiver);if(deleted.has(key)||!Reflect.isExtensible(target))return Reflect.get(target,key,original);return hasOwn(changes,key)?Reflect.get(changes,key,changes):Reflect.get(original,key,original)},set(target,key,value,receiver){if(hasOwn(target,key))return Reflect.set(target,key,value,receiver);return Reflect.defineProperty(target,key,{value,writable:!0,enumerable:!0,configurable:!0})},deleteProperty(target,key){if(!Reflect.deleteProperty(target,key))return!1;return deleted.add(key),!0},has(target,key){return Reflect.has(target,key)||Reflect.isExtensible(target)&&!deleted.has(key)&&(hasOwn(changes,key)||Reflect.has(original,key))},preventExtensions(target){if(!Reflect.isExtensible(target))return!0;let keys=new Set([...Reflect.ownKeys(original),...Reflect.ownKeys(changes)]);for(let key of keys){if(deleted.has(key)||hasOwn(target,key))continue;let source=hasOwn(changes,key)?changes:original,descriptor=Object.getOwnPropertyDescriptor(source,key);if(!descriptor)continue;if("value"in descriptor)Object.defineProperty(target,key,{...descriptor,configurable:!0});else{let getter=descriptor.get,replaced=!1,replacement,bound={...descriptor,configurable:!0};if(getter)bound.get=()=>replaced?replacement:getter.call(source);if(descriptor.set)bound.set=(value)=>{replaced=!0,replacement=value};Object.defineProperty(target,key,bound)}}return Reflect.preventExtensions(target)}})}class RunnerLifecycle{constructor(){this.state="open"}enter(){if(this.state!=="open")throw TypeError(this.state==="busy"?"Helper is busy.":"Helper is closed.");this.state="busy"}leave(){this.state=this.state==="draining"?"closed":"open"}close(){return this.state=this.state==="busy"||this.state==="draining"?"draining":"closed",{status:this.state}}}function isObjectPrototype(value){if(value===Object.prototype)return!0;if(Object.getPrototypeOf(value)!==null)return!1;let descriptor=Object.getOwnPropertyDescriptor(value,"constructor");if(!descriptor||!hasOwn(descriptor,"value"))return!1;let constructor=descriptor.value;if(typeof constructor!=="function")return!1;let prototype=Object.getOwnPropertyDescriptor(constructor,"prototype");return prototype!==void 0&&hasOwn(prototype,"value")&&prototype.value===value&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(Object)}function configuredOption(options,key,copied){let owner=options;while(owner!==null&&!isObjectPrototype(owner)){let descriptor=Object.getOwnPropertyDescriptor(owner,key);if(descriptor)return owner===options&&descriptor.enumerable&&copied?copied[key]:options[key];owner=Object.getPrototypeOf(owner)}return}function continuationRequestOptions(client,options,signal){let headers=buildHeaders([options&&Object.getOwnPropertyDescriptor(options,"headers")?.enumerable?options.headers:void 0]),effectiveHeaders=buildHeaders([client._options.defaultHeaders,headers]),idempotencyKey=options&&Object.getOwnPropertyDescriptor(options,"idempotencyKey")?.enumerable?options.idempotencyKey:void 0;if(!idempotencyKey&&!effectiveHeaders.values.has("idempotency-key")){if(options===void 0&&signal===void 0)return;let captured={signal};for(let[key,value]of[["headers",headers],["idempotencyKey",idempotencyKey]])Object.defineProperty(captured,key,{value,writable:!0,configurable:!0,enumerable:options?Boolean(Object.getOwnPropertyDescriptor(options,key)?.enumerable):!1});return overlayRequestOptions(options,captured)}let key=`stainless-node-retry-${uuid4()}`;return overlayRequestOptions(options,{signal,idempotencyKey:key,headers:buildHeaders([headers,...effectiveHeaders.values.has("idempotency-key")?[{"idempotency-key":key}]:[]])})}function protectRunnerJSON(value){let pending=[value],seen=new WeakSet;for(let record of pending){let prototype=Object.getPrototypeOf(record);if(seen.has(record)||!Array.isArray(record)&&prototype!==Object.prototype&&prototype!==null)continue;if(seen.add(record),!hasOwn(record,"toJSON"))Object.defineProperty(record,"toJSON",{value:void 0,writable:!0,configurable:!0});let entries=Object.values(record);for(let entry of entries)if(entry!==null&&typeof entry==="object")pending.push(entry)}}var init_runner_lifecycle=__esm(()=>{init_values();init_headers()});function emitted(value,key){return hasOwn(value,key)?value[key]:void 0}function allEntries(value,accepts){if(!Array.isArray(value))return!1;for(let index=0;index<value.length;index+=1){let entry=Object.getOwnPropertyDescriptor(value,index);if(!entry?.enumerable||!("value"in entry)||!accepts(entry.value))return!1}return!0}function annotation(value){if(!isObj(value))return!1;switch(emitted(value,"type")){case"file_citation":return typeof emitted(value,"file_id")==="string"&&typeof emitted(value,"filename")==="string"&&Number.isInteger(emitted(value,"index"));case"url_citation":return typeof emitted(value,"url")==="string"&&typeof emitted(value,"title")==="string"&&Number.isInteger(emitted(value,"start_index"))&&Number.isInteger(emitted(value,"end_index"));case"container_file_citation":return typeof emitted(value,"container_id")==="string"&&typeof emitted(value,"file_id")==="string"&&typeof emitted(value,"filename")==="string"&&Number.isInteger(emitted(value,"start_index"))&&Number.isInteger(emitted(value,"end_index"));case"file_path":return typeof emitted(value,"file_id")==="string"&&Number.isInteger(emitted(value,"index"));default:return!1}}function topLogprob(value){return isObj(value)&&typeof emitted(value,"token")==="string"&&typeof emitted(value,"logprob")==="number"&&Number.isFinite(emitted(value,"logprob"))&&allEntries(emitted(value,"bytes"),Number.isInteger)}function logprob(value){return isObj(value)&&topLogprob(value)&&allEntries(emitted(value,"top_logprobs"),topLogprob)}function contentPart(value){if(!isObj(value))return!1;if(emitted(value,"type")==="refusal")return typeof emitted(value,"refusal")==="string";let logprobs=emitted(value,"logprobs");return emitted(value,"type")==="output_text"&&typeof emitted(value,"text")==="string"&&allEntries(emitted(value,"annotations"),annotation)&&(logprobs===void 0||logprobs===null||allEntries(logprobs,logprob))}function isNativeResponseMessage(value){if(!isObj(value))return!1;let status=emitted(value,"status"),phase=emitted(value,"phase");return emitted(value,"type")==="message"&&typeof emitted(value,"id")==="string"&&emitted(value,"role")==="assistant"&&(status==="completed"||status==="incomplete"||status==="in_progress")&&(phase===void 0||phase===null||phase==="commentary"||phase==="final_answer")&&allEntries(emitted(value,"content"),contentPart)}function isNativeResponseReasoning(value){if(!isObj(value))return!1;let status=emitted(value,"status"),content=emitted(value,"content"),encrypted_content=emitted(value,"encrypted_content");return emitted(value,"type")==="reasoning"&&typeof emitted(value,"id")==="string"&&allEntries(emitted(value,"summary"),(part)=>isObj(part)&&emitted(part,"type")==="summary_text"&&typeof emitted(part,"text")==="string")&&(content===void 0||allEntries(content,(part)=>isObj(part)&&emitted(part,"type")==="reasoning_text"&&typeof emitted(part,"text")==="string"))&&(encrypted_content===void 0||encrypted_content===null||typeof encrypted_content==="string")&&(status===void 0||status==="completed"||status==="incomplete"||status==="in_progress")}var init_native_response_message=__esm(()=>{init_values()});function validateComputerSafetyChecks(call){let checks=configuredOption(call,"pending_safety_checks");if(!configuredOption(call,"actions")||checks!==void 0){if(!Array.isArray(checks))throw new OpenAIError("ComputerToolset requires valid pending safety checks before execution.");for(let index=0;index<checks.length;index+=1){let check=hasOwn(checks,index)?checks[index]:void 0,code=check?configuredOption(check,"code"):void 0,message=check?configuredOption(check,"message"):void 0;if(!check||!hasOwn(check,"id")||typeof check.id!=="string"||code!==void 0&&code!==null&&typeof code!=="string"||message!==void 0&&message!==null&&typeof message!=="string")throw new OpenAIError("ComputerToolset requires valid pending safety checks before execution.")}}}function validComputerPoint(point){return isObj(point)&&hasOwn(point,"x")&&hasOwn(point,"y")&&Number.isInteger(point.x)&&Number.isInteger(point.y)}function isDenseArray(values){if(!Array.isArray(values))return!1;for(let index=0;index<values.length;index+=1)if(!hasOwn(values,index))return!1;return!0}function validComputerKeys(keys){return isDenseArray(keys)&&keys.every((key)=>typeof key==="string")}function validComputerAction(action){if(!action||!hasOwn(action,"type"))return!1;let keys="keys"in action?configuredOption(action,"keys"):void 0;if(keys!==null&&keys!==void 0&&!validComputerKeys(keys))return!1;switch(action.type){case"click":{let button=configuredOption(action,"button");return validComputerPoint(action)&&["left","right","wheel","back","forward"].some((value)=>value===button)}case"double_click":case"move":return validComputerPoint(action);case"scroll":return validComputerPoint(action)&&Number.isInteger(configuredOption(action,"scroll_x"))&&Number.isInteger(configuredOption(action,"scroll_y"));case"drag":{let path=configuredOption(action,"path");return isDenseArray(path)&&path.every(validComputerPoint)}case"keypress":return validComputerKeys(configuredOption(action,"keys"));case"type":return typeof configuredOption(action,"text")==="string";case"screenshot":case"wait":return!0;default:return!1}}function computerActions(call){let singleAction=configuredOption(call,"action"),batch=configuredOption(call,"actions");if(!hasOwn(call,"type")||!hasOwn(call,"status")||!hasOwn(call,"id")||!hasOwn(call,"call_id")||call.type!=="computer_call"||call.status!=="completed"||typeof call.id!=="string"||typeof call.call_id!=="string"||singleAction===null||batch===null||singleAction!==void 0===(batch!==void 0))throw new OpenAIError("ComputerToolset requires a completed call with exactly one of action or actions.");validateComputerSafetyChecks(call);let actions=batch??[singleAction];if(!Array.isArray(actions)||actions.length===0)throw new OpenAIError("ComputerToolset requires at least one computer action.");if(!isDenseArray(actions))throw new OpenAIError("ComputerToolset received an invalid computer action.");for(let action of actions)if(Array.isArray(action)||!validComputerAction(action))throw new OpenAIError("ComputerToolset received an invalid computer action.");return actions}function snapshotComputerPolicy(options){return{signal:configuredOption(options,"signal"),approveSafetyChecks:configuredOption(options,"approveSafetyChecks")?.bind(options),beforeAction:configuredOption(options,"beforeAction")?.bind(options),onDiagnostic:configuredOption(options,"onDiagnostic")?.bind(options)}}function computerRunTools(params,maxSteps){if(!Number.isSafeInteger(maxSteps)||maxSteps<1)throw TypeError("ComputerToolset maxSteps must be a positive safe integer.");let suppliedTools=configuredOption(params,"tools"),tools=suppliedTools===void 0?[{type:"computer"}]:suppliedTools,conversation=configuredOption(params,"conversation"),previousResponse=configuredOption(params,"previous_response_id");if(configuredOption(params,"stream")||configuredOption(params,"background")||conversation!==void 0&&conversation!==null||previousResponse!==void 0&&previousResponse!==null||!Array.isArray(tools)||tools.length!==1||tools.some((tool)=>{let type=tool&&configuredOption(tool,"type");return type!=="computer"&&type!=="computer_use_preview"}))throw TypeError("ComputerToolset.run requires non-streaming, foreground, one computer tool and explicit input history.");return tools}function releaseForcedComputerChoice(choice){if(choice==="required"||typeof choice==="object"&&hasOwn(choice,"type")&&["computer","computer_use_preview","computer_use"].includes(choice.type))return"auto";if(typeof choice==="object"&&hasOwn(choice,"type")&&choice.type==="allowed_tools"&&hasOwn(choice,"mode")&&choice.mode==="required")return{...choice,mode:"auto"};return choice}function validateComputerChecklistOwner(call){let owner=call;while(owner!==null&&!isObjectPrototype(owner)){let descriptor=Object.getOwnPropertyDescriptor(owner,"pending_safety_checks");if(descriptor){if(owner!==call||!descriptor.enumerable||!("value"in descriptor))throw new OpenAIError("ComputerToolset requires own enumerable data for safety checks.");break}owner=Object.getPrototypeOf(owner)}}function snapshotComputerCall(call){if(Array.isArray(call))throw new OpenAIError("ComputerToolset requires a call object.");validateComputerChecklistOwner(call);let snapshot=structuredClone(call);for(let action of computerActions(snapshot))if(action.type==="double_click"&&configuredOption(action,"keys")===void 0)action.keys=null;return snapshot}function actionApprovalCall(call){let checks=configuredOption(call,"pending_safety_checks")??[],actions=configuredOption(call,"actions");if(!Array.isArray(actions)){let view=structuredClone({...call,pending_safety_checks:checks});return protectRunnerJSON(view),view}let sources={actions,pending_safety_checks:checks},view=structuredClone({...call,actions:[],pending_safety_checks:[]});protectRunnerJSON(view);for(let key of["actions","pending_safety_checks"]){let source=sources[key],materialized=!1,value,save=(replacement)=>{if(value=replacement,materialized=!0,Object.getOwnPropertyDescriptor(view,key)?.configurable)Object.defineProperty(view,key,{value,writable:!0,enumerable:!0,configurable:!0});return value};Object.defineProperty(view,key,{configurable:!0,enumerable:!0,get(){if(materialized)return value;let captured=structuredClone(source);return protectRunnerJSON(captured),save(captured)},set(replacement){if(Object.isFrozen(view))throw TypeError("Cannot assign to frozen computer approval call.");save(replacement)}})}return view}function computerCalls(response,earlierIdentities,earlierCallIds){if(configuredOption(response,"status")!=="completed")throw new OpenAIError("ComputerToolset.run received a response that is not completed.");let calls=[],output=[],source=configuredOption(response,"output");if(!Array.isArray(source))throw new OpenAIError("ComputerToolset.run received an invalid output array.");let{length}=source;if(!Number.isSafeInteger(length)||length<0)throw new OpenAIError("ComputerToolset.run received an invalid output array.");let hasFinalMessage=!1,identities=new Set,callIds=new Set;for(let index=0;index<length;index+=1){let raw=hasOwn(source,index)?source[index]:void 0;if(!raw)throw new OpenAIError("ComputerToolset.run received an absent output item.");let descriptors=Object.getOwnPropertyDescriptors(raw);for(let[name,descriptor]of Object.entries(descriptors))if(descriptor.get)if(name==="type")descriptors.type={value:descriptor.get.call(raw),enumerable:Boolean(descriptor.enumerable),configurable:Boolean(descriptor.configurable)};else descriptor.get=descriptor.get.bind(raw);let captured=Object.create(Object.getPrototypeOf(raw),descriptors),item=hasOwn(captured,"type")&&captured.type==="computer_call"?snapshotComputerCall(captured):structuredClone(captured);if(!hasOwn(item,"type")||!hasOwn(item,"id")||typeof item.id!=="string")throw new OpenAIError("ComputerToolset.run requires emitted output type and id fields.");if(item.type==="computer_call"){if(callIds.has(item.call_id)||earlierCallIds.has(item.call_id))throw new OpenAIError("ComputerToolset.run received a duplicate computer call identity.");callIds.add(item.call_id),calls.push(item)}else if(item.type==="message"){if(!isNativeResponseMessage(item))throw new OpenAIError("ComputerToolset.run requires native assistant content before replay.");hasFinalMessage||(hasFinalMessage=item.status==="completed"&&(!hasOwn(item,"phase")||item.phase!=="commentary"))}else if(item.type==="reasoning"){if(!isNativeResponseReasoning(item))throw new OpenAIError("ComputerToolset.run requires native reasoning content before replay.")}else if(item.type==="compaction"){if(!hasOwn(item,"encrypted_content")||typeof item.encrypted_content!=="string")throw new OpenAIError("ComputerToolset.run requires native compaction content before replay.")}else throw new OpenAIError("ComputerToolset.run cannot handle a non-computer output item.");if(output.push(item),identities.has(item.id)||item.id!==""&&earlierIdentities.has(item.id))throw new OpenAIError("ComputerToolset.run received a duplicate output item identity.");identities.add(item.id)}if(calls.length===0&&!hasFinalMessage)throw new OpenAIError("ComputerToolset.run received no completed final message.");for(let id of identities)if(id!=="")earlierIdentities.add(id);for(let id of callIds)earlierCallIds.add(id);return{calls,output}}function computerDriverMethod(driver,name){let method=configuredOption(driver,name);if(typeof method!=="function")throw new OpenAIError("ComputerToolset requires callable computer driver methods.");return method}class ComputerToolset{constructor(driver){this.lifecycle=new RunnerLifecycle;let methods={click:computerDriverMethod(driver,"click"),double_click:computerDriverMethod(driver,"double_click"),drag:computerDriverMethod(driver,"drag"),keypress:computerDriverMethod(driver,"keypress"),move:computerDriverMethod(driver,"move"),screenshot:computerDriverMethod(driver,"screenshot"),scroll:computerDriverMethod(driver,"scroll"),type:computerDriverMethod(driver,"type"),wait:computerDriverMethod(driver,"wait")};this.driver={click:methods.click.bind(driver),double_click:methods.double_click.bind(driver),drag:methods.drag.bind(driver),keypress:methods.keypress.bind(driver),move:methods.move.bind(driver),screenshot:methods.screenshot.bind(driver),scroll:methods.scroll.bind(driver),type:methods.type.bind(driver),wait:methods.wait.bind(driver)}}close(){return this.lifecycle.close()}static validate(call){return snapshotComputerCall(call)}async run(client,params,options={}){this.lifecycle.enter();try{return await this.runOwned(client,params,options)}finally{this.lifecycle.leave()}}async runOwned(client,params,options){let suppliedMaxSteps=configuredOption(options,"maxSteps"),maxSteps=suppliedMaxSteps===void 0?20:suppliedMaxSteps,encoded=JSON.stringify(params),decoded=JSON.parse(encoded);if(!isObj(decoded))throw TypeError("ComputerToolset request must be an object.");let request=decoded,tools=computerRunTools(request,maxSteps),suppliedInput=configuredOption(request,"input"),input=typeof suppliedInput==="string"?[{role:"user",content:suppliedInput}]:[...suppliedInput===void 0?[]:suppliedInput],include=[...configuredOption(request,"include")??[]];if(!include.includes("reasoning.encrypted_content"))include.push("reasoning.encrypted_content");let body={...request,tools,include,input};protectRunnerJSON(body);let policy=snapshotComputerPolicy(options),supplied=configuredOption(options,"requestOptions"),ownSignal=supplied&&Object.getOwnPropertyDescriptor(supplied,"signal"),signal=policy.signal??(supplied&&configuredOption(supplied,"signal"))??void 0;if(policy.signal||ownSignal&&!("value"in ownSignal)||signal&&!ownSignal?.enumerable)supplied=overlayRequestOptions(supplied,{signal});let executionOptions={...policy,signal},earlierIdentities=new Set,earlierCallIds=new Set;for(let item of input){if(!isObj(item))continue;let id=hasOwn(item,"id")?item.id:void 0,callId=hasOwn(item,"call_id")?item.call_id:void 0;if(typeof id==="string"&&id!=="")earlierIdentities.add(id);if(typeof callId==="string")earlierCallIds.add(callId)}for(let step=0;;step+=1){signal?.throwIfAborted();let nextOptions=step===0?supplied:continuationRequestOptions(client,supplied,signal);if(nextOptions&&Object.getOwnPropertyDescriptor(nextOptions,"body")?.enumerable)throw TypeError("ComputerToolset.run requestOptions.body is not supported.");let response;try{response=await client.responses.create(body,nextOptions)}catch(error){throw signal?.throwIfAborted(),error}signal?.throwIfAborted();let{calls,output}=computerCalls(response,earlierIdentities,earlierCallIds);if(calls.length===0)return response;if(step>=maxSteps-1)throw new OpenAIError("ComputerToolset.run reached maxSteps before executing another computer call.");let projected=toResponseInputItems(output);protectRunnerJSON(projected);let replay=JSON.parse(JSON.stringify(projected));protectRunnerJSON(replay);for(let item of replay)body.input.push(item);for(let call of calls){let observation=await this.executeOwned(call,executionOptions);body.input.push(observation)}let choice=configuredOption(body,"tool_choice");if(choice!==void 0&&choice!==null){if(body.tool_choice=releaseForcedComputerChoice(choice),typeof body.tool_choice==="object")protectRunnerJSON(body.tool_choice)}}}async execute(call,options={}){this.lifecycle.enter();try{return await this.executeOwned(call,snapshotComputerPolicy(options))}finally{this.lifecycle.leave()}}async executeOwned(call,policy){let snapshot=ComputerToolset.validate(call),projected=toResponseInputItems([snapshot]);protectRunnerJSON(projected);let replay=JSON.parse(JSON.stringify(projected)),actions=computerActions(snapshot);for(let action of actions)if((action.type==="click"||action.type==="drag"||action.type==="move"||action.type==="scroll")&&configuredOption(action,"keys")===void 0)Object.defineProperty(action,"keys",{value:void 0,enumerable:!0,writable:!0,configurable:!0});let needsScreenshot=actions[actions.length-1]?.type!=="screenshot";policy.signal?.throwIfAborted();let checks=configuredOption(snapshot,"pending_safety_checks")??[],nativeChecks=checks.map((check)=>({id:check.id,code:hasOwn(check,"code")?check.code:void 0,message:hasOwn(check,"message")?check.message:void 0})),captured=replay[0]?.pending_safety_checks??[];if(!Array.isArray(captured)||captured.length!==nativeChecks.length||!captured.every((value,index)=>isObj(value)&&hasOwn(value,"id")&&value.id===nativeChecks[index]?.id&&(hasOwn(value,"code")?value.code:void 0)===nativeChecks[index]?.code&&(hasOwn(value,"message")?value.message:void 0)===nativeChecks[index]?.message))throw new OpenAIError("ComputerToolset serialization changed the pending safety checks.");let acknowledged=captured;if(checks.length>0){for(let check of checks)for(let key of["code","message"])if(!hasOwn(check,key))Object.defineProperty(check,key,{value:void 0,enumerable:!0,writable:!0,configurable:!0});let started=performance.now();try{let view=structuredClone({...snapshot,pending_safety_checks:checks});protectRunnerJSON(view);let approved=await policy.approveSafetyChecks?.(view,{signal:policy.signal});if(policy.signal?.throwIfAborted(),approved!==!0)throw new OpenAIError("ComputerToolset requires explicit approval of pending safety checks.");reportDiagnostic(policy.onDiagnostic,{api:"computer",stage:"approval",reason:"completed",call_id:snapshot.call_id},started)}catch(error){throw reportDiagnostic(policy.onDiagnostic,{api:"computer",stage:"approval",reason:policy.signal?.aborted?"cancelled":"policy_failed",call_id:snapshot.call_id},started),policy.signal?.throwIfAborted(),error}}for(let action of actions)await this.perform(action,snapshot,policy);if(needsScreenshot)await this.perform({type:"screenshot"},snapshot,policy);policy.signal?.throwIfAborted();let output=await this.captureScreenshot(snapshot,policy),observation={type:"computer_call_output",call_id:snapshot.call_id,output,...checks.length>0?{acknowledged_safety_checks:acknowledged}:{}};return protectRunnerJSON(observation),observation}async captureScreenshot(snapshot,policy){let started=performance.now(),output;try{let supplied=await this.driver.screenshot({signal:policy.signal});if(policy.signal?.throwIfAborted(),!isObj(supplied))throw new OpenAIError("ComputerToolset screenshot must return a computer_screenshot with image_url or file_id.");let type=configuredOption(supplied,"type"),image_url=configuredOption(supplied,"image_url"),file_id=configuredOption(supplied,"file_id");if(type!=="computer_screenshot"||image_url!==void 0&&(typeof image_url!=="string"||!image_url.trim())||file_id!==void 0&&(typeof file_id!=="string"||!file_id.trim())||image_url===void 0&&file_id===void 0)throw new OpenAIError("ComputerToolset screenshot must return a computer_screenshot with image_url or file_id.");output={type,...image_url===void 0?{}:{image_url},...file_id===void 0?{}:{file_id}},reportDiagnostic(policy.onDiagnostic,{api:"computer",stage:"action",reason:"completed",call_id:snapshot.call_id,member:"screenshot"},started)}catch(error){throw reportDiagnostic(policy.onDiagnostic,{api:"computer",stage:"action",reason:policy.signal?.aborted?"cancelled":"driver_failed",call_id:snapshot.call_id,member:"screenshot"},started),policy.signal?.throwIfAborted(),error}return policy.signal?.throwIfAborted(),output}async perform(action,call,options){if(options.signal?.throwIfAborted(),options.beforeAction)await ComputerToolset.approveAction(action,call,options.beforeAction,options);options.signal?.throwIfAborted();let started=performance.now();try{let dispatched=structuredClone(action);switch(dispatched.type){case"click":{await this.driver.click(dispatched,{signal:options.signal});break}case"double_click":{await this.driver.double_click(dispatched,{signal:options.signal});break}case"drag":{await this.driver.drag(dispatched,{signal:options.signal});break}case"keypress":{await this.driver.keypress(dispatched,{signal:options.signal});break}case"move":{await this.driver.move(dispatched,{signal:options.signal});break}case"screenshot":break;case"scroll":{await this.driver.scroll(dispatched,{signal:options.signal});break}case"type":{await this.driver.type(dispatched,{signal:options.signal});break}case"wait":{await this.driver.wait(dispatched,{signal:options.signal});break}default:throw new OpenAIError("ComputerToolset received an unsupported computer action.")}if(options.signal?.throwIfAborted(),action.type!=="screenshot")reportDiagnostic(options.onDiagnostic,{api:"computer",stage:"action",reason:"completed",call_id:call.call_id,member:action.type},started)}catch(error){throw reportDiagnostic(options.onDiagnostic,{api:"computer",stage:"action",reason:options.signal?.aborted?"cancelled":"driver_failed",call_id:call.call_id,member:action.type},started),options.signal?.throwIfAborted(),error}options.signal?.throwIfAborted()}static async approveAction(action,call,beforeAction,options){let started=performance.now();try{let view=structuredClone(action);protectRunnerJSON(view);let approved=await beforeAction(view,actionApprovalCall(call),{signal:options.signal});if(options.signal?.throwIfAborted(),approved!==!0)throw new OpenAIError("ComputerToolset action declined by beforeAction.");reportDiagnostic(options.onDiagnostic,{api:"computer",stage:"approval",reason:"completed",call_id:call.call_id,member:action.type},started)}catch(error){throw reportDiagnostic(options.onDiagnostic,{api:"computer",stage:"approval",reason:options.signal?.aborted?"cancelled":"policy_failed",call_id:call.call_id,member:action.type},started),options.signal?.throwIfAborted(),error}}}var init_computer=__esm(()=>{init_error2();init_runner_diagnostics();init_runner_lifecycle();init_native_response_message();init_values()});function hasDeploymentPathSegment(baseURL){try{return new URL(baseURL).pathname.split("/").includes("deployments")}catch{return!1}}var AzureOpenAI,_deployments_endpoints;var init_azure=__esm(()=>{init_headers();init_error2();init_utils2();init_path();init_client();init_data_residency();AzureOpenAI=class AzureOpenAI extends OpenAI{constructor({baseURL=readEnv("OPENAI_BASE_URL"),apiKey=readEnv("AZURE_OPENAI_API_KEY"),apiVersion=readEnv("OPENAI_API_VERSION"),endpoint,deployment,azureADTokenProvider,dangerouslyAllowBrowser,dataResidency,...opts}={}){if(assertNoDataResidency(dataResidency,"AzureOpenAI"),!apiVersion)throw new OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof azureADTokenProvider==="function")dangerouslyAllowBrowser??(dangerouslyAllowBrowser=!0);if(!azureADTokenProvider&&!apiKey)throw new OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(azureADTokenProvider&&apiKey)throw new OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(opts.defaultQuery={...opts.defaultQuery,"api-version":apiVersion},!baseURL){if(!endpoint)endpoint=process.env.AZURE_OPENAI_ENDPOINT;if(!endpoint)throw new OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let endpointEnd=endpoint.length;while(endpointEnd>0&&endpoint[endpointEnd-1]==="/")endpointEnd--;baseURL=`${endpoint.slice(0,endpointEnd)}/openai`}else if(endpoint)throw new OpenAIError("baseURL and endpoint are mutually exclusive");super({apiKey:azureADTokenProvider??apiKey,baseURL,...opts,...dangerouslyAllowBrowser===void 0?{}:{dangerouslyAllowBrowser}});this.apiVersion="",this.apiVersion=apiVersion,this.deploymentName=deployment}withOptions(options){let azureOptions={apiVersion:this.apiVersion,deployment:this.deploymentName,...options};if(hasOwn(options,"endpoint")&&options.endpoint!==void 0&&!hasOwn(options,"baseURL"))azureOptions.baseURL=void 0;return super.withOptions(azureOptions)}async buildRequest(options,props={}){if(_deployments_endpoints.has(options.path)&&options.method==="post"&&options.body!==void 0){if(!isObj(options.body))throw Error("Expected request body to be an object");let model=this.deploymentName||options.body.model||options.__metadata?.model;if(model!==void 0&&!hasDeploymentPathSegment(this.baseURL))options.path=path`/deployments/${model}`+options.path}let built=await super.buildRequest(options,props);if(built.req.headers.has("api-key"))built.req.redirect="manual";return built}async fetchWithAuth(url,init,timeout,controller,schemes){if(new Headers(init.headers).has("api-key"))init.redirect="manual";return super.fetchWithAuth(url,init,timeout,controller,schemes)}async authHeaders(opts,schemes){let security=schemes??{bearerAuth:!0,adminAPIKeyAuth:!0};if(security.bearerAuth&&typeof this._options.apiKey==="string")return buildHeaders([{"api-key":this.apiKey}]);return super.authHeaders(opts,security)}};_deployments_endpoints=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"])});function deriveBedrockBaseURL(awsRegion){let region=awsRegion?.trim();if(!region)throw new OpenAIError("Must provide one of the `baseURL` or `awsRegion` arguments, or set the `AWS_BEDROCK_BASE_URL`, `AWS_REGION`, or `AWS_DEFAULT_REGION` environment variable.");if(!/^[a-z]{2,8}(?:-[a-z0-9]+)+-\d+$/u.test(region))throw new OpenAIError("The Bedrock AWS `region` is invalid. Use a standard AWS region such as `us-east-1`.");return`https://bedrock-mantle.${region}.api.aws/openai/v1`}function normalizeBedrockBaseURL(baseURL){let url=new URL(baseURL),responsesMatch=url.pathname.match(/\/responses(?:\/.*)?$/);if(responsesMatch?.index!==void 0)url.pathname=url.pathname.slice(0,responsesMatch.index)||"/";return url.toString().replace(/\/$/,"")}function addBedrockOutputText(response){if(!Object.getOwnPropertyDescriptor(response,"output_text"))addOutputText(response);return response}function restoreBedrockStreamOutputText(responses){let stream=responses.stream.bind(responses);return responses.stream=(body,options)=>{let responseStream=stream(body,options),finalResponse=responseStream.finalResponse.bind(responseStream);return responseStream.finalResponse=async()=>addBedrockOutputText(await finalResponse()),responseStream},responses}var _a4,BedrockOpenAI;var init_bedrock2=__esm(()=>{init_error2();init_client();init_realtime_credentials();init_data_residency();init_bedrock();init_headers();init_utils2();init_ResponsesParser();init_resources();BedrockOpenAI=class BedrockOpenAI extends OpenAI{constructor({baseURL=readEnv("AWS_BEDROCK_BASE_URL"),apiKey,awsRegion=readEnv("AWS_REGION")??readEnv("AWS_DEFAULT_REGION"),bedrockTokenProvider,adminAPIKey,workloadIdentity,x509Transport,dataResidency,...opts}={}){if(assertNoDataResidency(dataResidency,"BedrockOpenAI"),adminAPIKey||workloadIdentity||x509Transport)throw new OpenAIError("BedrockOpenAI only supports Bedrock bearer token authentication.");if(apiKey===void 0&&!bedrockTokenProvider)apiKey=readEnv("AWS_BEARER_TOKEN_BEDROCK")??null;if(typeof apiKey==="function")throw new OpenAIError("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(apiKey&&bedrockTokenProvider)throw new OpenAIError("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!apiKey&&!bedrockTokenProvider)throw new OpenAIError("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");let configuredBaseURL=baseURL?.trim()?baseURL:deriveBedrockBaseURL(awsRegion);super({apiKey:bedrockTokenProvider??apiKey,adminAPIKey:null,baseURL:normalizeBedrockBaseURL(configuredBaseURL),...opts});this[_a4]=!0;let currentApiKey=this.apiKey;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,get(){if(currentApiKey!==null)assertValidBedrockBearerCredential(currentApiKey);return currentApiKey},set(nextApiKey){currentApiKey=nextApiKey}});let trustedBaseURL=this.baseURL,currentBaseURL=trustedBaseURL;Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!1,get(){return currentBaseURL},set(nextBaseURL){assertBedrockRequestOrigin(trustedBaseURL,nextBaseURL),currentBaseURL=nextBaseURL}}),this.bedrockTokenProvider=bedrockTokenProvider,this.responses=restoreBedrockStreamOutputText(new Responses2(this))}async prepareOptions(options){let configuredBaseURL=this._options.baseURL??this.baseURL;assertBedrockRequestOrigin(configuredBaseURL,this.buildURL(options.path,null,options.defaultBaseURL)),await super.prepareOptions(options),assertBedrockRequestOrigin(configuredBaseURL,this.buildURL(options.path,null,options.defaultBaseURL))}async prepareRequest(request,context){assertBedrockRequestOrigin(this._options.baseURL??this.baseURL,context.url),await super.prepareRequest(request,context),assertBedrockRequestOrigin(this._options.baseURL??this.baseURL,this.buildURL(context.options.path,null,context.options.defaultBaseURL)),request.redirect="manual"}async authHeaders(opts,schemes){let security=schemes??{bearerAuth:!0,adminAPIKeyAuth:!0};if(security.bearerAuth||security.adminAPIKeyAuth){assertBedrockRequestOrigin(this._options.baseURL??this.baseURL,this.buildURL(opts.path,null,opts.defaultBaseURL));let{apiKey:credential}=await resolveRealtimeAPIKey(this);if(assertBedrockRequestOrigin(this._options.baseURL??this.baseURL,this.buildURL(opts.path,null,opts.defaultBaseURL)),credential===null)return;assertValidBedrockBearerCredential(credential);try{return buildHeaders([{Authorization:`Bearer ${credential}`}])}catch(error){if(error instanceof TypeError)throw TypeError("Bedrock bearer credential contains an invalid HTTP header value.");throw error}}return super.authHeaders(opts,security)}withOptions(options){let bedrockTokenProvider=options.apiKey===void 0?options.bedrockTokenProvider??this.bedrockTokenProvider:void 0;return super.withOptions({...options,...bedrockTokenProvider?{apiKey:void 0,bedrockTokenProvider}:{}})}};_a4=brand_privateBedrockClient});var exports_openai={};__export(exports_openai,{APIConnectionError:()=>APIConnectionError,APIConnectionTimeoutError:()=>APIConnectionTimeoutError,APIError:()=>APIError,APIPromise:()=>APIPromise,APIUserAbortError:()=>APIUserAbortError,AuthenticationError:()=>AuthenticationError,AzureOpenAI:()=>AzureOpenAI,BadRequestError:()=>BadRequestError,BedrockOpenAI:()=>BedrockOpenAI,ComputerToolset:()=>ComputerToolset,ConflictError:()=>ConflictError,InternalServerError:()=>InternalServerError,InvalidWebhookSignatureError:()=>InvalidWebhookSignatureError,NotFoundError:()=>NotFoundError,OAuthError:()=>OAuthError,OpenAI:()=>OpenAI,OpenAIError:()=>OpenAIError,PagePromise:()=>PagePromise,PermissionDeniedError:()=>PermissionDeniedError,RateLimitError:()=>RateLimitError,SubjectTokenProviderError:()=>SubjectTokenProviderError,UnprocessableEntityError:()=>UnprocessableEntityError,default:()=>OpenAI,toFile:()=>toFile,toStreamingFile:()=>toStreamingFile});var init_openai=__esm(()=>{init_client();init_uploads2();init_api_promise();init_client();init_pagination();init_computer();init_error();init_azure();init_bedrock2()});import{mkdirSync}from"fs";import{tmpdir}from"os";import{join}from"path";import{Elysia as Elysia2}from"elysia";import{Elysia}from"elysia";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
32
+ `);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}},BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};var CONTEXT_PROVIDER_TYPE="context",REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function registerContextProvider(provider,hostServices){if(!provider||typeof provider.name!=="string"||provider.name.length===0)throw Error("ContextProvider.name is required");if(typeof provider.getContext!=="function")throw Error("ContextProvider.getContext must be a function");getRegistry().set(provider.name,provider),hostServices?.serviceRegistry?.registerProvider?.(CONTEXT_PROVIDER_TYPE,provider,provider.name)}function listContextProviders(){return Array.from(getRegistry().values())}function getContextProvider(name){return getRegistry().get(name)}var ProviderRegistry=class{constructor(hostServices){this.hostServices=hostServices}hostServices;registerContextProvider(provider){registerContextProvider(provider,this.hostServices)}listContextProviders(){return listContextProviders()}getContextProvider(name){return getContextProvider(name)}getServiceRegistry(){return this.hostServices?.serviceRegistry}registerProvider(type,name,provider){this.hostServices?.serviceRegistry?.registerProvider?.(type,provider,name)}getProvider(type,name){let reg=this.hostServices?.serviceRegistry;if(!reg)return;if(name===void 0)return reg.getProvider?.(type);if(reg.getProviderByName)return reg.getProviderByName(type,name);if(!reg.listProvidersForType)return;if(!(reg.listProvidersForType(type)??[]).some((entry)=>typeof entry==="string"?entry===name:entry.pluginName===name))return;return reg.getProvider?.(type)}listProviders(type){return(this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]).map((entry)=>typeof entry==="string"?entry:entry.pluginName)}withCliContribution(contribution){let contributors=this.hostServices?.cliContributors;if(!contributors)return;for(let section of contribution.statusSections??[])contributors.addStatusSection?.(section);for(let check of contribution.doctorChecks??[])contributors.addDoctorCheck?.(check)}};var PROVIDER_NAME="codex",CLI_COMMAND="codex";function platformExeName(base){return process.platform==="win32"?`${base}.exe`:base}function resolveCliBin(){let found=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(CLI_COMMAND,{PATH:process.env.PATH}):null;if(found)return found;return platformExeName(CLI_COMMAND)}var CLI_BIN=resolveCliBin(),DISPLAY_NAME="OpenAI Codex",DEFAULT_MODEL="gpt-4.1-mini",DEFAULT_MAX_TOKENS=16384,API_PREFIX=`/api/ai-${PROVIDER_NAME}`,SUPPORTED_MODES=["sdk","cli"],CLI_NPM_PACKAGE="@openai/codex",CODEX_MODELS=[{id:"codex-mini-latest",name:"Codex Mini",provider:PROVIDER_NAME,contextWindow:200000,maxOutputTokens:1e5,supportsVision:!1,supportsStreaming:!0,inputPricePerMToken:1.5,outputPricePerMToken:6},{id:"gpt-4.1",name:"GPT-4.1",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:2,outputPricePerMToken:8},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:0.4,outputPricePerMToken:1.6},{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:0.1,outputPricePerMToken:0.4},{id:"o4-mini",name:"o4-mini",provider:PROVIDER_NAME,contextWindow:200000,maxOutputTokens:1e5,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:1.1,outputPricePerMToken:4.4}];class CodexSdkAdapter{mode="sdk";client=null;resolveApiKey;constructor(resolveApiKey){this.resolveApiKey=resolveApiKey}async getClient(){if(this.client)return this.client;let apiKey=(await this.resolveApiKey())?.trim();if(!apiKey)throw Error("OPENAI_API_KEY is required for SDK mode. Set it in the AI provider credentials (stored in the agent config) or export it in the agent environment.");let OpenAI;try{let mod=await Promise.resolve().then(() => (init_openai(),exports_openai));OpenAI=mod.default??mod}catch{throw Error("Failed to load openai SDK. Install it with: bun add openai")}return this.client=new OpenAI({apiKey}),this.client}async sendPrompt(prompt,config,_signal){let client=await this.getClient(),startTime=Date.now(),params={model:config.model||DEFAULT_MODEL,input:prompt};if(config.systemPrompt)params.instructions=config.systemPrompt;if(config.maxTokens)params.max_output_tokens=config.maxTokens;let response=await client.responses.create(params),durationMs=Date.now()-startTime;return{content:this.extractResponseText(response),model:response.model,inputTokens:response.usage.input_tokens,outputTokens:response.usage.output_tokens,durationMs,metadata:{provider:PROVIDER_NAME,mode:"sdk"}}}async streamPrompt(prompt,config,onChunk,_signal){let client=await this.getClient(),startTime=Date.now(),model=config.model||DEFAULT_MODEL,params={model,input:prompt,stream:!0};if(config.systemPrompt)params.instructions=config.systemPrompt;if(config.maxTokens)params.max_output_tokens=config.maxTokens;let stream=await client.responses.create(params),collectedText=[],finalModel=model,inputTokens=0,outputTokens=0;for await(let event of stream)if(event.type==="response.output_text.delta"&&event.delta)collectedText.push(event.delta),onChunk({type:"text",content:event.delta});else if(event.type==="response.completed"){let completed=event;if(completed.response)finalModel=completed.response.model,inputTokens=completed.response.usage.input_tokens,outputTokens=completed.response.usage.output_tokens}let durationMs=Date.now()-startTime,content=collectedText.join("");if(inputTokens===0&&outputTokens===0)inputTokens=Math.ceil(prompt.length/4),outputTokens=Math.ceil(content.length/4);return onChunk({type:"done",content:""}),{content,model:finalModel,inputTokens,outputTokens,durationMs,metadata:{provider:PROVIDER_NAME,mode:"sdk"}}}async healthCheck(){try{return await this.getClient(),{ok:!0,message:`${DISPLAY_NAME} SDK ready (API key configured)`}}catch(err){return{ok:!1,message:err instanceof Error?err.message:"SDK initialization failed"}}}extractResponseText(response){let parts=[];for(let output of response.output)if(output.type==="message"&&output.content){for(let block of output.content)if(block.type==="output_text"&&block.text)parts.push(block.text)}return parts.join("")}}function permissionFlags(mode){switch(mode){case"plan":return["--sandbox","read-only"];case"fullAuto":return["--dangerously-bypass-approvals-and-sandbox"];case"acceptEdits":default:return["--sandbox","workspace-write"]}}class CodexCliAdapter{mode="cli";resolveApiKey;loggedInKey=null;constructor(resolveApiKey){this.resolveApiKey=resolveApiKey}codexHome(){let home=process.env.CODEX_HOME?.trim()||join(tmpdir(),"vibe-codex-home");try{mkdirSync(home,{recursive:!0})}catch{}return home}async ensureAuth(home){let apiKey=(await this.resolveApiKey())?.trim();if(!apiKey||apiKey===this.loggedInKey)return;let proc=Bun.spawn([CLI_BIN,"login","--with-api-key"],{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:{...process.env,CODEX_HOME:home},timeout:30000});proc.stdin.write(apiKey),await proc.stdin.end();let exitCode=await proc.exited;if(exitCode===0)this.loggedInKey=apiKey;else{let stderr=await new Response(proc.stderr).text();throw Error(`Codex CLI login failed (exit ${exitCode}): ${stderr.trim()}`)}}buildCliArgs(config,prompt){let args=["exec","--skip-git-repo-check","--color","never",...permissionFlags(config.permissionMode)];if(config.model)args.push("--model",config.model);return args.push(prompt),args}async spawnEnv(home){let env={...process.env,CODEX_HOME:home},apiKey=(await this.resolveApiKey())?.trim();if(apiKey)env.OPENAI_API_KEY=apiKey;return env}async sendPrompt(prompt,config){let startTime=Date.now(),args=this.buildCliArgs(config,prompt),home=this.codexHome();await this.ensureAuth(home);let proc=Bun.spawn([CLI_BIN,...args],{stdout:"pipe",stderr:"pipe",cwd:config.workingDirectory||process.cwd(),env:await this.spawnEnv(home),timeout:config.providerConfig?.timeoutMs||300000}),stdout=await new Response(proc.stdout).text(),stderr=await new Response(proc.stderr).text(),exitCode=await proc.exited,durationMs=Date.now()-startTime;if(exitCode!==0&&!stdout)throw Error(`${DISPLAY_NAME} CLI exited with code ${exitCode}: ${stderr}`);let content=stdout.trim()||stderr.trim(),inputTokens=Math.ceil(prompt.length/4),outputTokens=Math.ceil(content.length/4),model=config.model||DEFAULT_MODEL;return{content,model,inputTokens,outputTokens,durationMs,metadata:{exitCode,provider:PROVIDER_NAME,mode:"cli"}}}async streamPrompt(prompt,config,onChunk){let result=await this.sendPrompt(prompt,config);return onChunk({type:"text",content:result.content}),onChunk({type:"done",content:""}),result}async healthCheck(){try{let proc=Bun.spawnSync([CLI_BIN,"--version"],{timeout:5000,stdout:"pipe",stderr:"ignore"});if(proc.exitCode===0)return{ok:!0,message:`${DISPLAY_NAME} CLI ${proc.stdout.toString().trim()}`};return{ok:!1,message:`${DISPLAY_NAME} CLI not available (exit code ${proc.exitCode})`}}catch{return{ok:!1,message:`${DISPLAY_NAME} CLI not installed or not in PATH`}}}}class CodexProvider{name=PROVIDER_NAME;sessions=new Map;logIngester=null;hostServices=null;logger=null;activeMode=null;adapter=null;cachedApiKey;setHostServices(hs){this.hostServices=hs,this.logger=new BoundLogger(hs.logger,`${PROVIDER_NAME}-provider`);let registry=new ProviderRegistry(hs);this.logIngester=registry.getProvider("ai","log-ingester")??null,Promise.resolve(hs.getConfig?.("OPENAI_API_KEY")).then((apiKey)=>{let trimmed=apiKey?.trim();if(trimmed)this.cachedApiKey=trimmed}).catch(()=>{})}async resolveApiKey(){let envKey=process.env.OPENAI_API_KEY?.trim();if(envKey)return envKey;if(this.cachedApiKey)return this.cachedApiKey;if(this.hostServices?.getConfig)try{let apiKey=(await this.hostServices.getConfig("OPENAI_API_KEY"))?.trim();if(apiKey)return this.cachedApiKey=apiKey,apiKey}catch{return}return}getSupportedModes(){return[...SUPPORTED_MODES]}getDisplayName(){return DISPLAY_NAME}getPrereqApiPrefix(){return API_PREFIX}getMode(){if(this.activeMode)return this.activeMode;return this.detectMode()}setMode(mode){if(!SUPPORTED_MODES.includes(mode))throw Error(`${DISPLAY_NAME} does not support ${mode} mode`);this.activeMode=mode,this.adapter=null,this.log("info",`Mode explicitly set to: ${mode}`)}detectMode(){if(process.env.OPENAI_API_KEY?.trim()||this.cachedApiKey)return"sdk";try{if(Bun.which(CLI_COMMAND,{PATH:process.env.PATH}))return"cli"}catch{}return"sdk"}getAdapter(){if(this.adapter)return this.adapter;let mode=this.getMode();return this.adapter=mode==="sdk"?new CodexSdkAdapter(()=>this.resolveApiKey()):new CodexCliAdapter(()=>this.resolveApiKey()),this.activeMode=mode,this.log("info",`Adapter initialized in ${mode} mode`),this.adapter}async createSession(config){let id=config.providerConfig?.sessionId||crypto.randomUUID(),now=new Date().toISOString(),existing=this.sessions.get(id);if(existing)return existing.status="active",existing.updatedAt=now,this.toAISession(existing);let session={id,config,status:"active",stats:{inputTokens:0,outputTokens:0,requestCount:0,estimatedCostUsd:0},abortController:null,files:[],createdAt:now,updatedAt:now};return this.sessions.set(id,session),this.log("info",`Session created: ${id} (${config.name})`),this.toAISession(session)}async sendPrompt(sessionId,prompt,context){let session=this.getSession(sessionId);session.status="processing",session.updatedAt=new Date().toISOString();let abortController=new AbortController;session.abortController=abortController;let fullPrompt=this.buildFullPrompt(prompt,context,session.files);this.logIngester?.append({sessionId,type:"input",content:prompt});try{let result=await this.getAdapter().sendPrompt(fullPrompt,session.config,abortController.signal);return this.updateSessionStats(session,result.inputTokens,result.outputTokens),this.logIngester?.append({sessionId,type:"output",content:result.content,tokenCount:result.outputTokens,model:result.model,durationMs:result.durationMs}),{content:result.content,model:result.model,inputTokens:result.inputTokens,outputTokens:result.outputTokens,durationMs:result.durationMs,metadata:result.metadata}}catch(err){session.status="error",session.updatedAt=new Date().toISOString();let errorMsg=err instanceof Error?err.message:"Unknown error";throw this.logIngester?.append({sessionId,type:"error",content:errorMsg}),err}finally{session.abortController=null}}async streamPrompt(sessionId,prompt,context,onChunk){let session=this.getSession(sessionId);session.status="processing",session.updatedAt=new Date().toISOString();let abortController=new AbortController;session.abortController=abortController;let fullPrompt=this.buildFullPrompt(prompt,context,session.files);this.logIngester?.append({sessionId,type:"input",content:prompt});try{let adapter=this.getAdapter(),chunkHandler=onChunk??((_c)=>{}),result=await adapter.streamPrompt(fullPrompt,session.config,chunkHandler,abortController.signal);return this.updateSessionStats(session,result.inputTokens,result.outputTokens),this.logIngester?.append({sessionId,type:"output",content:result.content,tokenCount:result.outputTokens,model:result.model,durationMs:result.durationMs}),{content:result.content,model:result.model,inputTokens:result.inputTokens,outputTokens:result.outputTokens,durationMs:result.durationMs,metadata:result.metadata}}catch(err){session.status="error",session.updatedAt=new Date().toISOString();let errorMsg=err instanceof Error?err.message:"Unknown error";throw this.logIngester?.append({sessionId,type:"error",content:errorMsg}),err}finally{session.abortController=null}}async listModels(){return[...CODEX_MODELS]}async cancelRequest(sessionId){let session=this.sessions.get(sessionId);if(!session)throw Error(`Session ${sessionId} not found`);if(session.abortController)session.abortController.abort(),session.abortController=null,session.status="active",session.updatedAt=new Date().toISOString(),this.log("info",`Request cancelled for session: ${sessionId}`)}getCapabilities(){let mode=this.getMode();return{streaming:mode==="sdk",vision:mode==="sdk",fileAttachments:!0,toolUse:!1,mcpSupport:!1,voiceMode:!1,cancelSupport:mode==="sdk",modelListing:!0}}async attachFiles(sessionId,files){let session=this.getSession(sessionId);session.files.push(...files),session.updatedAt=new Date().toISOString(),this.log("debug",`Attached ${files.length} file(s) to session ${sessionId}`)}async getSessionLogs(_sessionId,_filter){return[]}async getUsageStats(sessionId){return this.sessions.get(sessionId)?.stats??{inputTokens:0,outputTokens:0,requestCount:0,estimatedCostUsd:0}}async configureSession(sessionId,config){let session=this.getSession(sessionId);Object.assign(session.config,config),session.updatedAt=new Date().toISOString()}async destroySession(sessionId){let session=this.sessions.get(sessionId);if(session){if(session.abortController)session.abortController.abort(),session.abortController=null;session.status="terminated",session.files=[],session.updatedAt=new Date().toISOString(),this.log("info",`Session terminated: ${sessionId}`)}}async listSessions(){return Array.from(this.sessions.values()).map((s)=>this.toAISession(s))}async getSessionStatus(sessionId){return this.sessions.get(sessionId)?.status??"terminated"}async healthCheck(){return this.getAdapter().healthCheck()}getCliLaunchSpec(){let env={},apiKey=process.env.OPENAI_API_KEY?.trim()||this.cachedApiKey;if(apiKey)env.OPENAI_API_KEY=apiKey;return{binary:CLI_COMMAND,env}}async sdkOneShot(opts){let adapter=new CodexSdkAdapter(()=>this.resolveApiKey()),config={name:"vibe-ai-sdk",agentType:PROVIDER_NAME,model:opts.model??DEFAULT_MODEL,maxTokens:opts.maxTokens??DEFAULT_MAX_TOKENS,providerConfig:opts.extras},result=await adapter.sendPrompt(opts.prompt,config);return{text:result.content,usage:{inputTokens:result.inputTokens,outputTokens:result.outputTokens,model:result.model,durationMs:result.durationMs}}}getSession(sessionId){let session=this.sessions.get(sessionId);if(!session)throw Error(`Session ${sessionId} not found`);if(session.status==="terminated")throw Error("Session is terminated");return session}buildFullPrompt(prompt,context,files){let fullPrompt=prompt;if(context&&context.length>0){let contextStr=context.map((c)=>`--- Context (${c.type}): ---
22
33
  ${c.content}`).join(`
23
34
 
24
35
  `);fullPrompt=`${prompt}
@@ -28,4 +39,4 @@ ${textContent}`}).join(`
28
39
 
29
40
  `);fullPrompt=`${fullPrompt}
30
41
 
31
- ${fileStr}`}return fullPrompt}updateSessionStats(session,inputTokens,outputTokens){let model=session.config.model||DEFAULT_MODEL,modelInfo=CODEX_MODELS.find((m)=>m.id===model);if(session.stats.inputTokens+=inputTokens,session.stats.outputTokens+=outputTokens,session.stats.requestCount+=1,modelInfo){let cost=inputTokens/1e6*modelInfo.inputPricePerMToken+outputTokens/1e6*modelInfo.outputPricePerMToken;session.stats.estimatedCostUsd+=cost}if(!session.stats.modelBreakdown)session.stats.modelBreakdown={};let breakdown=session.stats.modelBreakdown[model]??{inputTokens:0,outputTokens:0,requestCount:0};breakdown.inputTokens+=inputTokens,breakdown.outputTokens+=outputTokens,breakdown.requestCount+=1,session.stats.modelBreakdown[model]=breakdown,session.status="active",session.updatedAt=new Date().toISOString()}toAISession(s){return{id:s.id,name:s.config.name,status:s.status,agentType:s.config.agentType,provider:PROVIDER_NAME,config:s.config,stats:s.stats,createdAt:s.createdAt,updatedAt:s.updatedAt}}log(level,msg){this.logger?.[level](msg)}}function getCliVersion(){try{let proc=Bun.spawnSync([CLI_BIN,"--version"],{timeout:5000,stdout:"pipe",stderr:"ignore"});if(proc.exitCode===0)return proc.stdout.toString().trim()}catch{}return null}function installGlobalNpmCli(pkgSpec){let candidates=[["bun","install","-g",pkgSpec],["npm","install","-g",pkgSpec]],lastError="";for(let cmd of candidates){let exe=cmd[0];if(!Bun.which(exe,{PATH:process.env.PATH}))continue;try{let proc=Bun.spawnSync(cmd,{timeout:180000,stdout:"pipe",stderr:"pipe"});if(proc.exitCode===0)return{ok:!0,message:cmd.join(" ")};lastError=proc.stderr.toString().trim()||`${exe} exited ${proc.exitCode}`}catch(err){lastError=err instanceof Error?err.message:String(err)}}return{ok:!1,message:lastError||`No global installer (bun/npm) found. Run manually: bun install -g ${pkgSpec}`}}function createPrereqsRoutes(){return new Elysia2({prefix:"/prereqs"}).get("/status",()=>{let version=getCliVersion();return{satisfied:Boolean(version),missing:version?[]:[{name:CLI_COMMAND,kind:"npm",requiresSudo:!1,description:`${DISPLAY_NAME} CLI for CLI mode`}]}}).post("/install",()=>{if(getCliVersion())return{ok:!0,installed:[CLI_COMMAND],pendingSudo:[],errors:[]};let result=installGlobalNpmCli(CLI_NPM_PACKAGE);if(result.ok)return{ok:!0,installed:[CLI_COMMAND],pendingSudo:[],errors:[]};return{ok:!1,installed:[],pendingSudo:[],errors:[{name:CLI_COMMAND,message:result.message}]}})}var PLUGIN_NAME="codex",PLUGIN_VERSION="1.0.0",provider=new CodexProvider,lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"ai.provider.ready",onInit:(hostServices)=>{provider.setHostServices(hostServices),new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emit("ai.provider.ready",{provider:PLUGIN_NAME})},onShutdown:()=>{for(let[id]of provider.sessions)provider.destroySession(id).catch(()=>{})}}),createPlugin=(_ctx)=>({capabilities:{secrets:"read",subprocess:!0,gateway:!1,telemetry:!0},name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"OpenAI Codex AI agent provider for VibeControls (dual-mode: SDK + CLI)",tags:["provider","integration"],apiPrefix:API_PREFIX,prerequisites:[{name:CLI_COMMAND,kind:"npm",requiresSudo:!1}],providers:{ai:provider},createRoutes:()=>createPrereqsRoutes(),onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop});export{permissionFlags,createPlugin};
42
+ ${fileStr}`}return fullPrompt}updateSessionStats(session,inputTokens,outputTokens){let model=session.config.model||DEFAULT_MODEL,modelInfo=CODEX_MODELS.find((m)=>m.id===model);if(session.stats.inputTokens+=inputTokens,session.stats.outputTokens+=outputTokens,session.stats.requestCount+=1,modelInfo){let cost=inputTokens/1e6*modelInfo.inputPricePerMToken+outputTokens/1e6*modelInfo.outputPricePerMToken;session.stats.estimatedCostUsd+=cost}if(!session.stats.modelBreakdown)session.stats.modelBreakdown={};let breakdown=session.stats.modelBreakdown[model]??{inputTokens:0,outputTokens:0,requestCount:0};breakdown.inputTokens+=inputTokens,breakdown.outputTokens+=outputTokens,breakdown.requestCount+=1,session.stats.modelBreakdown[model]=breakdown,session.status="active",session.updatedAt=new Date().toISOString()}toAISession(s){return{id:s.id,name:s.config.name,status:s.status,agentType:s.config.agentType,provider:PROVIDER_NAME,config:s.config,stats:s.stats,createdAt:s.createdAt,updatedAt:s.updatedAt}}log(level,msg){this.logger?.[level](msg)}}function getCliVersion(){try{let proc=Bun.spawnSync([CLI_BIN,"--version"],{timeout:5000,stdout:"pipe",stderr:"ignore"});if(proc.exitCode===0)return proc.stdout.toString().trim()}catch{}return null}function installGlobalNpmCli(pkgSpec){let candidates=[["bun","install","-g",pkgSpec],["npm","install","-g",pkgSpec]],lastError="";for(let cmd of candidates){let exe=cmd[0];if(!Bun.which(exe,{PATH:process.env.PATH}))continue;try{let proc=Bun.spawnSync(cmd,{timeout:180000,stdout:"pipe",stderr:"pipe"});if(proc.exitCode===0)return{ok:!0,message:cmd.join(" ")};lastError=proc.stderr.toString().trim()||`${exe} exited ${proc.exitCode}`}catch(err){lastError=err instanceof Error?err.message:String(err)}}return{ok:!1,message:lastError||`No global installer (bun/npm) found. Run manually: bun install -g ${pkgSpec}`}}function createPrereqsRoutes(){return new Elysia2({prefix:"/prereqs"}).get("/status",()=>{let version=getCliVersion();return{satisfied:Boolean(version),missing:version?[]:[{name:CLI_COMMAND,kind:"npm",requiresSudo:!1,description:`${DISPLAY_NAME} CLI for CLI mode`}]}}).post("/install",()=>{if(getCliVersion())return{ok:!0,installed:[CLI_COMMAND],pendingSudo:[],errors:[]};let result=installGlobalNpmCli(CLI_NPM_PACKAGE);if(result.ok)return{ok:!0,installed:[CLI_COMMAND],pendingSudo:[],errors:[]};return{ok:!1,installed:[],pendingSudo:[],errors:[{name:CLI_COMMAND,message:result.message}]}})}var PLUGIN_NAME="codex",PLUGIN_VERSION="1.0.0",provider=new CodexProvider,lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"ai.provider.ready",onInit:(hostServices)=>{provider.setHostServices(hostServices),new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emit("ai.provider.ready",{provider:PLUGIN_NAME})},onShutdown:()=>{for(let[id]of provider.sessions)provider.destroySession(id).catch(()=>{})}}),createPlugin=(_ctx)=>({capabilities:{secrets:"read",subprocess:!0,gateway:!1,telemetry:!0},name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"OpenAI Codex AI agent provider for VibeControls (dual-mode: SDK + CLI)",tags:["provider","integration"],apiPrefix:API_PREFIX,prerequisites:[{name:CLI_COMMAND,kind:"npm",requiresSudo:!1}],providers:{ai:provider},createRoutes:()=>createPrereqsRoutes(),onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop});export{createPlugin,permissionFlags};