@copilotkit/voice 1.51.3-next.7 → 1.51.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @copilotkit/voice
2
2
 
3
+ ## 1.51.3
4
+
5
+ ### Patch Changes
6
+
7
+ - d36fc1e: Add UMD export
8
+ - Updated dependencies [d36fc1e]
9
+ - @copilotkitnext/runtime@1.51.3
10
+
11
+ ## 1.51.3-next.8
12
+
13
+ ### Patch Changes
14
+
15
+ - d36fc1e: Add UMD export
16
+ - Updated dependencies [d36fc1e]
17
+ - @copilotkitnext/runtime@1.51.3-next.8
18
+
3
19
  ## 1.51.3-next.7
4
20
 
5
21
  ### Patch Changes
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CopilotKitVoice={})}(this,function(e){"use strict";var t,s;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},e.getValidEnumValues=t=>{const s=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of s)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(const s of e)if(t(s))return s},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t||(t={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const n=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),r=e=>{switch(typeof e){case"undefined":return n.undefined;case"string":return n.string;case"number":return Number.isNaN(e)?n.nan:n.number;case"boolean":return n.boolean;case"function":return n.function;case"bigint":return n.bigint;case"symbol":return n.symbol;case"object":return Array.isArray(e)?n.array:null===e?n.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?n.promise:"undefined"!=typeof Map&&e instanceof Map?n.map:"undefined"!=typeof Set&&e instanceof Set?n.set:"undefined"!=typeof Date&&e instanceof Date?n.date:n.object;default:return n.unknown}},a=t.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class i extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},n=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(n);else if("invalid_return_type"===r.code)n(r.returnTypeError);else if("invalid_arguments"===r.code)n(r.argumentsError);else if(0===r.path.length)s._errors.push(t(r));else{let e=s,n=0;for(;n<r.path.length;){const s=r.path[n];n===r.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(r))):e[s]=e[s]||{_errors:[]},e=e[s],n++}}};return n(this),s}static assert(e){if(!(e instanceof i))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];t[s]=t[s]||[],t[s].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}i.create=e=>new i(e);const o=(e,s)=>{let r;switch(e.code){case a.invalid_type:r=e.received===n.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case a.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case a.unrecognized_keys:r=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case a.invalid_union:r="Invalid input";break;case a.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case a.invalid_enum_value:r=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case a.invalid_arguments:r="Invalid function arguments";break;case a.invalid_return_type:r="Invalid function return type";break;case a.invalid_date:r="Invalid date";break;case a.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case a.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case a.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case a.custom:r="Invalid input";break;case a.invalid_intersection_types:r="Intersection results could not be merged";break;case a.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case a.not_finite:r="Number must be finite";break;default:r=s.defaultError,t.assertNever(e)}return{message:r}};let c=o;function l(e,t){const s=c,n=(e=>{const{data:t,path:s,errorMaps:n,issueData:r}=e,a=[...s,...r.path||[]],i={...r,path:a};if(void 0!==r.message)return{...r,path:a,message:r.message};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...r,path:a,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===o?void 0:o].filter(e=>!!e)});e.common.issues.push(n)}class u{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if("aborted"===n.status)return d;"dirty"===n.status&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const e of t){const t=await e.key,n=await e.value;s.push({key:t,value:n})}return u.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:t,value:r}=n;if("aborted"===t.status)return d;if("aborted"===r.status)return d;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!n.alwaysSet||(s[t.value]=r.value)}return{status:e.value,value:s}}}const d=Object.freeze({status:"aborted"}),h=e=>({status:"dirty",value:e}),p=e=>({status:"valid",value:e}),f=e=>"aborted"===e.status,m=e=>"dirty"===e.status,g=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;var y;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(y||(y={}));class v{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const w=(e,t)=>{if(g(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new i(e.common.issues);return this._error=t,this._error}}};function b(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:n,description:r}=e;if(t&&(s||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(t,r)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??r.defaultError}:void 0===r.data?{message:a??n??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:a??s??r.defaultError}},description:r}}class x{get description(){return this._def.description}_getType(e){return r(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new u,ctx:{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},n=this._parseSync({data:e,path:s.path,parent:s});return w(s,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return g(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>g(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(_(n)?n:Promise.resolve(n));return w(s,a)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const r=e(t),i=()=>n.addIssue({code:a.custom,...s(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(i(),!1)):!!r||(i(),!1)})}refinement(e,t){return this._refinement((s,n)=>!!e(s)||(n.addIssue("function"==typeof t?t(s,n):t),!1))}_refinement(e){return new Se({schema:this,typeName:$e.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Te.create(this,this._def)}nullable(){return Ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ae.create(this)}promise(){return xe.create(this,this._def)}or(e){return ce.create([this,e],this._def)}and(e){return he.create(this,e,this._def)}transform(e){return new Se({...b(this._def),schema:this,typeName:$e.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ke({...b(this._def),innerType:this,defaultValue:t,typeName:$e.ZodDefault})}brand(){return new Ee({typeName:$e.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Oe({...b(this._def),innerType:this,catchValue:t,typeName:$e.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ne.create(this,e)}readonly(){return Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const S=/^c[^\s-]{8,}$/i,T=/^[0-9a-z]+$/,A=/^[0-9A-HJKMNP-TV-Z]{26}$/i,k=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,O=/^[a-z0-9_-]{21}$/i,I=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,E=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,N=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let R;const $=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,C=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,L=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,P=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,j=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,M=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,D="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",F=new RegExp(`^${D}$`);function Z(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function U(e){return new RegExp(`^${Z(e)}$`)}function B(e){let t=`${D}T${Z(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function q(e,t){return!("v4"!==t&&t||!$.test(e))||!("v6"!==t&&t||!L.test(e))}function W(e,t){if(!I.test(e))return!1;try{const[s]=e.split(".");if(!s)return!1;const n=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),r=JSON.parse(atob(n));return"object"==typeof r&&null!==r&&((!("typ"in r)||"JWT"===r?.typ)&&(!!r.alg&&(!t||r.alg===t)))}catch{return!1}}function H(e,t){return!("v4"!==t&&t||!C.test(e))||!("v6"!==t&&t||!P.test(e))}class K extends x{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==n.string){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.string,received:t.parsedType}),d}const s=new u;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),l(r,{code:a.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),s.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),l(r,{code:a.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),s.dirty());else if("length"===n.kind){const t=e.data.length>n.value,i=e.data.length<n.value;(t||i)&&(r=this._getOrReturnCtx(e,r),t?l(r,{code:a.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&l(r,{code:a.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),s.dirty())}else if("email"===n.kind)N.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"email",code:a.invalid_string,message:n.message}),s.dirty());else if("emoji"===n.kind)R||(R=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),R.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"emoji",code:a.invalid_string,message:n.message}),s.dirty());else if("uuid"===n.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"uuid",code:a.invalid_string,message:n.message}),s.dirty());else if("nanoid"===n.kind)O.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"nanoid",code:a.invalid_string,message:n.message}),s.dirty());else if("cuid"===n.kind)S.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"cuid",code:a.invalid_string,message:n.message}),s.dirty());else if("cuid2"===n.kind)T.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"cuid2",code:a.invalid_string,message:n.message}),s.dirty());else if("ulid"===n.kind)A.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"ulid",code:a.invalid_string,message:n.message}),s.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),l(r,{validation:"url",code:a.invalid_string,message:n.message}),s.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"regex",code:a.invalid_string,message:n.message}),s.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),l(r,{code:a.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),s.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),l(r,{code:a.invalid_string,validation:{startsWith:n.value},message:n.message}),s.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),l(r,{code:a.invalid_string,validation:{endsWith:n.value},message:n.message}),s.dirty());else if("datetime"===n.kind){B(n).test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:a.invalid_string,validation:"datetime",message:n.message}),s.dirty())}else if("date"===n.kind){F.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:a.invalid_string,validation:"date",message:n.message}),s.dirty())}else if("time"===n.kind){U(n).test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:a.invalid_string,validation:"time",message:n.message}),s.dirty())}else"duration"===n.kind?E.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"duration",code:a.invalid_string,message:n.message}),s.dirty()):"ip"===n.kind?q(e.data,n.version)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"ip",code:a.invalid_string,message:n.message}),s.dirty()):"jwt"===n.kind?W(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"jwt",code:a.invalid_string,message:n.message}),s.dirty()):"cidr"===n.kind?H(e.data,n.version)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"cidr",code:a.invalid_string,message:n.message}),s.dirty()):"base64"===n.kind?j.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"base64",code:a.invalid_string,message:n.message}),s.dirty()):"base64url"===n.kind?M.test(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{validation:"base64url",code:a.invalid_string,message:n.message}),s.dirty()):t.assertNever(n);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:a.invalid_string,...y.errToObj(s)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...y.errToObj(e)})}url(e){return this._addCheck({kind:"url",...y.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...y.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...y.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...y.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...y.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...y.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...y.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...y.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...y.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...y.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...y.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...y.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...y.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...y.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...y.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...y.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...y.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...y.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...y.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...y.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...y.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...y.errToObj(t)})}nonempty(e){return this.min(1,y.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function V(e,t){const s=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,r=s>n?s:n;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}K.create=e=>new K({checks:[],typeName:$e.ZodString,coerce:e?.coerce??!1,...b(e)});class X extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==n.number){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.number,received:t.parsedType}),d}let s;const r=new u;for(const n of this._def.checks)if("int"===n.kind)t.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:a.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:a.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:a.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==V(e.data,n.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:a.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:a.not_finite,message:n.message}),r.dirty()):t.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,y.toString(t))}setLimit(e,t,s,n){return new X({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:y.toString(n)}]})}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:y.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:y.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:y.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}X.create=e=>new X({checks:[],typeName:$e.ZodNumber,coerce:e?.coerce||!1,...b(e)});class z extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==n.bigint)return this._getInvalidInput(e);let s;const r=new u;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:a.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:a.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),l(s,{code:a.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):t.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.bigint,received:t.parsedType}),d}gte(e,t){return this.setLimit("min",e,!0,y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,y.toString(t))}setLimit(e,t,s,n){return new z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:y.toString(n)}]})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:y.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}z.create=e=>new z({checks:[],typeName:$e.ZodBigInt,coerce:e?.coerce??!1,...b(e)});class J extends x{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==n.boolean){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.boolean,received:t.parsedType}),d}return p(e.data)}}J.create=e=>new J({typeName:$e.ZodBoolean,coerce:e?.coerce||!1,...b(e)});class G extends x{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==n.date){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.date,received:t.parsedType}),d}if(Number.isNaN(e.data.getTime())){return l(this._getOrReturnCtx(e),{code:a.invalid_date}),d}const s=new u;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),l(r,{code:a.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),s.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),l(r,{code:a.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),s.dirty()):t.assertNever(n);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:y.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:y.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}G.create=e=>new G({checks:[],coerce:e?.coerce||!1,typeName:$e.ZodDate,...b(e)});class Y extends x{_parse(e){if(this._getType(e)!==n.symbol){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.symbol,received:t.parsedType}),d}return p(e.data)}}Y.create=e=>new Y({typeName:$e.ZodSymbol,...b(e)});class Q extends x{_parse(e){if(this._getType(e)!==n.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.undefined,received:t.parsedType}),d}return p(e.data)}}Q.create=e=>new Q({typeName:$e.ZodUndefined,...b(e)});class ee extends x{_parse(e){if(this._getType(e)!==n.null){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.null,received:t.parsedType}),d}return p(e.data)}}ee.create=e=>new ee({typeName:$e.ZodNull,...b(e)});class te extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return p(e.data)}}te.create=e=>new te({typeName:$e.ZodAny,...b(e)});class se extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return p(e.data)}}se.create=e=>new se({typeName:$e.ZodUnknown,...b(e)});class ne extends x{_parse(e){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.never,received:t.parsedType}),d}}ne.create=e=>new ne({typeName:$e.ZodNever,...b(e)});class re extends x{_parse(e){if(this._getType(e)!==n.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.void,received:t.parsedType}),d}return p(e.data)}}re.create=e=>new re({typeName:$e.ZodVoid,...b(e)});class ae extends x{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==n.array)return l(t,{code:a.invalid_type,expected:n.array,received:t.parsedType}),d;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,n=t.data.length<r.exactLength.value;(e||n)&&(l(t,{code:e?a.too_big:a.too_small,minimum:n?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(l(t,{code:a.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(l(t,{code:a.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>r.type._parseAsync(new v(t,e,t.path,s)))).then(e=>u.mergeArray(s,e));const i=[...t.data].map((e,s)=>r.type._parseSync(new v(t,e,t.path,s)));return u.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new ae({...this._def,minLength:{value:e,message:y.toString(t)}})}max(e,t){return new ae({...this._def,maxLength:{value:e,message:y.toString(t)}})}length(e,t){return new ae({...this._def,exactLength:{value:e,message:y.toString(t)}})}nonempty(e){return this.min(1,e)}}function ie(e){if(e instanceof oe){const t={};for(const s in e.shape){const n=e.shape[s];t[s]=Te.create(ie(n))}return new oe({...e._def,shape:()=>t})}return e instanceof ae?new ae({...e._def,type:ie(e.element)}):e instanceof Te?Te.create(ie(e.unwrap())):e instanceof Ae?Ae.create(ie(e.unwrap())):e instanceof pe?pe.create(e.items.map(e=>ie(e))):e}ae.create=(e,t)=>new ae({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$e.ZodArray,...b(t)});class oe extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),s=t.objectKeys(e);return this._cached={shape:e,keys:s},this._cached}_parse(e){if(this._getType(e)!==n.object){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.object,received:t.parsedType}),d}const{status:t,ctx:s}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ne&&"strip"===this._def.unknownKeys))for(const e in s.data)i.includes(e)||o.push(e);const c=[];for(const e of i){const t=r[e],n=s.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new v(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ne){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)c.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)o.length>0&&(l(s,{code:a.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const n=s.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new v(s,n,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const s=await t.key,n=await t.value;e.push({key:s,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>u.mergeObjectSync(t,e)):u.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return y.errToObj,new oe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,s)=>{const n=this._def.errorMap?.(t,s).message??s.defaultError;return"unrecognized_keys"===t.code?{message:y.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new oe({...this._def,unknownKeys:"strip"})}passthrough(){return new oe({...this._def,unknownKeys:"passthrough"})}extend(e){return new oe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new oe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:$e.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new oe({...this._def,catchall:e})}pick(e){const s={};for(const n of t.objectKeys(e))e[n]&&this.shape[n]&&(s[n]=this.shape[n]);return new oe({...this._def,shape:()=>s})}omit(e){const s={};for(const n of t.objectKeys(this.shape))e[n]||(s[n]=this.shape[n]);return new oe({...this._def,shape:()=>s})}deepPartial(){return ie(this)}partial(e){const s={};for(const n of t.objectKeys(this.shape)){const t=this.shape[n];e&&!e[n]?s[n]=t:s[n]=t.optional()}return new oe({...this._def,shape:()=>s})}required(e){const s={};for(const n of t.objectKeys(this.shape))if(e&&!e[n])s[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof Te;)e=e._def.innerType;s[n]=e}return new oe({...this._def,shape:()=>s})}keyof(){return ve(t.objectKeys(this.shape))}}oe.create=(e,t)=>new oe({shape:()=>e,unknownKeys:"strip",catchall:ne.create(),typeName:$e.ZodObject,...b(t)}),oe.strictCreate=(e,t)=>new oe({shape:()=>e,unknownKeys:"strict",catchall:ne.create(),typeName:$e.ZodObject,...b(t)}),oe.lazycreate=(e,t)=>new oe({shape:e,unknownKeys:"strip",catchall:ne.create(),typeName:$e.ZodObject,...b(t)});class ce extends x{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map(async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map(e=>new i(e.ctx.common.issues));return l(t,{code:a.invalid_union,unionErrors:s}),d});{let e;const n=[];for(const r of s){const s={...t,common:{...t.common,issues:[]},parent:null},a=r._parseSync({data:t.data,path:t.path,parent:s});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:s}),s.common.issues.length&&n.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=n.map(e=>new i(e));return l(t,{code:a.invalid_union,unionErrors:r}),d}}get options(){return this._def.options}}ce.create=(e,t)=>new ce({options:e,typeName:$e.ZodUnion,...b(t)});const le=e=>e instanceof _e?le(e.schema):e instanceof Se?le(e.innerType()):e instanceof ye?[e.value]:e instanceof we?e.options:e instanceof be?t.objectValues(e.enum):e instanceof ke?le(e._def.innerType):e instanceof Q?[void 0]:e instanceof ee?[null]:e instanceof Te?[void 0,...le(e.unwrap())]:e instanceof Ae?[null,...le(e.unwrap())]:e instanceof Ee||e instanceof Re?le(e.unwrap()):e instanceof Oe?le(e._def.innerType):[];class ue extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.object)return l(t,{code:a.invalid_type,expected:n.object,received:t.parsedType}),d;const s=this.discriminator,r=t.data[s],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:a.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),d)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const s of t){const t=le(s.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(n.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);n.set(r,s)}}return new ue({typeName:$e.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...b(s)})}}function de(e,s){const a=r(e),i=r(s);if(e===s)return{valid:!0,data:e};if(a===n.object&&i===n.object){const n=t.objectKeys(s),r=t.objectKeys(e).filter(e=>-1!==n.indexOf(e)),a={...e,...s};for(const t of r){const n=de(e[t],s[t]);if(!n.valid)return{valid:!1};a[t]=n.data}return{valid:!0,data:a}}if(a===n.array&&i===n.array){if(e.length!==s.length)return{valid:!1};const t=[];for(let n=0;n<e.length;n++){const r=de(e[n],s[n]);if(!r.valid)return{valid:!1};t.push(r.data)}return{valid:!0,data:t}}return a===n.date&&i===n.date&&+e===+s?{valid:!0,data:e}:{valid:!1}}class he extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(e,n)=>{if(f(e)||f(n))return d;const r=de(e.value,n.value);return r.valid?((m(e)||m(n))&&t.dirty(),{status:t.value,value:r.data}):(l(s,{code:a.invalid_intersection_types}),d)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}he.create=(e,t,s)=>new he({left:e,right:t,typeName:$e.ZodIntersection,...b(s)});class pe extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==n.array)return l(s,{code:a.invalid_type,expected:n.array,received:s.parsedType}),d;if(s.data.length<this._def.items.length)return l(s,{code:a.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;!this._def.rest&&s.data.length>this._def.items.length&&(l(s,{code:a.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...s.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new v(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(r).then(e=>u.mergeArray(t,e)):u.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new pe({...this._def,rest:e})}}pe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pe({items:e,typeName:$e.ZodTuple,rest:null,...b(t)})};class fe extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==n.object)return l(s,{code:a.invalid_type,expected:n.object,received:s.parsedType}),d;const r=[],i=this._def.keyType,o=this._def.valueType;for(const e in s.data)r.push({key:i._parse(new v(s,e,s.path,e)),value:o._parse(new v(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?u.mergeObjectAsync(t,r):u.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return new fe(t instanceof x?{keyType:e,valueType:t,typeName:$e.ZodRecord,...b(s)}:{keyType:K.create(),valueType:e,typeName:$e.ZodRecord,...b(t)})}}class me extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==n.map)return l(s,{code:a.invalid_type,expected:n.map,received:s.parsedType}),d;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([e,t],n)=>({key:r._parse(new v(s,e,s.path,[n,"key"])),value:i._parse(new v(s,t,s.path,[n,"value"]))}));if(s.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const s of o){const n=await s.key,r=await s.value;if("aborted"===n.status||"aborted"===r.status)return d;"dirty"!==n.status&&"dirty"!==r.status||t.dirty(),e.set(n.value,r.value)}return{status:t.value,value:e}})}{const e=new Map;for(const s of o){const n=s.key,r=s.value;if("aborted"===n.status||"aborted"===r.status)return d;"dirty"!==n.status&&"dirty"!==r.status||t.dirty(),e.set(n.value,r.value)}return{status:t.value,value:e}}}}me.create=(e,t,s)=>new me({valueType:t,keyType:e,typeName:$e.ZodMap,...b(s)});class ge extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==n.set)return l(s,{code:a.invalid_type,expected:n.set,received:s.parsedType}),d;const r=this._def;null!==r.minSize&&s.data.size<r.minSize.value&&(l(s,{code:a.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&s.data.size>r.maxSize.value&&(l(s,{code:a.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const s=new Set;for(const n of e){if("aborted"===n.status)return d;"dirty"===n.status&&t.dirty(),s.add(n.value)}return{status:t.value,value:s}}const c=[...s.data.values()].map((e,t)=>i._parse(new v(s,e,s.path,t)));return s.common.async?Promise.all(c).then(e=>o(e)):o(c)}min(e,t){return new ge({...this._def,minSize:{value:e,message:y.toString(t)}})}max(e,t){return new ge({...this._def,maxSize:{value:e,message:y.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ge.create=(e,t)=>new ge({valueType:e,minSize:null,maxSize:null,typeName:$e.ZodSet,...b(t)});class _e extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}_e.create=(e,t)=>new _e({getter:e,typeName:$e.ZodLazy,...b(t)});class ye extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:a.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ve(e,t){return new we({values:e,typeName:$e.ZodEnum,...b(t)})}ye.create=(e,t)=>new ye({value:e,typeName:$e.ZodLiteral,...b(t)});class we extends x{_parse(e){if("string"!=typeof e.data){const s=this._getOrReturnCtx(e),n=this._def.values;return l(s,{expected:t.joinValues(n),received:s.parsedType,code:a.invalid_type}),d}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return l(t,{received:t.data,code:a.invalid_enum_value,options:s}),d}return p(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return we.create(e,{...this._def,...t})}exclude(e,t=this._def){return we.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}we.create=ve;class be extends x{_parse(e){const s=t.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==n.string&&r.parsedType!==n.number){const e=t.objectValues(s);return l(r,{expected:t.joinValues(e),received:r.parsedType,code:a.invalid_type}),d}if(this._cache||(this._cache=new Set(t.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=t.objectValues(s);return l(r,{received:r.data,code:a.invalid_enum_value,options:e}),d}return p(e.data)}get enum(){return this._def.values}}be.create=(e,t)=>new be({values:e,typeName:$e.ZodNativeEnum,...b(t)});class xe extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.promise&&!1===t.common.async)return l(t,{code:a.invalid_type,expected:n.promise,received:t.parsedType}),d;const s=t.parsedType===n.promise?t.data:Promise.resolve(t.data);return p(s.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(e,t)=>new xe({type:e,typeName:$e.ZodPromise,...b(t)});class Se extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:s,ctx:n}=this._processInputParams(e),r=this._def.effect||null,a={addIssue:e=>{l(n,e),e.fatal?s.abort():s.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===r.type){const e=r.transform(n.data,a);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===s.value)return d;const t=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===t.status?d:"dirty"===t.status||"dirty"===s.value?h(t.value):t});{if("aborted"===s.value)return d;const t=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===t.status?d:"dirty"===t.status||"dirty"===s.value?h(t.value):t}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,a);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const t=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===t.status?d:("dirty"===t.status&&s.dirty(),e(t.value),{status:s.value,value:t.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(t=>"aborted"===t.status?d:("dirty"===t.status&&s.dirty(),e(t.value).then(()=>({status:s.value,value:t.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!g(e))return d;const t=r.transform(e.value,a);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:t}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>g(e)?Promise.resolve(r.transform(e.value,a)).then(e=>({status:s.value,value:e})):d)}t.assertNever(r)}}Se.create=(e,t,s)=>new Se({schema:e,typeName:$e.ZodEffects,effect:t,...b(s)}),Se.createWithPreprocess=(e,t,s)=>new Se({schema:t,effect:{type:"preprocess",transform:e},typeName:$e.ZodEffects,...b(s)});class Te extends x{_parse(e){return this._getType(e)===n.undefined?p(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:$e.ZodOptional,...b(t)});class Ae extends x{_parse(e){return this._getType(e)===n.null?p(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:$e.ZodNullable,...b(t)});class ke extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===n.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ke.create=(e,t)=>new ke({innerType:e,typeName:$e.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Oe extends x{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return _(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new i(s.common.issues)},input:s.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new i(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:$e.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class Ie extends x{_parse(e){if(this._getType(e)!==n.nan){const t=this._getOrReturnCtx(e);return l(t,{code:a.invalid_type,expected:n.nan,received:t.parsedType}),d}return{status:"valid",value:e.data}}}Ie.create=e=>new Ie({typeName:$e.ZodNaN,...b(e)});class Ee extends x{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ne extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?d:"dirty"===e.status?(t.dirty(),h(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})()}{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?d:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(e,t){return new Ne({in:e,out:t,typeName:$e.ZodPipeline})}}class Re extends x{_parse(e){const t=this._def.innerType._parse(e),s=e=>(g(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}}var $e;Re.create=(e,t)=>new Re({innerType:e,typeName:$e.ZodReadonly,...b(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}($e||($e={}));const Ce=K.create,Le=X.create,Pe=J.create,je=te.create;ne.create;const Me=ae.create,De=oe.create,Fe=ce.create,Ze=ue.create;he.create,pe.create;const Ue=fe.create,Be=ye.create;we.create;const qe=be.create;xe.create,Te.create,Ae.create;var We=De({name:Ce(),arguments:Ce()}),He=De({id:Ce(),type:Be("function"),function:We}),Ke=De({id:Ce(),role:Ce(),content:Ce().optional(),name:Ce().optional()}),Ve=De({type:Be("text"),text:Ce()}),Xe=De({type:Be("binary"),mimeType:Ce(),id:Ce().optional(),url:Ce().optional(),data:Ce().optional(),filename:Ce().optional()}),ze=(e,t)=>{e.id||e.url||e.data||t.addIssue({code:a.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})};Xe.superRefine((e,t)=>{ze(e,t)});var Je=Ze("type",[Ve,Xe]).superRefine((e,t)=>{"binary"===e.type&&ze(e,t)}),Ge=Ze("role",[Ke.extend({role:Be("developer"),content:Ce()}),Ke.extend({role:Be("system"),content:Ce()}),Ke.extend({role:Be("assistant"),content:Ce().optional(),toolCalls:Me(He).optional()}),Ke.extend({role:Be("user"),content:Fe([Ce(),Me(Je)])}),De({id:Ce(),content:Ce(),role:Be("tool"),toolCallId:Ce(),error:Ce().optional()}),De({id:Ce(),role:Be("activity"),activityType:Ce(),content:Ue(je())})]);Fe([Be("developer"),Be("system"),Be("assistant"),Be("user"),Be("tool"),Be("activity")]);var Ye=De({description:Ce(),value:Ce()}),Qe=De({name:Ce(),description:Ce(),parameters:je()}),et=De({threadId:Ce(),runId:Ce(),parentRunId:Ce().optional(),state:je(),messages:Me(Ge),tools:Me(Qe),context:Me(Ye),forwardedProps:je()}),tt=je(),st=Fe([Be("developer"),Be("system"),Be("assistant"),Be("user")]),nt=(e=>(e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e))(nt||{}),rt=De({type:qe(nt),timestamp:Le().optional(),rawEvent:je().optional()}),at=rt.extend({type:Be("TEXT_MESSAGE_START"),messageId:Ce(),role:st.default("assistant")}),it=rt.extend({type:Be("TEXT_MESSAGE_CONTENT"),messageId:Ce(),delta:Ce().refine(e=>e.length>0,"Delta must not be an empty string")}),ot=rt.extend({type:Be("TEXT_MESSAGE_END"),messageId:Ce()}),ct=rt.extend({type:Be("TEXT_MESSAGE_CHUNK"),messageId:Ce().optional(),role:st.optional(),delta:Ce().optional()}),lt=rt.extend({type:Be("THINKING_TEXT_MESSAGE_START")}),ut=it.omit({messageId:!0,type:!0}).extend({type:Be("THINKING_TEXT_MESSAGE_CONTENT")}),dt=rt.extend({type:Be("THINKING_TEXT_MESSAGE_END")}),ht=rt.extend({type:Be("TOOL_CALL_START"),toolCallId:Ce(),toolCallName:Ce(),parentMessageId:Ce().optional()}),pt=rt.extend({type:Be("TOOL_CALL_ARGS"),toolCallId:Ce(),delta:Ce()}),ft=rt.extend({type:Be("TOOL_CALL_END"),toolCallId:Ce()}),mt=rt.extend({messageId:Ce(),type:Be("TOOL_CALL_RESULT"),toolCallId:Ce(),content:Ce(),role:Be("tool").optional()}),gt=rt.extend({type:Be("TOOL_CALL_CHUNK"),toolCallId:Ce().optional(),toolCallName:Ce().optional(),parentMessageId:Ce().optional(),delta:Ce().optional()});Ze("type",[at,it,ot,ct,rt.extend({type:Be("THINKING_START"),title:Ce().optional()}),rt.extend({type:Be("THINKING_END")}),lt,ut,dt,ht,pt,ft,gt,mt,rt.extend({type:Be("STATE_SNAPSHOT"),snapshot:tt}),rt.extend({type:Be("STATE_DELTA"),delta:Me(je())}),rt.extend({type:Be("MESSAGES_SNAPSHOT"),messages:Me(Ge)}),rt.extend({type:Be("ACTIVITY_SNAPSHOT"),messageId:Ce(),activityType:Ce(),content:Ue(je()),replace:Pe().optional().default(!0)}),rt.extend({type:Be("ACTIVITY_DELTA"),messageId:Ce(),activityType:Ce(),patch:Me(je())}),rt.extend({type:Be("RAW"),event:je(),source:Ce().optional()}),rt.extend({type:Be("CUSTOM"),name:Ce(),value:je()}),rt.extend({type:Be("RUN_STARTED"),threadId:Ce(),runId:Ce(),parentRunId:Ce().optional(),input:et.optional()}),rt.extend({type:Be("RUN_FINISHED"),threadId:Ce(),runId:Ce(),result:je().optional()}),rt.extend({type:Be("RUN_ERROR"),message:Ce(),code:Ce().optional()}),rt.extend({type:Be("STEP_STARTED"),stepName:Ce()}),rt.extend({type:Be("STEP_FINISHED"),stepName:Ce()})]);var _t,yt,vt={},wt={};function bt(){return _t||(_t=1,e=wt,Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow),wt;var e}yt||(yt=1,function(e){var t=vt&&vt.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var r=Object.getOwnPropertyDescriptor(t,s);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,r)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),s=vt&&vt.__exportStar||function(e,s){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(s,n)||t(s,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;const n=bt();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),s(bt(),e);class r extends Error{}e.PartialJSON=r;class a extends Error{}function i(e,t=n.Allow.ALL){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return o(e.trim(),t)}e.MalformedJSON=a,e.parseJSON=i;const o=(e,t)=>{const s=e.length;let i=0;const o=e=>{throw new r(`${e} at position ${i}`)},c=e=>{throw new a(`${e} at position ${i}`)},l=()=>(f(),i>=s&&o("Unexpected end of input"),'"'===e[i]?u():"{"===e[i]?d():"["===e[i]?h():"null"===e.substring(i,i+4)||n.Allow.NULL&t&&s-i<4&&"null".startsWith(e.substring(i))?(i+=4,null):"true"===e.substring(i,i+4)||n.Allow.BOOL&t&&s-i<4&&"true".startsWith(e.substring(i))?(i+=4,!0):"false"===e.substring(i,i+5)||n.Allow.BOOL&t&&s-i<5&&"false".startsWith(e.substring(i))?(i+=5,!1):"Infinity"===e.substring(i,i+8)||n.Allow.INFINITY&t&&s-i<8&&"Infinity".startsWith(e.substring(i))?(i+=8,1/0):"-Infinity"===e.substring(i,i+9)||n.Allow._INFINITY&t&&1<s-i&&s-i<9&&"-Infinity".startsWith(e.substring(i))?(i+=9,-1/0):"NaN"===e.substring(i,i+3)||n.Allow.NAN&t&&s-i<3&&"NaN".startsWith(e.substring(i))?(i+=3,NaN):p()),u=()=>{const r=i;let a=!1;for(i++;i<s&&('"'!==e[i]||a&&"\\"===e[i-1]);)a="\\"===e[i]&&!a,i++;if('"'==e.charAt(i))try{return JSON.parse(e.substring(r,++i-Number(a)))}catch(e){c(String(e))}else if(n.Allow.STR&t)try{return JSON.parse(e.substring(r,i-Number(a))+'"')}catch(t){return JSON.parse(e.substring(r,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{i++,f();const r={};try{for(;"}"!==e[i];){if(f(),i>=s&&n.Allow.OBJ&t)return r;const a=u();f(),i++;try{const e=l();r[a]=e}catch(e){if(n.Allow.OBJ&t)return r;throw e}f(),","===e[i]&&i++}}catch(e){if(n.Allow.OBJ&t)return r;o("Expected '}' at end of object")}return i++,r},h=()=>{i++;const s=[];try{for(;"]"!==e[i];)s.push(l()),f(),","===e[i]&&i++}catch(e){if(n.Allow.ARR&t)return s;o("Expected ']' at end of array")}return i++,s},p=()=>{if(0===i){"-"===e&&c("Not sure what '-' is");try{return JSON.parse(e)}catch(s){if(n.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}c(String(s))}}const r=i;for("-"===e[i]&&i++;e[i]&&-1===",]}".indexOf(e[i]);)i++;i!=s||n.Allow.NUM&t||o("Unterminated number literal");try{return JSON.parse(e.substring(r,i))}catch(t){"-"===e.substring(r,i)&&o("Not sure what '-' is");try{return JSON.parse(e.substring(r,e.lastIndexOf("e")))}catch(e){c(String(e))}}},f=()=>{for(;i<s&&" \n\r\t".includes(e[i]);)i++};return l()},c=i;e.parse=c}(vt));var xt=(e=>(e.SERVICE_NOT_CONFIGURED="service_not_configured",e.INVALID_AUDIO_FORMAT="invalid_audio_format",e.AUDIO_TOO_LONG="audio_too_long",e.AUDIO_TOO_SHORT="audio_too_short",e.RATE_LIMITED="rate_limited",e.AUTH_FAILED="auth_failed",e.PROVIDER_ERROR="provider_error",e.NETWORK_ERROR="network_error",e.INVALID_REQUEST="invalid_request",e))(xt||{}),St=class{constructor(e){this.threadId=e}subject=null;isRunning=!1;currentRunId=null;historicRuns=[];agent=null;runSubject=null;stopRequested=!1;currentEvents=null},Tt=Symbol.for("@copilotkitnext/runtime/in-memory-store");!function(){const e=globalThis;e[Tt]||(e[Tt]={stores:new Map,historicRunsBackup:new Map});const t=e[Tt];if(0===t.stores.size&&t.historicRunsBackup.size>0)for(const[e,s]of t.historicRunsBackup){const n=new St(e);n.historicRuns=s,t.stores.set(e,n)}t.stores}(),xt.SERVICE_NOT_CONFIGURED,xt.INVALID_AUDIO_FORMAT,xt.AUDIO_TOO_LONG,xt.AUDIO_TOO_SHORT,xt.RATE_LIMITED,xt.AUTH_FAILED,xt.PROVIDER_ERROR,xt.NETWORK_ERROR,xt.INVALID_REQUEST,new Set(".\\+*[^]$()");var At=class{};function kt(e,t,s,n,r){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function Ot(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}let It=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return It=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^s()&15>>+e/4).toString(16))};function Et(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const Nt=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Rt extends Error{}class $t extends Rt{constructor(e,t,s,n){super(`${$t.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new Lt({message:s,cause:Nt(t)});const r=t?.error;return 400===e?new jt(e,r,s,n):401===e?new Mt(e,r,s,n):403===e?new Dt(e,r,s,n):404===e?new Ft(e,r,s,n):409===e?new Zt(e,r,s,n):422===e?new Ut(e,r,s,n):429===e?new Bt(e,r,s,n):e>=500?new qt(e,r,s,n):new $t(e,r,s,n)}}class Ct extends $t{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Lt extends $t{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Pt extends Lt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class jt extends $t{}class Mt extends $t{}class Dt extends $t{}class Ft extends $t{}class Zt extends $t{}class Ut extends $t{}class Bt extends $t{}class qt extends $t{}class Wt extends Rt{constructor(){super("Could not parse response content as the length limit was reached")}}class Ht extends Rt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Kt extends Error{constructor(e){super(e)}}const Vt=/^[a-z][a-z0-9+.-]*:/i;let Xt=e=>(Xt=Array.isArray,Xt(e)),zt=Xt;function Jt(e){return"object"!=typeof e?{}:e??{}}function Gt(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const Yt=e=>new Promise(t=>setTimeout(t,e)),Qt="5.23.2";const es=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qt,"X-Stainless-OS":ss(Deno.build.os),"X-Stainless-Arch":ts(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qt,"X-Stainless-OS":ss(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ts(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const ts=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ss=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let ns;function rs(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function as(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return rs({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function is(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const os=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),cs="RFC3986",ls=e=>String(e),us={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ls};let ds=(e,t)=>(ds=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ds(e,t));const hs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),ps=1024;function fs(e,t){if(Xt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const ms={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},gs=function(e,t){Array.prototype.push.apply(e,Xt(t)?t:[t])};let _s;const ys={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===s)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let i="";for(let e=0;e<a.length;e+=ps){const t=a.length>=ps?a.slice(e,e+ps):a,s=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?s[s.length]=t.charAt(e):n<128?s[s.length]=hs[n]:n<2048?s[s.length]=hs[192|n>>6]+hs[128|63&n]:n<55296||n>=57344?s[s.length]=hs[224|n>>12]+hs[128|n>>6&63]+hs[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=hs[240|n>>18]+hs[128|n>>12&63]+hs[128|n>>6&63]+hs[128|63&n])}i+=s.join("")}return i},encodeValuesOnly:!1,format:cs,formatter:ls,indices:!1,serializeDate:e=>(_s??(_s=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const vs={};function ws(e,t,s,n,r,a,i,o,c,l,u,d,h,p,f,m,g,_){let y=e,v=_,w=0,b=!1;for(;void 0!==(v=v.get(vs))&&!b;){const t=v.get(e);if(w+=1,void 0!==t){if(t===w)throw new RangeError("Cyclic object value");b=!0}void 0===v.get(vs)&&(w=0)}if("function"==typeof l?y=l(t,y):y instanceof Date?y=h?.(y):"comma"===s&&Xt(y)&&(y=fs(y,function(e){return e instanceof Date?h?.(e):e})),null===y){if(a)return c&&!m?c(t,ys.encoder,g,"key",p):t;y=""}if("string"==typeof(x=y)||"number"==typeof x||"boolean"==typeof x||"symbol"==typeof x||"bigint"==typeof x||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(y)){if(c){const e=m?t:c(t,ys.encoder,g,"key",p);return[f?.(e)+"="+f?.(c(y,ys.encoder,g,"value",p))]}return[f?.(t)+"="+f?.(String(y))]}var x;const S=[];if(void 0===y)return S;let T;if("comma"===s&&Xt(y))m&&c&&(y=fs(y,c)),T=[{value:y.length>0?y.join(",")||null:void 0}];else if(Xt(l))T=l;else{const e=Object.keys(y);T=u?e.sort(u):e}const A=o?String(t).replace(/\./g,"%2E"):String(t),k=n&&Xt(y)&&1===y.length?A+"[]":A;if(r&&Xt(y)&&0===y.length)return k+"[]";for(let t=0;t<T.length;++t){const v=T[t],b="object"==typeof v&&void 0!==v.value?v.value:y[v];if(i&&null===b)continue;const x=d&&o?v.replace(/\./g,"%2E"):v,A=Xt(y)?"function"==typeof s?s(k,x):k:k+(d?"."+x:"["+x+"]");_.set(e,w);const O=new WeakMap;O.set(vs,_),gs(S,ws(b,A,s,n,r,a,i,o,"comma"===s&&m&&Xt(y)?null:c,l,u,d,h,p,f,m,g,O))}return S}function bs(e,t={}){let s=e;const n=function(e=ys){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||ys.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=cs;if(void 0!==e.format){if(!ds(us,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=us[s];let r,a=ys.filter;if(("function"==typeof e.filter||Xt(e.filter))&&(a=e.filter),r=e.arrayFormat&&e.arrayFormat in ms?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":ys.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=void 0===e.allowDots?1==!!e.encodeDotInKeys||ys.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:ys.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:ys.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ys.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?ys.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:ys.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:ys.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:ys.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:ys.encodeValuesOnly,filter:a,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:ys.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:ys.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ys.strictNullHandling}}(t);let r,a;"function"==typeof n.filter?(a=n.filter,s=a("",s)):Xt(n.filter)&&(a=n.filter,r=a);const i=[];if("object"!=typeof s||null===s)return"";const o=ms[n.arrayFormat],c="comma"===o&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const l=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];n.skipNulls&&null===s[t]||gs(i,ws(s[t],t,o,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}const u=i.join(n.delimiter);let d=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}let xs,Ss;function Ts(e){let t;return(xs??(t=new globalThis.TextEncoder,xs=t.encode.bind(t)))(e)}function As(e){let t;return(Ss??(t=new globalThis.TextDecoder,Ss=t.decode.bind(t)))(e)}var ks,Os;class Is{constructor(){ks.set(this,void 0),Os.set(this,void 0),kt(this,ks,new Uint8Array),kt(this,Os,null)}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Ts(e):e;kt(this,ks,function(e){let t=0;for(const s of e)t+=s.length;const s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}([Ot(this,ks,"f"),t]));const s=[];let n;for(;null!=(n=Es(Ot(this,ks,"f"),Ot(this,Os,"f")));){if(n.carriage&&null==Ot(this,Os,"f")){kt(this,Os,n.index);continue}if(null!=Ot(this,Os,"f")&&(n.index!==Ot(this,Os,"f")+1||n.carriage)){s.push(As(Ot(this,ks,"f").subarray(0,Ot(this,Os,"f")-1))),kt(this,ks,Ot(this,ks,"f").subarray(Ot(this,Os,"f"))),kt(this,Os,null);continue}const e=null!==Ot(this,Os,"f")?n.preceding-1:n.preceding,t=As(Ot(this,ks,"f").subarray(0,e));s.push(t),kt(this,ks,Ot(this,ks,"f").subarray(n.index)),kt(this,Os,null)}return s}flush(){return Ot(this,ks,"f").length?this.decode("\n"):[]}}function Es(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}function Ns(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}ks=new WeakMap,Os=new WeakMap,Is.NEWLINE_CHARS=new Set(["\n","\r"]),Is.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const Rs={off:0,error:200,warn:300,info:400,debug:500},$s=(e,t,s)=>{var n,r;if(e)return n=Rs,r=e,Object.prototype.hasOwnProperty.call(n,r)?e:void Ms(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Rs))}`)};function Cs(){}function Ls(e,t,s){return!t||Rs[e]>Rs[s]?Cs:t[e].bind(t)}const Ps={error:Cs,warn:Cs,info:Cs,debug:Cs};let js=new WeakMap;function Ms(e){const t=e.logger,s=e.logLevel??"off";if(!t)return Ps;const n=js.get(t);if(n&&n[0]===s)return n[1];const r={error:Ls("error",t,s),warn:Ls("warn",t,s),info:Ls("info",t,s),debug:Ls("debug",t,s)};return js.set(t,[s,r]),r}const Ds=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Fs,Zs,Us;class Bs{constructor(e,t,s){this.iterator=e,Fs.set(this,void 0),this.controller=t,kt(this,Fs,s)}static fromSSEResponse(e,t,s){let n=!1;const r=s?Ms(s):console;return new Bs(async function*(){if(n)throw new Rt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Rt("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 Rt("Attempted to iterate over a response with no body")}const s=new qs,n=new Is,r=is(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const s of e){if(null==s)continue;const e=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?Ts(s):s;let n,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(n=Ns(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(r))for(const t of n.decode(e)){const e=s.decode(t);e&&(yield e)}for(const e of n.flush()){const t=s.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null!==n.event&&n.event.startsWith("thread.")){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new $t(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw r.error("Could not parse message into JSON:",n.data),r.error("From chunk:",n.raw),e}if(t&&t.error)throw new $t(void 0,t.error,void 0,e.headers);yield t}s=!0}catch(e){if(Et(e))return;throw e}finally{s||t.abort()}},t,s)}static fromReadableStream(e,t,s){let n=!1;return new Bs(async function*(){if(n)throw new Rt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new Is,s=is(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(e){if(Et(e))return;throw e}finally{s||t.abort()}},t,s)}[(Fs=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new Bs(()=>n(e),this.controller,Ot(this,Fs,"f")),new Bs(()=>n(t),this.controller,Ot(this,Fs,"f"))]}toReadableStream(){const e=this;let t;return rs({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:n}=await t.next();if(n)return e.close();const r=Ts(JSON.stringify(s)+"\n");e.enqueue(r)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class qs{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function Ws(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:a}=t,i=await(async()=>{if(t.options.stream)return Ms(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):Bs.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const n=s.headers.get("content-type"),r=n?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){return Hs(await s.json(),s)}return await s.text()})();return Ms(e).debug(`[${n}] response parsed`,Ds({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function Hs(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class Ks extends Promise{constructor(e,t,s=Ws){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,Zs.set(this,void 0),kt(this,Zs,e)}_thenUnwrap(e){return new Ks(Ot(this,Zs,"f"),this.responsePromise,async(t,s)=>Hs(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Ot(this,Zs,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Zs=new WeakMap;class Vs{constructor(e,t,s,n){Us.set(this,void 0),kt(this,Us,e),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Rt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ot(this,Us,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Us=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Xs extends Ks{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await Ws(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class zs extends Vs{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Js extends Vs{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Jt(this.options.query),after:t}}:null}}class Gs extends Vs{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...Jt(this.options.query),after:e}}:null}}const Ys=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Qs(e,t,s){return Ys(),new File(e,t??"unknown_file",s)}function en(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const tn=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],sn=async(e,t)=>({...e,body:await rn(e.body,t)}),nn=new WeakMap;const rn=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,s=nn.get(t);if(s)return s;const n=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new e(s).text()}catch{return!0}})();return nn.set(t,n),n}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>an(s,e,t))),s},an=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response)e.append(t,Qs([await s.blob()],en(s)));else if(tn(s))e.append(t,Qs([await new Response(as(s)).blob()],en(s)));else if((e=>e instanceof Blob&&"name"in e)(s))e.append(t,s,en(s));else if(Array.isArray(s))await Promise.all(s.map(s=>an(e,t+"[]",s)));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map(([s,n])=>an(e,`${t}[${s}]`,n)))}}},on=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function cn(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(on(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!tn(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await cn(s))}return t}class ln{constructor(e){this._client=e}}function un(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const dn=Object.freeze(Object.create(null)),hn=(e=un)=>function(t,...s){if(1===t.length)return t[0];let n=!1;const r=[],a=t.reduce((t,a,i)=>{/[?#]/.test(a)&&(n=!0);const o=s[i];let c=(n?encodeURIComponent:e)(""+o);return i!==s.length&&(null==o||"object"==typeof o&&o.toString===Object.getPrototypeOf(Object.getPrototypeOf(o.hasOwnProperty??dn)??dn)?.toString)&&(c=o+"",r.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(o).slice(8,-1)} is not a valid path parameter`})),t+a+(i===s.length?"":c)},""),i=a.split(/[?#]/,1)[0],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=o.exec(i));)r.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(r.sort((e,t)=>e.start-t.start),r.length>0){let e=0;const t=r.reduce((t,s)=>{const n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r},"");throw new Rt(`Path parameters result in path with invalid segments:\n${r.map(e=>e.error).join("\n")}\n${a}\n${t}`)}return a},pn=hn(un);let fn=class extends ln{list(e,t={},s){return this._client.getAPIList(pn`/chat/completions/${e}/messages`,Js,{query:t,...s})}};function mn(e){return void 0!==e&&"function"in e&&void 0!==e.function}function gn(e){return"auto-parseable-response-format"===e?.$brand}function _n(e){return"auto-parseable-tool"===e?.$brand}function yn(e,t){const s=e.choices.map(e=>{if("length"===e.finish_reason)throw new Wt;if("content_filter"===e.finish_reason)throw new Ht;return xn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const s=e.tools?.find(e=>mn(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:_n(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?vn(t,e.message.content):null}}});return{...e,choices:s}}function vn(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function wn(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const s=e.tools?.find(e=>mn(e)&&e.function?.name===t.function.name);return mn(s)&&(_n(s)||s?.function.strict||!1)}function bn(e){return!!gn(e.response_format)||(e.tools?.some(e=>_n(e)||"function"===e.type&&!0===e.function.strict)??!1)}function xn(e){for(const t of e||[])if("function"!==t.type)throw new Rt(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}const Sn=e=>"assistant"===e?.role,Tn=e=>"tool"===e?.role;var An,kn,On,In,En,Nn,Rn,$n,Cn,Ln,Pn,jn,Mn,Dn,Fn,Zn,Un,Bn,qn,Wn,Hn;class Kn{constructor(){An.add(this),this.controller=new AbortController,kn.set(this,void 0),On.set(this,()=>{}),In.set(this,()=>{}),En.set(this,void 0),Nn.set(this,()=>{}),Rn.set(this,()=>{}),$n.set(this,{}),Cn.set(this,!1),Ln.set(this,!1),Pn.set(this,!1),jn.set(this,!1),kt(this,kn,new Promise((e,t)=>{kt(this,On,e),kt(this,In,t)})),kt(this,En,new Promise((e,t)=>{kt(this,Nn,e),kt(this,Rn,t)})),Ot(this,kn,"f").catch(()=>{}),Ot(this,En,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Ot(this,An,"m",Mn).bind(this))},0)}_connected(){this.ended||(Ot(this,On,"f").call(this),this._emit("connect"))}get ended(){return Ot(this,Cn,"f")}get errored(){return Ot(this,Ln,"f")}get aborted(){return Ot(this,Pn,"f")}abort(){this.controller.abort()}on(e,t){return(Ot(this,$n,"f")[e]||(Ot(this,$n,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=Ot(this,$n,"f")[e];if(!s)return this;const n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(Ot(this,$n,"f")[e]||(Ot(this,$n,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{kt(this,jn,!0),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){kt(this,jn,!0),await Ot(this,En,"f")}_emit(e,...t){if(Ot(this,Cn,"f"))return;"end"===e&&(kt(this,Cn,!0),Ot(this,Nn,"f").call(this));const s=Ot(this,$n,"f")[e];if(s&&(Ot(this,$n,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return Ot(this,jn,"f")||s?.length||Promise.reject(e),Ot(this,In,"f").call(this,e),Ot(this,Rn,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Ot(this,jn,"f")||s?.length||Promise.reject(e),Ot(this,In,"f").call(this,e),Ot(this,Rn,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function Vn(e){return"function"==typeof e.parse}kn=new WeakMap,On=new WeakMap,In=new WeakMap,En=new WeakMap,Nn=new WeakMap,Rn=new WeakMap,$n=new WeakMap,Cn=new WeakMap,Ln=new WeakMap,Pn=new WeakMap,jn=new WeakMap,An=new WeakSet,Mn=function(e){if(kt(this,Ln,!0),e instanceof Error&&"AbortError"===e.name&&(e=new Ct),e instanceof Ct)return kt(this,Pn,!0),this._emit("abort",e);if(e instanceof Rt)return this._emit("error",e);if(e instanceof Error){const t=new Rt(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Rt(String(e)))};const Xn=10;class zn extends Kn{constructor(){super(...arguments),Dn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),Tn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Sn(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Rt("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Ot(this,Dn,"m",Fn).call(this)}async finalMessage(){return await this.done(),Ot(this,Dn,"m",Zn).call(this)}async finalFunctionToolCall(){return await this.done(),Ot(this,Dn,"m",Un).call(this)}async finalFunctionToolCallResult(){return await this.done(),Ot(this,Dn,"m",Bn).call(this)}async totalUsage(){return await this.done(),Ot(this,Dn,"m",qn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Ot(this,Dn,"m",Zn).call(this);t&&this._emit("finalMessage",t);const s=Ot(this,Dn,"m",Fn).call(this);s&&this._emit("finalContent",s);const n=Ot(this,Dn,"m",Un).call(this);n&&this._emit("finalFunctionToolCall",n);const r=Ot(this,Dn,"m",Bn).call(this);null!=r&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",Ot(this,Dn,"m",qn).call(this))}async _createChatCompletion(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ot(this,Dn,"m",Wn).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(yn(r,t))}async _runChatCompletion(e,t,s){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const n="tool",{tool_choice:r="auto",stream:a,...i}=t,o="string"!=typeof r&&"function"===r.type&&r?.function?.name,{maxChatCompletions:c=Xn}=s||{},l=t.tools.map(e=>{if(_n(e)){if(!e.$callback)throw new Rt("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?l.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...i,tool_choice:r,tools:d,messages:[...this.messages]},s),a=t.choices[0]?.message;if(!a)throw new Rt("missing message in ChatCompletion response");if(!a.tool_calls?.length)return;for(const e of a.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:s,arguments:r}=e.function,a=u[s];if(!a){const e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(o&&o!==s){const e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let i;try{i=Vn(a)?await a.parse(r):r}catch(e){const s=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:s});continue}const c=await a.function(i,this),l=Ot(this,Dn,"m",Hn).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),o)return}}}}Dn=new WeakSet,Fn=function(){return Ot(this,Dn,"m",Zn).call(this).content??null},Zn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Sn(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new Rt("stream ended without producing a ChatCompletionMessage with role=assistant")},Un=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Sn(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},Bn=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Tn(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},qn=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Wn=function(e){if(null!=e.n&&e.n>1)throw new Rt("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Hn=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Jn extends zn{static runTools(e,t,s){const n=new Jn,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,r)),n}_addMessage(e,t=!0){super._addMessage(e,t),Sn(e)&&e.content&&this._emit("content",e.content)}}const Gn=1,Yn=2,Qn=4,er=8,tr=16,sr=32,nr=64,rr=128,ar=256,ir=511;class or extends Error{}class cr extends Error{}const lr=(e,t)=>{const s=e.length;let n=0;const r=e=>{throw new or(`${e} at position ${n}`)},a=e=>{throw new cr(`${e} at position ${n}`)},i=()=>(d(),n>=s&&r("Unexpected end of input"),'"'===e[n]?o():"{"===e[n]?c():"["===e[n]?l():"null"===e.substring(n,n+4)||tr&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||sr&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||sr&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||rr&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||ar&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||nr&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),o=()=>{const i=n;let o=!1;for(n++;n<s&&('"'!==e[n]||o&&"\\"===e[n-1]);)o="\\"===e[n]&&!o,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(i,++n-Number(o)))}catch(e){a(String(e))}else if(Gn&t)try{return JSON.parse(e.substring(i,n-Number(o))+'"')}catch(t){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,d();const a={};try{for(;"}"!==e[n];){if(d(),n>=s&&er&t)return a;const r=o();d(),n++;try{const e=i();Object.defineProperty(a,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(er&t)return a;throw e}d(),","===e[n]&&n++}}catch(e){if(er&t)return a;r("Expected '}' at end of object")}return n++,a},l=()=>{n++;const s=[];try{for(;"]"!==e[n];)s.push(i()),d(),","===e[n]&&n++}catch(e){if(Qn&t)return s;r("Expected ']' at end of array")}return n++,s},u=()=>{if(0===n){"-"===e&&Yn&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(s){if(Yn&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}a(String(s))}}const i=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=s||Yn&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,n))}catch(s){"-"===e.substring(i,n)&&Yn&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){a(String(e))}}},d=()=>{for(;n<s&&" \n\r\t".includes(e[n]);)n++};return i()},ur=e=>function(e,t=ir){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return lr(e.trim(),t)}(e,ir^Yn);var dr,hr,pr,fr,mr,gr,_r,yr,vr,wr,br,xr;class Sr extends zn{constructor(e){super(),dr.add(this),hr.set(this,void 0),pr.set(this,void 0),fr.set(this,void 0),kt(this,hr,e),kt(this,pr,[])}get currentChatCompletionSnapshot(){return Ot(this,fr,"f")}static fromReadableStream(e){const t=new Sr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const n=new Sr(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,s){super._createChatCompletion;const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ot(this,dr,"m",mr).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const e of r)Ot(this,dr,"m",_r).call(this,e);if(r.controller.signal?.aborted)throw new Ct;return this._addChatCompletion(Ot(this,dr,"m",wr).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Ot(this,dr,"m",mr).call(this),this._connected();const n=Bs.fromReadableStream(e,this.controller);let r;for await(const e of n)r&&r!==e.id&&this._addChatCompletion(Ot(this,dr,"m",wr).call(this)),Ot(this,dr,"m",_r).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new Ct;return this._addChatCompletion(Ot(this,dr,"m",wr).call(this))}[(hr=new WeakMap,pr=new WeakMap,fr=new WeakMap,dr=new WeakSet,mr=function(){this.ended||kt(this,fr,void 0)},gr=function(e){let t=Ot(this,pr,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Ot(this,pr,"f")[e.index]=t,t)},_r=function(e){if(this.ended)return;const t=Ot(this,dr,"m",xr).call(this,e);this._emit("chunk",e,t);for(const s of e.choices){const e=t.choices[s.index];null!=s.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),null!=s.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=s.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=Ot(this,dr,"m",gr).call(this,e);e.finish_reason&&(Ot(this,dr,"m",vr).call(this,e),null!=n.current_tool_call_index&&Ot(this,dr,"m",yr).call(this,e,n.current_tool_call_index));for(const t of s.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(Ot(this,dr,"m",vr).call(this,e),null!=n.current_tool_call_index&&Ot(this,dr,"m",yr).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of s.delta.tool_calls??[]){const s=e.message.tool_calls?.[t.index];s?.type&&("function"===s?.type?this._emit("tool_calls.function.arguments.delta",{name:s.function?.name,index:t.index,arguments:s.function.arguments,parsed_arguments:s.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):Ar(s?.type))}}},yr=function(e,t){if(Ot(this,dr,"m",gr).call(this,e).done_tool_calls.has(t))return;const s=e.message.tool_calls?.[t];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if("function"===s.type){const e=Ot(this,hr,"f")?.tools?.find(e=>mn(e)&&e.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:t,arguments:s.function.arguments,parsed_arguments:_n(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},vr=function(e){const t=Ot(this,dr,"m",gr).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const s=Ot(this,dr,"m",br).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},wr=function(){if(this.ended)throw new Rt("stream has ended, this shouldn't happen");const e=Ot(this,fr,"f");if(!e)throw new Rt("request ended without sending any chunks");return kt(this,fr,void 0),kt(this,pr,[]),function(e,t){const{id:s,choices:n,created:r,model:a,system_fingerprint:i,...o}=e,c={...o,id:s,choices:n.map(({message:t,finish_reason:s,index:n,logprobs:r,...a})=>{if(!s)throw new Rt(`missing finish_reason for choice ${n}`);const{content:i=null,function_call:o,tool_calls:c,...l}=t,u=t.role;if(!u)throw new Rt(`missing role for choice ${n}`);if(o){const{arguments:e,name:c}=o;if(null==e)throw new Rt(`missing function_call.arguments for choice ${n}`);if(!c)throw new Rt(`missing function_call.name for choice ${n}`);return{...a,message:{content:i,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}return c?{...a,index:n,finish_reason:s,logprobs:r,message:{...l,role:u,content:i,refusal:t.refusal??null,tool_calls:c.map((t,s)=>{const{function:r,type:a,id:i,...o}=t,{arguments:c,name:l,...u}=r||{};if(null==i)throw new Rt(`missing choices[${n}].tool_calls[${s}].id\n${Tr(e)}`);if(null==a)throw new Rt(`missing choices[${n}].tool_calls[${s}].type\n${Tr(e)}`);if(null==l)throw new Rt(`missing choices[${n}].tool_calls[${s}].function.name\n${Tr(e)}`);if(null==c)throw new Rt(`missing choices[${n}].tool_calls[${s}].function.arguments\n${Tr(e)}`);return{...o,id:i,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:i,role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&bn(t)?yn(e,t):{...e,choices:e.choices.map(e=>(xn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(c,t)}(e,Ot(this,hr,"f"))},br=function(){const e=Ot(this,hr,"f")?.response_format;return gn(e)?e:null},xr=function(e){var t,s,n,r;let a=Ot(this,fr,"f");const{choices:i,...o}=e;a?Object.assign(a,o):a=kt(this,fr,{...o,choices:[]});for(const{delta:i,finish_reason:o,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||(e=a.choices[c]={finish_reason:o,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:n,refusal:r,...a}=l;Object.assign(e.logprobs,a),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),r&&((s=e.logprobs).refusal??(s.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},l);if(o&&(e.finish_reason=o,Ot(this,hr,"f")&&bn(Ot(this,hr,"f")))){if("length"===o)throw new Wt;if("content_filter"===o)throw new Ht}if(Object.assign(e,u),!i)continue;const{content:d,refusal:h,function_call:p,role:f,tool_calls:m,...g}=i;if(Object.assign(e.message,g),h&&(e.message.refusal=(e.message.refusal||"")+h),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&Ot(this,dr,"m",br).call(this)&&(e.message.parsed=ur(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:s,type:n,function:a,...i}of m){const o=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(o,i),s&&(o.id=s),n&&(o.type=n),a&&(o.function??(o.function={name:a.name??"",arguments:""})),a?.name&&(o.function.name=a.name),a?.arguments&&(o.function.arguments+=a.arguments,wn(Ot(this,hr,"f"),o)&&(o.function.parsed_arguments=ur(o.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Bs(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Tr(e){return JSON.stringify(e)}function Ar(e){}class kr extends Sr{static fromReadableStream(e){const t=new kr(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const n=new kr(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,r)),n}}let Or=class extends ln{constructor(){super(...arguments),this.messages=new fn(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(pn`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(pn`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",Js,{query:e,...t})}delete(e,t){return this._client.delete(pn`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new Rt(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new Rt(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>yn(t,e))}runTools(e,t){return e.stream?kr.runTools(this._client,e,t):Jn.runTools(this._client,e,t)}stream(e,t){return Sr.createChatCompletion(this._client,e,t)}};Or.Messages=fn;class Ir extends ln{constructor(){super(...arguments),this.completions=new Or(this._client)}}Ir.Completions=Or;const Er=Symbol("brand.privateNullableHeaders");function*Nr(e){if(!e)return;if(Er in e){const{values:t,nulls:s}=e;yield*t.entries();for(const e of s)yield[e,null];return}let t,s=!1;e instanceof Headers?t=e.entries():zt(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=zt(e[1])?e[1]:[e[1]];let r=!1;for(const e of n)void 0!==e&&(s&&!r&&(r=!0,yield[t,null]),yield[t,e])}}const Rr=e=>{const t=new Headers,s=new Set;for(const n of e){const e=new Set;for(const[r,a]of Nr(n)){const n=r.toLowerCase();e.has(n)||(t.delete(r),e.add(n)),null===a?(t.delete(r),s.add(n)):(t.append(r,a),s.delete(n))}}return{[Er]:!0,values:t,nulls:s}};class $r extends ln{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Rr([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Cr extends ln{create(e,t){return this._client.post("/audio/transcriptions",sn({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Lr extends ln{create(e,t){return this._client.post("/audio/translations",sn({body:e,...t,__metadata:{model:e.model}},this._client))}}class Pr extends ln{constructor(){super(...arguments),this.transcriptions=new Cr(this._client),this.translations=new Lr(this._client),this.speech=new $r(this._client)}}Pr.Transcriptions=Cr,Pr.Translations=Lr,Pr.Speech=$r;class jr extends ln{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(pn`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Js,{query:e,...t})}cancel(e,t){return this._client.post(pn`/batches/${e}/cancel`,t)}}class Mr extends ln{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(pn`/assistants/${e}`,{...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(pn`/assistants/${e}`,{body:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Js,{query:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(pn`/assistants/${e}`,{...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Dr extends ln{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Fr extends ln{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Zr=class extends ln{constructor(){super(...arguments),this.sessions=new Dr(this._client),this.transcriptionSessions=new Fr(this._client)}};Zr.Sessions=Dr,Zr.TranscriptionSessions=Fr;class Ur extends ln{create(e,t,s){return this._client.post(pn`/threads/${e}/messages`,{body:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(pn`/threads/${n}/messages/${e}`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(pn`/threads/${n}/messages/${e}`,{body:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(pn`/threads/${e}/messages`,Js,{query:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:n}=t;return this._client.delete(pn`/threads/${n}/messages/${e}`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Br extends ln{retrieve(e,t,s){const{thread_id:n,run_id:r,...a}=t;return this._client.get(pn`/threads/${n}/runs/${r}/steps/${e}`,{query:a,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:n,...r}=t;return this._client.getAPIList(pn`/threads/${n}/runs/${e}/steps`,Js,{query:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const qr=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var Wr,Hr,Kr,Vr,Xr,zr,Jr,Gr,Yr,Qr,ea,ta,sa,na,ra,aa,ia,oa,ca,la,ua,da,ha;class pa extends Kn{constructor(){super(...arguments),Wr.add(this),Kr.set(this,[]),Vr.set(this,{}),Xr.set(this,{}),zr.set(this,void 0),Jr.set(this,void 0),Gr.set(this,void 0),Yr.set(this,void 0),Qr.set(this,void 0),ea.set(this,void 0),ta.set(this,void 0),sa.set(this,void 0),na.set(this,void 0)}[(Kr=new WeakMap,Vr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,Jr=new WeakMap,Gr=new WeakMap,Yr=new WeakMap,Qr=new WeakMap,ea=new WeakMap,ta=new WeakMap,sa=new WeakMap,na=new WeakMap,Wr=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Hr;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const n=Bs.fromReadableStream(e,this.controller);for await(const e of n)Ot(this,Wr,"m",ra).call(this,e);if(n.controller.signal?.aborted)throw new Ct;return this._addRun(Ot(this,Wr,"m",aa).call(this))}toReadableStream(){return new Bs(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){const r=new Hr;return r._run(()=>r._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createToolAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},i=await e.submitToolOutputs(t,a,{...n,signal:this.controller.signal});this._connected();for await(const e of i)Ot(this,Wr,"m",ra).call(this,e);if(i.controller.signal?.aborted)throw new Ct;return this._addRun(Ot(this,Wr,"m",aa).call(this))}static createThreadAssistantStream(e,t,s){const n=new Hr;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){const r=new Hr;return r._run(()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return Ot(this,ta,"f")}currentRun(){return Ot(this,sa,"f")}currentMessageSnapshot(){return Ot(this,zr,"f")}currentRunStepSnapshot(){return Ot(this,na,"f")}async finalRunSteps(){return await this.done(),Object.values(Ot(this,Vr,"f"))}async finalMessages(){return await this.done(),Object.values(Ot(this,Xr,"f"))}async finalRun(){if(await this.done(),!Ot(this,Jr,"f"))throw Error("Final run was not received.");return Ot(this,Jr,"f")}async _createThreadAssistantStream(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));const r={...t,stream:!0},a=await e.createAndRun(r,{...s,signal:this.controller.signal});this._connected();for await(const e of a)Ot(this,Wr,"m",ra).call(this,e);if(a.controller.signal?.aborted)throw new Ct;return this._addRun(Ot(this,Wr,"m",aa).call(this))}async _createAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},i=await e.create(t,a,{...n,signal:this.controller.signal});this._connected();for await(const e of i)Ot(this,Wr,"m",ra).call(this,e);if(i.controller.signal?.aborted)throw new Ct;return this._addRun(Ot(this,Wr,"m",aa).call(this))}static accumulateDelta(e,t){for(const[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let t=e[s];if(null!=t)if("index"!==s&&"type"!==s){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!Gt(t)||!Gt(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...n);continue}for(const e of n){if(!Gt(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const s=e.index;if(null==s)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof s)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);const n=t[s];null==n?t.push(e):t[s]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[s]=t}else e[s]=n;else e[s]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}}Hr=pa,ra=function(e){if(!this.ended)switch(kt(this,ta,e),Ot(this,Wr,"m",ca).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Ot(this,Wr,"m",ha).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ot(this,Wr,"m",oa).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Ot(this,Wr,"m",ia).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},aa=function(){if(this.ended)throw new Rt("stream has ended, this shouldn't happen");if(!Ot(this,Jr,"f"))throw Error("Final run has not been received");return Ot(this,Jr,"f")},ia=function(e){const[t,s]=Ot(this,Wr,"m",ua).call(this,e,Ot(this,zr,"f"));kt(this,zr,t),Ot(this,Xr,"f")[t.id]=t;for(const e of s){const s=t.content[e.index];"text"==s?.type&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if("text"==s.type&&s.text){let e=s.text,n=t.content[s.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(s.index!=Ot(this,Gr,"f")){if(Ot(this,Yr,"f"))switch(Ot(this,Yr,"f").type){case"text":this._emit("textDone",Ot(this,Yr,"f").text,Ot(this,zr,"f"));break;case"image_file":this._emit("imageFileDone",Ot(this,Yr,"f").image_file,Ot(this,zr,"f"))}kt(this,Gr,s.index)}kt(this,Yr,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Ot(this,Gr,"f")){const t=e.data.content[Ot(this,Gr,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Ot(this,zr,"f"));break;case"text":this._emit("textDone",t.text,Ot(this,zr,"f"))}}Ot(this,zr,"f")&&this._emit("messageDone",e.data),kt(this,zr,void 0)}},oa=function(e){const t=Ot(this,Wr,"m",la).call(this,e);switch(kt(this,na,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&"tool_calls"==s.step_details.type&&s.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of s.step_details.tool_calls)e.index==Ot(this,Qr,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Ot(this,ea,"f")&&this._emit("toolCallDone",Ot(this,ea,"f")),kt(this,Qr,e.index),kt(this,ea,t.step_details.tool_calls[e.index]),Ot(this,ea,"f")&&this._emit("toolCallCreated",Ot(this,ea,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":kt(this,na,void 0);"tool_calls"==e.data.step_details.type&&Ot(this,ea,"f")&&(this._emit("toolCallDone",Ot(this,ea,"f")),kt(this,ea,void 0)),this._emit("runStepDone",e.data,t)}},ca=function(e){Ot(this,Kr,"f").push(e),this._emit("event",e)},la=function(e){switch(e.event){case"thread.run.step.created":return Ot(this,Vr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Ot(this,Vr,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const n=Hr.accumulateDelta(t,s.delta);Ot(this,Vr,"f")[e.data.id]=n}return Ot(this,Vr,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Ot(this,Vr,"f")[e.data.id]=e.data}if(Ot(this,Vr,"f")[e.data.id])return Ot(this,Vr,"f")[e.data.id];throw new Error("No snapshot available")},ua=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let s=t.content[e.index];t.content[e.index]=Ot(this,Wr,"m",da).call(this,e,s)}else t.content[e.index]=e,s.push(e);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},da=function(e,t){return Hr.accumulateDelta(t,e)},ha=function(e){switch(kt(this,sa,e.data),e.event){case"thread.run.created":case"thread.run.queued":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":kt(this,Jr,e.data),Ot(this,ea,"f")&&(this._emit("toolCallDone",Ot(this,ea,"f")),kt(this,ea,void 0))}};let fa=class extends ln{constructor(){super(...arguments),this.steps=new Br(this._client)}create(e,t,s){const{include:n,...r}=t;return this._client.post(pn`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(pn`/threads/${n}/runs/${e}`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(pn`/threads/${n}/runs/${e}`,{body:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(pn`/threads/${e}/runs`,Js,{query:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:n}=t;return this._client.post(pn`/threads/${n}/runs/${e}/cancel`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return pa.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n=Rr([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await Yt(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return pa.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:n,...r}=t;return this._client.post(pn`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){const n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return pa.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};fa.Steps=Br;class ma extends ln{constructor(){super(...arguments),this.runs=new fa(this._client),this.messages=new Ur(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(pn`/threads/${e}`,{...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(pn`/threads/${e}`,{body:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(pn`/threads/${e}`,{...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return pa.createThreadAssistantStream(e,this._client.beta.threads,t)}}ma.Runs=fa,ma.Messages=Ur;class ga extends ln{constructor(){super(...arguments),this.realtime=new Zr(this._client),this.assistants=new Mr(this._client),this.threads=new ma(this._client)}}ga.Realtime=Zr,ga.Assistants=Mr,ga.Threads=ma;class _a extends ln{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ya extends ln{retrieve(e,t,s){const{container_id:n}=t;return this._client.get(pn`/containers/${n}/files/${e}/content`,{...s,headers:Rr([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let va=class extends ln{constructor(){super(...arguments),this.content=new ya(this._client)}create(e,t,s){return this._client.post(pn`/containers/${e}/files`,sn({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:n}=t;return this._client.get(pn`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(pn`/containers/${e}/files`,Js,{query:t,...s})}delete(e,t,s){const{container_id:n}=t;return this._client.delete(pn`/containers/${n}/files/${e}`,{...s,headers:Rr([{Accept:"*/*"},s?.headers])})}};va.Content=ya;class wa extends ln{constructor(){super(...arguments),this.files=new va(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(pn`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Js,{query:e,...t})}delete(e,t){return this._client.delete(pn`/containers/${e}`,{...t,headers:Rr([{Accept:"*/*"},t?.headers])})}}wa.Files=va;class ba extends ln{create(e,t,s){const{include:n,...r}=t;return this._client.post(pn`/conversations/${e}/items`,{query:{include:n},body:r,...s})}retrieve(e,t,s){const{conversation_id:n,...r}=t;return this._client.get(pn`/conversations/${n}/items/${e}`,{query:r,...s})}list(e,t={},s){return this._client.getAPIList(pn`/conversations/${e}/items`,Gs,{query:t,...s})}delete(e,t,s){const{conversation_id:n}=t;return this._client.delete(pn`/conversations/${n}/items/${e}`,s)}}class xa extends ln{constructor(){super(...arguments),this.items=new ba(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(pn`/conversations/${e}`,t)}update(e,t,s){return this._client.post(pn`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(pn`/conversations/${e}`,t)}}xa.Items=ba;class Sa extends ln{create(e,t){const s=!!e.encoding_format;let n=s?e.encoding_format:"base64";s&&Ms(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?r:(Ms(this._client).debug("embeddings/decoding base64 embeddings from base64"),r._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)}),e)))}}class Ta extends ln{retrieve(e,t,s){const{eval_id:n,run_id:r}=t;return this._client.get(pn`/evals/${n}/runs/${r}/output_items/${e}`,s)}list(e,t,s){const{eval_id:n,...r}=t;return this._client.getAPIList(pn`/evals/${n}/runs/${e}/output_items`,Js,{query:r,...s})}}class Aa extends ln{constructor(){super(...arguments),this.outputItems=new Ta(this._client)}create(e,t,s){return this._client.post(pn`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:n}=t;return this._client.get(pn`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(pn`/evals/${e}/runs`,Js,{query:t,...s})}delete(e,t,s){const{eval_id:n}=t;return this._client.delete(pn`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:n}=t;return this._client.post(pn`/evals/${n}/runs/${e}`,s)}}Aa.OutputItems=Ta;class ka extends ln{constructor(){super(...arguments),this.runs=new Aa(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(pn`/evals/${e}`,t)}update(e,t,s){return this._client.post(pn`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",Js,{query:e,...t})}delete(e,t){return this._client.delete(pn`/evals/${e}`,t)}}ka.Runs=Aa;let Oa=class extends ln{create(e,t){return this._client.post("/files",sn({body:e,...t},this._client))}retrieve(e,t){return this._client.get(pn`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Js,{query:e,...t})}delete(e,t){return this._client.delete(pn`/files/${e}`,t)}content(e,t){return this._client.get(pn`/files/${e}/content`,{...t,headers:Rr([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await Yt(t),a=await this.retrieve(e),Date.now()-r>s)throw new Pt({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class Ia extends ln{}let Ea=class extends ln{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Na extends ln{constructor(){super(...arguments),this.graders=new Ea(this._client)}}Na.Graders=Ea;class Ra extends ln{create(e,t,s){return this._client.getAPIList(pn`/fine_tuning/checkpoints/${e}/permissions`,zs,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(pn`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(pn`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}}let $a=class extends ln{constructor(){super(...arguments),this.permissions=new Ra(this._client)}};$a.Permissions=Ra;class Ca extends ln{list(e,t={},s){return this._client.getAPIList(pn`/fine_tuning/jobs/${e}/checkpoints`,Js,{query:t,...s})}}class La extends ln{constructor(){super(...arguments),this.checkpoints=new Ca(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(pn`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Js,{query:e,...t})}cancel(e,t){return this._client.post(pn`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(pn`/fine_tuning/jobs/${e}/events`,Js,{query:t,...s})}pause(e,t){return this._client.post(pn`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(pn`/fine_tuning/jobs/${e}/resume`,t)}}La.Checkpoints=Ca;class Pa extends ln{constructor(){super(...arguments),this.methods=new Ia(this._client),this.jobs=new La(this._client),this.checkpoints=new $a(this._client),this.alpha=new Na(this._client)}}Pa.Methods=Ia,Pa.Jobs=La,Pa.Checkpoints=$a,Pa.Alpha=Na;class ja extends ln{}class Ma extends ln{constructor(){super(...arguments),this.graderModels=new ja(this._client)}}Ma.GraderModels=ja;class Da extends ln{createVariation(e,t){return this._client.post("/images/variations",sn({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",sn({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class Fa extends ln{retrieve(e,t){return this._client.get(pn`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",zs,e)}delete(e,t){return this._client.delete(pn`/models/${e}`,t)}}class Za extends ln{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class Ua extends ln{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class Ba extends ln{constructor(){super(...arguments),this.clientSecrets=new Ua(this._client)}}function qa(e,t){return t&&function(e){if(gn(e.text?.format))return!0;return!1}(t)?Wa(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}function Wa(e,t){const s=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:Ka(t,e)};if("message"===e.type){const s=e.content.map(e=>"output_text"===e.type?{...e,parsed:Ha(t,e.text)}:e);return{...e,content:s}}return e}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||Va(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function Ha(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const s=e.text?.format;return s.$parseRaw(t)}return JSON.parse(t)}function Ka(e,t){const s=(n=e.tools??[],r=t.name,n.find(e=>"function"===e.type&&e.name===r));var n,r,a;return{...t,...t,parsed_arguments:(a=s,"auto-parseable-tool"===a?.$brand?s.$parseRaw(t.arguments):s?.strict?JSON.parse(t.arguments):null)}}function Va(e){const t=[];for(const s of e.output)if("message"===s.type)for(const e of s.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}var Xa,za,Ja,Ga,Ya,Qa,ei,ti;Ba.ClientSecrets=Ua;class si extends Kn{constructor(e){super(),Xa.add(this),za.set(this,void 0),Ja.set(this,void 0),Ga.set(this,void 0),kt(this,za,e)}static createResponse(e,t,s){const n=new si(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ot(this,Xa,"m",Ya).call(this);let a=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const e of r)Ot(this,Xa,"m",Qa).call(this,e,a);if(r.controller.signal?.aborted)throw new Ct;return Ot(this,Xa,"m",ei).call(this)}[(za=new WeakMap,Ja=new WeakMap,Ga=new WeakMap,Xa=new WeakSet,Ya=function(){this.ended||kt(this,Ja,void 0)},Qa=function(e,t){if(this.ended)return;const s=(e,s)=>{(null==t||s.sequence_number>t)&&this._emit(e,s)},n=Ot(this,Xa,"m",ti).call(this,e);switch(s("event",e),e.type){case"response.output_text.delta":{const t=n.output[e.output_index];if(!t)throw new Rt(`missing output at index ${e.output_index}`);if("message"===t.type){const n=t.content[e.content_index];if(!n)throw new Rt(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new Rt(`expected content to be 'output_text', got ${n.type}`);s("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{const t=n.output[e.output_index];if(!t)throw new Rt(`missing output at index ${e.output_index}`);"function_call"===t.type&&s("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:s(e.type,e)}},ei=function(){if(this.ended)throw new Rt("stream has ended, this shouldn't happen");const e=Ot(this,Ja,"f");if(!e)throw new Rt("request ended without sending any events");kt(this,Ja,void 0);const t=function(e,t){return qa(e,t)}(e,Ot(this,za,"f"));return kt(this,Ga,t),t},ti=function(e){let t=Ot(this,Ja,"f");if(!t){if("response.created"!==e.type)throw new Rt(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=kt(this,Ja,e.response),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const s=t.output[e.output_index];if(!s)throw new Rt(`missing output at index ${e.output_index}`);const n=s.type,r=e.part;"message"===n&&"reasoning_text"!==r.type?s.content.push(r):"reasoning"===n&&"reasoning_text"===r.type&&(s.content||(s.content=[]),s.content.push(r));break}case"response.output_text.delta":{const s=t.output[e.output_index];if(!s)throw new Rt(`missing output at index ${e.output_index}`);if("message"===s.type){const t=s.content[e.content_index];if(!t)throw new Rt(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Rt(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const s=t.output[e.output_index];if(!s)throw new Rt(`missing output at index ${e.output_index}`);"function_call"===s.type&&(s.arguments+=e.delta);break}case"response.reasoning_text.delta":{const s=t.output[e.output_index];if(!s)throw new Rt(`missing output at index ${e.output_index}`);if("reasoning"===s.type){const t=s.content?.[e.content_index];if(!t)throw new Rt(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new Rt(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":kt(this,Ja,e.response)}return t},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Ot(this,Ga,"f");if(!e)throw new Rt("stream ended without producing a ChatCompletion");return e}}class ni extends ln{list(e,t={},s){return this._client.getAPIList(pn`/responses/${e}/input_items`,Js,{query:t,...s})}}class ri extends ln{constructor(){super(...arguments),this.inputItems=new ni(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&Va(e),e))}retrieve(e,t={},s){return this._client.get(pn`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&Va(e),e))}delete(e,t){return this._client.delete(pn`/responses/${e}`,{...t,headers:Rr([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>Wa(t,e))}stream(e,t){return si.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(pn`/responses/${e}/cancel`,t)}}ri.InputItems=ni;class ai extends ln{create(e,t,s){return this._client.post(pn`/uploads/${e}/parts`,sn({body:t,...s},this._client))}}class ii extends ln{constructor(){super(...arguments),this.parts=new ai(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(pn`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(pn`/uploads/${e}/complete`,{body:t,...s})}}ii.Parts=ai;class oi extends ln{create(e,t,s){return this._client.post(pn`/vector_stores/${e}/file_batches`,{body:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(pn`/vector_stores/${n}/file_batches/${e}`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:n}=t;return this._client.post(pn`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){const{vector_store_id:n,...r}=t;return this._client.getAPIList(pn`/vector_stores/${n}/file_batches/${e}/files`,Js,{query:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const n=Rr([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await Yt(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=n?.maxConcurrency??5,a=Math.min(r,t.length),i=this._client,o=t.values(),c=[...s];const l=Array(a).fill(o).map(async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},n);c.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),s=t.filter(e=>"rejected"===e.status);if(s.length){for(const e of s)console.error(e.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(l),await this.createAndPoll(e,{file_ids:c})}}class ci extends ln{create(e,t,s){return this._client.post(pn`/vector_stores/${e}/files`,{body:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(pn`/vector_stores/${n}/files/${e}`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:n,...r}=t;return this._client.post(pn`/vector_stores/${n}/files/${e}`,{body:r,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(pn`/vector_stores/${e}/files`,Js,{query:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:n}=t;return this._client.delete(pn`/vector_stores/${n}/files/${e}`,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){const n=Rr([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const r=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),a=r.data;switch(a.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await Yt(e);break;case"failed":case"completed":return a}}}async upload(e,t,s){const n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){const n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){const{vector_store_id:n}=t;return this._client.getAPIList(pn`/vector_stores/${n}/files/${e}/content`,zs,{...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class li extends ln{constructor(){super(...arguments),this.files=new ci(this._client),this.fileBatches=new oi(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(pn`/vector_stores/${e}`,{...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(pn`/vector_stores/${e}`,{body:t,...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Js,{query:e,...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(pn`/vector_stores/${e}`,{...t,headers:Rr([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(pn`/vector_stores/${e}/search`,zs,{body:t,method:"post",...s,headers:Rr([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}var ui,di,hi,pi,fi,mi,gi;li.Files=ci,li.FileBatches=oi;class _i extends ln{constructor(){super(...arguments),ui.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");Ot(this,ui,"m",di).call(this,s);const r=Rr([t]).values,a=Ot(this,ui,"m",hi).call(this,r,"webhook-signature"),i=Ot(this,ui,"m",hi).call(this,r,"webhook-timestamp"),o=Ot(this,ui,"m",hi).call(this,r,"webhook-id"),c=parseInt(i,10);if(isNaN(c))throw new Kt("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>n)throw new Kt("Webhook timestamp is too old");if(c>l+n)throw new Kt("Webhook timestamp is too new");const u=a.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),d=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),h=o?`${o}.${i}.${e}`:`${i}.${e}`,p=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of u)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,(new TextEncoder).encode(h)))return}catch{continue}throw new Kt("The given webhook signature does not match the expected signature")}}ui=new WeakSet,di=function(e){if("string"!=typeof e||0===e.length)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},hi=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(null==s)throw new Error(`Missing required header: ${t}`);return s};class yi{constructor({baseURL:e=qr("OPENAI_BASE_URL"),apiKey:t=qr("OPENAI_API_KEY"),organization:s=qr("OPENAI_ORG_ID")??null,project:n=qr("OPENAI_PROJECT_ID")??null,webhookSecret:r=qr("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(pi.add(this),mi.set(this,void 0),this.completions=new _a(this),this.chat=new Ir(this),this.embeddings=new Sa(this),this.files=new Oa(this),this.images=new Da(this),this.audio=new Pr(this),this.moderations=new Za(this),this.models=new Fa(this),this.fineTuning=new Pa(this),this.graders=new Ma(this),this.vectorStores=new li(this),this.webhooks=new _i(this),this.beta=new ga(this),this.batches=new jr(this),this.uploads=new ii(this),this.responses=new ri(this),this.realtime=new Ba(this),this.conversations=new xa(this),this.evals=new ka(this),this.containers=new wa(this),void 0===t)throw new Rt("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const i={apiKey:t,organization:s,project:n,webhookSecret:r,...a,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Rt("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");this.baseURL=i.baseURL,this.timeout=i.timeout??fi.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=$s(i.logLevel,"ClientOptions.logLevel",this)??$s(qr("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),kt(this,mi,os),this._options=i,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=s,this.project=n,this.webhookSecret=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return Rr([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return bs(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Qt}`}defaultIdempotencyKey(){return`stainless-node-retry-${It()}`}makeStatusError(e,t,s,n){return $t.generate(e,t,s,n)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(e){if(e instanceof Rt)throw e;throw new Rt(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new Rt(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const n=!Ot(this,pi,"m",gi).call(this)&&s||this.baseURL,r=(e=>Vt.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(a)||(t={...a,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Ks(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);const{req:a,url:i,timeout:o}=await this.buildRequest(n,{retryCount:r-t});await this.prepareRequest(a,{url:i,options:n});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===s?"":`, retryOf: ${s}`,u=Date.now();if(Ms(this).debug(`[${c}] sending request`,Ds({retryOfRequestLogID:s,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new Ct;const d=new AbortController,h=await this.fetchWithTimeout(i,a,o,d).catch(Nt),p=Date.now();if(h instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new Ct;const r=Et(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Ms(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),Ms(this).debug(`[${c}] connection ${r?"timed out":"failed"} (${e})`,Ds({retryOfRequestLogID:s,url:i,durationMs:p-u,message:h.message})),this.retryRequest(n,t,s??c);if(Ms(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),Ms(this).debug(`[${c}] connection ${r?"timed out":"failed"} (error; no more retries left)`,Ds({retryOfRequestLogID:s,url:i,durationMs:p-u,message:h.message})),r)throw new Pt;throw new Lt({cause:h})}const f=`[${c}${l}${[...h.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${a.method} ${i} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=await this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}(h.body),Ms(this).info(`${f} - ${e}`),Ms(this).debug(`[${c}] response error (${e})`,Ds({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(n,t,s??c,h.headers)}const r=e?"error; no more retries left":"error; not retryable";Ms(this).info(`${f} - ${r}`);const a=await h.text().catch(e=>Nt(e).message),i=(e=>{try{return JSON.parse(e)}catch(e){return}})(a),o=i?void 0:a;Ms(this).debug(`[${c}] response error (${r})`,Ds({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:o,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,i,o,h.headers)}return Ms(this).info(f),Ms(this).debug(`[${c}] response start`,Ds({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:n,controller:d,requestLogID:c,retryOfRequestLogID:s,startTime:u}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Xs(this,s,e)}async fetchWithTimeout(e,t,s,n){const{signal:r,method:a,...i}=t||{};r&&r.addEventListener("abort",()=>n.abort());const o=setTimeout(()=>n.abort(),s),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,l={signal:n.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(o)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s,n){let r;const a=n?.get("retry-after-ms");if(a){const e=parseFloat(a);Number.isNaN(e)||(r=e)}const i=n?.get("retry-after");if(i&&!r){const e=parseFloat(i);r=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){const s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await Yt(r),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:n,path:r,query:a,defaultBaseURL:i}=s,o=this.buildURL(r,a,i);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Rt(`${e} must be an integer`);if(t<0)throw new Rt(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:s});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...s.fetchOptions??{}},url:o,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let r={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const a=Rr([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ns??(ns=es()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=Rr([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:as(e)}:Ot(this,mi,"f").call(this,{body:e,headers:s})}}fi=yi,mi=new WeakMap,pi=new WeakSet,gi=function(){return"https://api.openai.com/v1"!==this.baseURL},yi.OpenAI=fi,yi.DEFAULT_TIMEOUT=6e5,yi.OpenAIError=Rt,yi.APIError=$t,yi.APIConnectionError=Lt,yi.APIConnectionTimeoutError=Pt,yi.APIUserAbortError=Ct,yi.NotFoundError=Ft,yi.ConflictError=Zt,yi.RateLimitError=Bt,yi.BadRequestError=jt,yi.AuthenticationError=Mt,yi.InternalServerError=qt,yi.PermissionDeniedError=Dt,yi.UnprocessableEntityError=Ut,yi.InvalidWebhookSignatureError=Kt,yi.toFile=async function(e,t,s){if(Ys(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&on(e))(e=await e))return e instanceof File?e:Qs([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Qs(await cn(n),t,s)}const n=await cn(e);if(t||(t=en(e)),!s?.type){const e=n.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(s={...s,type:e})}return Qs(n,t,s)},yi.Completions=_a,yi.Chat=Ir,yi.Embeddings=Sa,yi.Files=Oa,yi.Images=Da,yi.Audio=Pr,yi.Moderations=Za,yi.Models=Fa,yi.FineTuning=Pa,yi.Graders=Ma,yi.VectorStores=li,yi.Webhooks=_i,yi.Beta=ga,yi.Batches=jr,yi.Uploads=ii,yi.Responses=ri,yi.Realtime=Ba,yi.Conversations=xa,yi.Evals=ka,yi.Containers=wa;e.TranscriptionServiceOpenAI=class extends At{constructor(e){var t,s;super(),this.openai=null!==(t=e.openai)&&void 0!==t?t:new yi,this.model=null!==(s=e.model)&&void 0!==s?s:"whisper-1",this.language=e.language,this.prompt=e.prompt,this.temperature=e.temperature}async transcribeFile(e){return(await this.openai.audio.transcriptions.create({file:e.audioFile,model:this.model,...this.language&&{language:this.language},...this.prompt&&{prompt:this.prompt},...void 0!==this.temperature&&{temperature:this.temperature}})).text}}});
2
+ //# sourceMappingURL=index.umd.js.map