shiplightai 0.1.21 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/agentHelpers-ZM2YPYUG.js +3 -0
  2. package/dist/agentLogin-TVTERJCC.js +3 -0
  3. package/dist/chunk-47OHTDHW.js +18 -0
  4. package/dist/chunk-4MP3EHVU.js +11 -0
  5. package/dist/{chunk-32JFHFFG.js → chunk-AEEQXF3N.js} +29 -29
  6. package/dist/chunk-C6BVAOFE.js +3 -0
  7. package/dist/{chunk-RTTIJBGI.js → chunk-CSHDULY4.js} +28 -28
  8. package/dist/chunk-EEEG4LZX.js +3 -0
  9. package/dist/chunk-HJNJZWUA.js +5 -0
  10. package/dist/chunk-ID5JNGPZ.js +18 -0
  11. package/dist/{chunk-YHOTGR6H.js → chunk-J4TZ3OFZ.js} +1 -1
  12. package/dist/chunk-JQ2K2XJ4.js +61 -0
  13. package/dist/chunk-L5JSAS2D.js +3 -0
  14. package/dist/{chunk-YDR4P3GA.js → chunk-NLZ3YJX4.js} +1 -1
  15. package/dist/{chunk-JHSENQ4F.js → chunk-SFCNGCFT.js} +27 -27
  16. package/dist/{chunk-2F3YRAA7.js → chunk-VLVDPV2E.js} +13 -13
  17. package/dist/cjs/debugger-pw.cjs +7 -7
  18. package/dist/cjs/fixture.cjs +162 -147
  19. package/dist/cjs/index.cjs +229 -309
  20. package/dist/cjs/reporter.cjs +725 -0
  21. package/dist/cli.js +2107 -939
  22. package/dist/config-BUSI76YU.js +3 -0
  23. package/dist/debugger-pw.d.ts +5 -0
  24. package/dist/debugger-pw.js +1 -1
  25. package/dist/dist-3HGFS7M3-T7FMZHX4.js +3 -0
  26. package/dist/dist-K7NWI5BS.js +3 -0
  27. package/dist/dist-SIZHXBHX.js +3 -0
  28. package/dist/fixture.js +1 -1
  29. package/dist/handler-J6CCKSPE.js +3 -0
  30. package/dist/index.d.ts +1 -48
  31. package/dist/index.js +4 -11
  32. package/dist/{intRunner-5A6M6JSJ.js → intRunner-ZYEEZ6MK.js} +1 -1
  33. package/dist/reporter.d.ts +28 -0
  34. package/dist/reporter.js +723 -0
  35. package/dist/task-EDC5BGTS.js +192 -0
  36. package/dist/testFlow-HYGLHAP6.js +3 -0
  37. package/package.json +8 -1
  38. package/dist/agentHelpers-2TII7YCW.js +0 -3
  39. package/dist/agentLogin-GDOU6BCP.js +0 -3
  40. package/dist/chunk-DJDHFWEV.js +0 -3
  41. package/dist/chunk-JNRJXAJS.js +0 -18
  42. package/dist/chunk-LPSNOKYP.js +0 -61
  43. package/dist/chunk-THVHM4KG.js +0 -11
  44. package/dist/chunk-USRSZQWN.js +0 -5
  45. package/dist/dist-CXOVVE77.js +0 -3
  46. package/dist/dist-SRXGJZ7P.js +0 -3
  47. package/dist/handler-BAP4TGW6.js +0 -3
  48. package/dist/task-VW6MUEKX.js +0 -192
  49. package/dist/testFlow-ZLC5L5GT.js +0 -3
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  const require = __createRequire(import.meta.url);
3
- import{b as _t,c as Or,d as Tr,e as Nr,f as Fr,n as Mr}from"./chunk-RTTIJBGI.js";import{h as un,l as fn}from"./chunk-USRSZQWN.js";import{a as Z}from"./chunk-YDR4P3GA.js";import{b as ln,c as cn}from"./chunk-DJDHFWEV.js";import{zodToJsonSchema as hn}from"zod-to-json-schema";function Lr(s){let e=hn(s,{$refStrategy:"none"});if(e.$schema&&delete e.$schema,e.type!=="object")throw new Error(`Schema must be a Zod object schema, got type: ${e.type}`);return ur(e),e}function fa(s){return hn(s,{$refStrategy:"none"})}function ur(s){if(!(typeof s!="object"||s===null)){if(s.type==="object"&&(s.additionalProperties=!1,s.properties)){let e=Object.keys(s.properties);s.required=e;for(let t of Object.values(s.properties))ur(t)}s.type==="array"&&s.items&&ur(s.items);for(let e of["anyOf","oneOf","allOf"])Array.isArray(s[e])&&s[e].forEach(ur);for(let[e,t]of Object.entries(s))typeof t=="object"&&t!==null&&!["properties","items","anyOf","oneOf","allOf"].includes(e)&&ur(t)}}var pn=class{constructor(s){this.registry=s}getToolDefinitions(){return this.registry.getTools().filter(s=>s.availability.openai).map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:Lr(s.schema),strict:!0}}))}getToolDefinitionsFiltered(s){let e=new Set(s);return this.registry.getTools().filter(t=>e.has(t.name)&&t.availability.openai).map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:Lr(t.schema),strict:!0}}))}toJSON(){return this.getToolDefinitions()}getToolDefinition(s){let e=this.registry.get(s);if(e)return{type:"function",function:{name:e.name,description:e.description,parameters:Lr(e.schema),strict:!0}}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}};function jr(s,e){return s?{prompt_tokens:s.promptTokens||s.inputTokens||0,completion_tokens:s.completionTokens||s.outputTokens||0,total_tokens:s.totalTokens||0,model:e}:null}function Io(s,e){let t=new Map;for(let u of e)u.hash&&u.url?t.set(u.hash,u.url):u.uuid&&u.url&&t.set(u.uuid,u.url);let r=/!\[([^\]]*)\]\(image:([a-f0-9]{64}|[a-zA-Z0-9\-]+)\)/g,n=[],o=0,i;for(;(i=r.exec(s))!==null;){let u=s.slice(o,i.index);u&&n.push({type:"text",text:u});let p=i[2];t.has(p)?n.push({type:"image",image:new URL(t.get(p))}):n.push({type:"text",text:i[0]}),o=i.index+i[0].length}let a=s.slice(o);return a&&n.push({type:"text",text:a}),n.length===0&&n.push({type:"text",text:s}),n}function So(s){let e=[];for(let t of s){let r=t.content||"",n=t.images||[],o=Io(r,n);e.length>0&&o.length>0&&e.push({type:"text",text:`
3
+ import{b as gt,c as Or,d as Tr,e as Nr,f as Fr,n as Mr}from"./chunk-CSHDULY4.js";import{a as ee}from"./chunk-NLZ3YJX4.js";import{h as fn,l as hn}from"./chunk-HJNJZWUA.js";import{a as ws}from"./chunk-EEEG4LZX.js";import{c as un}from"./chunk-C6BVAOFE.js";import{zodToJsonSchema as pn}from"zod-to-json-schema";function Lr(s){let e=pn(s,{$refStrategy:"none"});if(e.$schema&&delete e.$schema,e.type!=="object")throw new Error(`Schema must be a Zod object schema, got type: ${e.type}`);return ur(e),e}function ha(s){return pn(s,{$refStrategy:"none"})}function ur(s){if(!(typeof s!="object"||s===null)){if(s.type==="object"&&(s.additionalProperties=!1,s.properties)){let e=Object.keys(s.properties);s.required=e;for(let t of Object.values(s.properties))ur(t)}s.type==="array"&&s.items&&ur(s.items);for(let e of["anyOf","oneOf","allOf"])Array.isArray(s[e])&&s[e].forEach(ur);for(let[e,t]of Object.entries(s))typeof t=="object"&&t!==null&&!["properties","items","anyOf","oneOf","allOf"].includes(e)&&ur(t)}}var dn=class{constructor(s){this.registry=s}getToolDefinitions(){return this.registry.getTools().filter(s=>s.availability.openai).map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:Lr(s.schema),strict:!0}}))}getToolDefinitionsFiltered(s){let e=new Set(s);return this.registry.getTools().filter(t=>e.has(t.name)&&t.availability.openai).map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:Lr(t.schema),strict:!0}}))}toJSON(){return this.getToolDefinitions()}getToolDefinition(s){let e=this.registry.get(s);if(e)return{type:"function",function:{name:e.name,description:e.description,parameters:Lr(e.schema),strict:!0}}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}};function So(s,e){let t=new Map;for(let u of e)u.hash&&u.url?t.set(u.hash,u.url):u.uuid&&u.url&&t.set(u.uuid,u.url);let r=/!\[([^\]]*)\]\(image:([a-f0-9]{64}|[a-zA-Z0-9\-]+)\)/g,n=[],o=0,i;for(;(i=r.exec(s))!==null;){let u=s.slice(o,i.index);u&&n.push({type:"text",text:u});let p=i[2];t.has(p)?n.push({type:"image",image:new URL(t.get(p))}):n.push({type:"text",text:i[0]}),o=i.index+i[0].length}let a=s.slice(o);return a&&n.push({type:"text",text:a}),n.length===0&&n.push({type:"text",text:s}),n}function vo(s){let e=[];for(let t of s){let r=t.content||"",n=t.images||[],o=So(r,n);e.length>0&&o.length>0&&e.push({type:"text",text:`
4
4
 
5
- `}),e.push(...o)}return e}var dn=!1;function Br(s,e=dn){if(e){let t=So(s);if(t.length===0)return[];let r={type:"text",text:`
5
+ `}),e.push(...o)}return e}var mn=!1;function jr(s,e=mn){if(e){let t=vo(s);if(t.length===0)return[];let r={type:"text",text:`
6
6
 
7
7
  <retrieved_knowledge>
8
8
 
@@ -22,7 +22,7 @@ Below are expert curated knowledge that are retrieved from the knowledge base; A
22
22
 
23
23
  </retrieved_knowledge>
24
24
 
25
- `}]:[]}}function mn(s,e=dn){if(!e)return 0;let t=0;for(let r of s)r.images&&(t+=r.images.length);return t}function vo(){let s=new Date,e=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).formatToParts(s),t=e.find(m=>m.type==="year").value,r=e.find(m=>m.type==="month").value,n=e.find(m=>m.type==="day").value,o=e.find(m=>m.type==="hour").value,i=e.find(m=>m.type==="minute").value,a=e.find(m=>m.type==="second").value,u=e.find(m=>m.type==="timeZoneName").value,p=String(s.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${n} ${o}:${i}:${a}.${p} ${u}`}function gn(s){return`# Your Role
25
+ `}]:[]}}function gn(s,e=mn){if(!e)return 0;let t=0;for(let r of s)r.images&&(t+=r.images.length);return t}function Po(){let s=new Date,e=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).formatToParts(s),t=e.find(m=>m.type==="year").value,r=e.find(m=>m.type==="month").value,n=e.find(m=>m.type==="day").value,o=e.find(m=>m.type==="hour").value,i=e.find(m=>m.type==="minute").value,a=e.find(m=>m.type==="second").value,u=e.find(m=>m.type==="timeZoneName").value,p=String(s.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${n} ${o}:${i}:${a}.${p} ${u}`}function _n(s){return`# Your Role
26
26
  You are part of a end-to-end testing system that is designed to automate the testing of a website. Given an instruction in natural language, your job is to translate it into an action in the predefined actions. The instruction might not match any action in the predefined actions or might require to interact with an element that is not on the page. It's your job to detect these cases and return an empty action.
27
27
 
28
28
  # Rules
@@ -82,11 +82,11 @@ Example of empty action when the target element is not on the page, or the instr
82
82
  "action": {}, // empty action object to indicate the instruction cannot be completed
83
83
  "completes_instruction": false
84
84
  }
85
- `}function Po(s){if(!s||s.length===0)return"";let e="";return s.forEach(([t,r],n)=>{e+=`(${n+1}) Description: ${t}
85
+ `}function Ro(s){if(!s||s.length===0)return"";let e="";return s.forEach(([t,r],n)=>{e+=`(${n+1}) Description: ${t}
86
86
  Feedback: ${r}
87
87
  `}),`## Additional context
88
88
  You just executed following steps in order:
89
- ${e}`}function _n(s,e,t,r,n,o,i=!1,a=vo(),u=!1,p){let m=[],d=`
89
+ ${e}`}function yn(s,e,t,r,n,o,i=!1,a=Po(),u=!1,p){let m=[],d=`
90
90
  # Instruction
91
91
  "${e}"
92
92
 
@@ -106,7 +106,7 @@ ${s.tabsText}
106
106
 
107
107
  ## Interactive elements from current page:
108
108
  ${s.elementsText}
109
- `;if(m.push({type:"text",text:d}),i&&s.slicedScreenshotsBase64)for(let h of s.slicedScreenshotsBase64)m.push({type:"text",text:"The following images provided are sliced screenshots of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),m.push({type:"image",image:h});else o&&(m.push({type:"text",text:"The following image provided is a screenshot of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),m.push({type:"image",image:o}));if(n&&n.length>0){let h=Br(n,u);m.push(...h)}let _="";if(_+=`
109
+ `;if(m.push({type:"text",text:d}),i&&s.slicedScreenshotsBase64)for(let h of s.slicedScreenshotsBase64)m.push({type:"text",text:"The following images provided are sliced screenshots of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),m.push({type:"image",image:h});else o&&(m.push({type:"text",text:"The following image provided is a screenshot of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),m.push({type:"image",image:o}));if(n&&n.length>0){let h=jr(n,u);m.push(...h)}let _="";if(_+=`
110
110
  Current local time is ${a}.
111
111
  `,t&&Object.keys(t).length>0){let h=[];for(let A of Object.keys(t))if(p?.has(A))h.push(` - ${A}: [SENSITIVE - value hidden]`);else{let b=t[A],R=typeof b=="string"?b:JSON.stringify(b);h.push(` - ${A}: "${R}"`)}_+=`
112
112
  ## Available Data Placeholders
@@ -119,23 +119,23 @@ To use them, write Jinja-like template syntax: {{ placeholder_name }}
119
119
  - Do NOT use the actual value directly
120
120
  - The values shown are for context only to help you understand what data is available
121
121
  - In action descriptions, describe what the placeholder represents in natural language (e.g., "Type the first user name" instead of "Type {{ firstUserName }}")
122
- `}if(r&&r.length>0){let h=Po(r);_+=`
122
+ `}if(r&&r.length>0){let h=Ro(r);_+=`
123
123
  `+h}return _+=`
124
124
  Based on the above information, please determine the right action to accomplish the task.
125
- `,m.push({type:"text",text:_}),m}function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function l(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var ws=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return ws=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function fr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var hr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var y=class extends Error{},B=class s extends y{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new ve({message:r,cause:hr(t)});let o=t?.error;return e===400?new yt(e,o,r,n):e===401?new bt(e,o,r,n):e===403?new wt(e,o,r,n):e===404?new xt(e,o,r,n):e===409?new At(e,o,r,n):e===422?new It(e,o,r,n):e===429?new St(e,o,r,n):e>=500?new vt(e,o,r,n):new s(e,o,r,n)}},L=class extends B{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ve=class extends B{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Pe=class extends ve{constructor({message:e}={}){super({message:e??"Request timed out."})}},yt=class extends B{},bt=class extends B{},wt=class extends B{},xt=class extends B{},At=class extends B{},It=class extends B{},St=class extends B{},vt=class extends B{},Pt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},Rt=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ne=class extends Error{constructor(e){super(e)}};var Eo=/^[a-z][a-z0-9+.-]*:/i,yn=s=>Eo.test(s),J=s=>(J=Array.isArray,J(s)),xs=J;function As(s){return typeof s!="object"?{}:s??{}}function bn(s){if(!s)return!0;for(let e in s)return!1;return!0}function wn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function pr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var xn=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${s} must be an integer`);if(e<0)throw new y(`${s} must be a positive integer`);return e};var An=s=>{try{return JSON.parse(s)}catch{return}};var oe=s=>new Promise(e=>setTimeout(e,s));var Re="6.25.0";var Pn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Co(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var $o=()=>{let s=Co();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Re,"X-Stainless-OS":Sn(Deno.build.os),"X-Stainless-Arch":In(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Re,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Re,"X-Stainless-OS":Sn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":In(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ko();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Re,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Re,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ko(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var In=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Sn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),vn,Rn=()=>vn??(vn=$o());function En(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Is(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Ur(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Is({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Ss(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Cn(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var $n=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Dr="RFC3986",vs=s=>String(s),Hr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:vs},Ps="RFC1738";var Wr=(s,e)=>(Wr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Wr(s,e)),ie=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Rs=1024,kn=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Rs){let u=o.length>=Rs?o.slice(a,a+Rs):o,p=[];for(let m=0;m<u.length;++m){let d=u.charCodeAt(m);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===Ps&&(d===40||d===41)){p[p.length]=u.charAt(m);continue}if(d<128){p[p.length]=ie[d];continue}if(d<2048){p[p.length]=ie[192|d>>6]+ie[128|d&63];continue}if(d<55296||d>=57344){p[p.length]=ie[224|d>>12]+ie[128|d>>6&63]+ie[128|d&63];continue}m+=1,d=65536+((d&1023)<<10|u.charCodeAt(m)&1023),p[p.length]=ie[240|d>>18]+ie[128|d>>12&63]+ie[128|d>>6&63]+ie[128|d&63]}i+=p.join("")}return i};function On(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Es(s,e){if(J(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Nn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Fn=function(s,e){Array.prototype.push.apply(s,J(e)?e:[e])},Tn,U={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:kn,encodeValuesOnly:!1,format:Dr,formatter:vs,indices:!1,serializeDate(s){return(Tn??(Tn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function No(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Cs={};function Mn(s,e,t,r,n,o,i,a,u,p,m,d,_,h,A,b,R,v){let w=s,k=v,P=0,E=!1;for(;(k=k.get(Cs))!==void 0&&!E;){let T=k.get(s);if(P+=1,typeof T<"u"){if(T===P)throw new RangeError("Cyclic object value");E=!0}typeof k.get(Cs)>"u"&&(P=0)}if(typeof p=="function"?w=p(e,w):w instanceof Date?w=_?.(w):t==="comma"&&J(w)&&(w=Es(w,function(T){return T instanceof Date?_?.(T):T})),w===null){if(o)return u&&!b?u(e,U.encoder,R,"key",h):e;w=""}if(No(w)||On(w)){if(u){let T=b?e:u(e,U.encoder,R,"key",h);return[A?.(T)+"="+A?.(u(w,U.encoder,R,"value",h))]}return[A?.(e)+"="+A?.(String(w))]}let O=[];if(typeof w>"u")return O;let C;if(t==="comma"&&J(w))b&&u&&(w=Es(w,u)),C=[{value:w.length>0?w.join(",")||null:void 0}];else if(J(p))C=p;else{let T=Object.keys(w);C=m?T.sort(m):T}let N=a?String(e).replace(/\./g,"%2E"):String(e),F=r&&J(w)&&w.length===1?N+"[]":N;if(n&&J(w)&&w.length===0)return F+"[]";for(let T=0;T<C.length;++T){let $=C[T],Q=typeof $=="object"&&typeof $.value<"u"?$.value:w[$];if(i&&Q===null)continue;let Ae=d&&a?$.replace(/\./g,"%2E"):$,dt=J(w)?typeof t=="function"?t(F,Ae):F:F+(d?"."+Ae:"["+Ae+"]");v.set(s,P);let De=new WeakMap;De.set(Cs,v),Fn(O,Mn(Q,dt,t,r,n,o,i,a,t==="comma"&&b&&J(w)?null:u,p,m,d,_,h,A,b,R,De))}return O}function Fo(s=U){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||U.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Dr;if(typeof s.format<"u"){if(!Wr(Hr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Hr[t],n=U.filter;(typeof s.filter=="function"||J(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Nn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=U.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:U.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:U.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:U.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:U.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?U.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:U.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:U.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:U.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:U.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:U.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:U.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:U.strictNullHandling}}function $s(s,e={}){let t=s,r=Fo(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):J(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let a=Nn[r.arrayFormat],u=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let _=0;_<n.length;++_){let h=n[_];r.skipNulls&&t[h]===null||Fn(i,Mn(t[h],h,a,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let m=i.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),m.length>0?d+m:""}function Bn(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Ln;function Et(s){let e;return(Ln??(e=new globalThis.TextEncoder,Ln=e.encode.bind(e)))(s)}var jn;function ks(s){let e;return(jn??(e=new globalThis.TextDecoder,jn=e.decode.bind(e)))(s)}var z,G,qe=class{constructor(){z.set(this,void 0),G.set(this,void 0),x(this,z,new Uint8Array,"f"),x(this,G,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Et(e):e;x(this,z,Bn([l(this,z,"f"),t]),"f");let r=[],n;for(;(n=Lo(l(this,z,"f"),l(this,G,"f")))!=null;){if(n.carriage&&l(this,G,"f")==null){x(this,G,n.index,"f");continue}if(l(this,G,"f")!=null&&(n.index!==l(this,G,"f")+1||n.carriage)){r.push(ks(l(this,z,"f").subarray(0,l(this,G,"f")-1))),x(this,z,l(this,z,"f").subarray(l(this,G,"f")),"f"),x(this,G,null,"f");continue}let o=l(this,G,"f")!==null?n.preceding-1:n.preceding,i=ks(l(this,z,"f").subarray(0,o));r.push(i),x(this,z,l(this,z,"f").subarray(n.index),"f"),x(this,G,null,"f")}return r}flush(){return l(this,z,"f").length?this.decode(`
125
+ `,m.push({type:"text",text:_}),m}function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function l(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var xs=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return xs=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function fr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var hr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var y=class extends Error{},B=class s extends y{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Re({message:r,cause:hr(t)});let o=t?.error;return e===400?new _t(e,o,r,n):e===401?new yt(e,o,r,n):e===403?new bt(e,o,r,n):e===404?new wt(e,o,r,n):e===409?new xt(e,o,r,n):e===422?new At(e,o,r,n):e===429?new It(e,o,r,n):e>=500?new St(e,o,r,n):new s(e,o,r,n)}},L=class extends B{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Re=class extends B{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ee=class extends Re{constructor({message:e}={}){super({message:e??"Request timed out."})}},_t=class extends B{},yt=class extends B{},bt=class extends B{},wt=class extends B{},xt=class extends B{},At=class extends B{},It=class extends B{},St=class extends B{},vt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},Pt=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},oe=class extends Error{constructor(e){super(e)}};var Co=/^[a-z][a-z0-9+.-]*:/i,bn=s=>Co.test(s),J=s=>(J=Array.isArray,J(s)),As=J;function Is(s){return typeof s!="object"?{}:s??{}}function wn(s){if(!s)return!0;for(let e in s)return!1;return!0}function xn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function pr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var An=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${s} must be an integer`);if(e<0)throw new y(`${s} must be a positive integer`);return e};var In=s=>{try{return JSON.parse(s)}catch{return}};var ie=s=>new Promise(e=>setTimeout(e,s));var Ce="6.25.0";var Rn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $o(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ko=()=>{let s=$o();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":vn(Deno.build.os),"X-Stainless-Arch":Sn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":vn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Sn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Oo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Oo(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Sn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",vn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Pn,En=()=>Pn??(Pn=ko());function Cn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ss(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Br(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Ss({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function vs(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function $n(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var kn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ur="RFC3986",Ps=s=>String(s),Dr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Ps},Rs="RFC1738";var Hr=(s,e)=>(Hr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Hr(s,e)),ae=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Es=1024,On=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Es){let u=o.length>=Es?o.slice(a,a+Es):o,p=[];for(let m=0;m<u.length;++m){let d=u.charCodeAt(m);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===Rs&&(d===40||d===41)){p[p.length]=u.charAt(m);continue}if(d<128){p[p.length]=ae[d];continue}if(d<2048){p[p.length]=ae[192|d>>6]+ae[128|d&63];continue}if(d<55296||d>=57344){p[p.length]=ae[224|d>>12]+ae[128|d>>6&63]+ae[128|d&63];continue}m+=1,d=65536+((d&1023)<<10|u.charCodeAt(m)&1023),p[p.length]=ae[240|d>>18]+ae[128|d>>12&63]+ae[128|d>>6&63]+ae[128|d&63]}i+=p.join("")}return i};function Tn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Cs(s,e){if(J(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Fn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Mn=function(s,e){Array.prototype.push.apply(s,J(e)?e:[e])},Nn,U={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:On,encodeValuesOnly:!1,format:Ur,formatter:Ps,indices:!1,serializeDate(s){return(Nn??(Nn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Fo(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var $s={};function Ln(s,e,t,r,n,o,i,a,u,p,m,d,_,h,A,b,R,v){let w=s,k=v,P=0,E=!1;for(;(k=k.get($s))!==void 0&&!E;){let T=k.get(s);if(P+=1,typeof T<"u"){if(T===P)throw new RangeError("Cyclic object value");E=!0}typeof k.get($s)>"u"&&(P=0)}if(typeof p=="function"?w=p(e,w):w instanceof Date?w=_?.(w):t==="comma"&&J(w)&&(w=Cs(w,function(T){return T instanceof Date?_?.(T):T})),w===null){if(o)return u&&!b?u(e,U.encoder,R,"key",h):e;w=""}if(Fo(w)||Tn(w)){if(u){let T=b?e:u(e,U.encoder,R,"key",h);return[A?.(T)+"="+A?.(u(w,U.encoder,R,"value",h))]}return[A?.(e)+"="+A?.(String(w))]}let O=[];if(typeof w>"u")return O;let C;if(t==="comma"&&J(w))b&&u&&(w=Cs(w,u)),C=[{value:w.length>0?w.join(",")||null:void 0}];else if(J(p))C=p;else{let T=Object.keys(w);C=m?T.sort(m):T}let N=a?String(e).replace(/\./g,"%2E"):String(e),F=r&&J(w)&&w.length===1?N+"[]":N;if(n&&J(w)&&w.length===0)return F+"[]";for(let T=0;T<C.length;++T){let $=C[T],Ie=typeof $=="object"&&typeof $.value<"u"?$.value:w[$];if(i&&Ie===null)continue;let Q=d&&a?$.replace(/\./g,"%2E"):$,dt=J(w)?typeof t=="function"?t(F,Q):F:F+(d?"."+Q:"["+Q+"]");v.set(s,P);let We=new WeakMap;We.set($s,v),Mn(O,Ln(Ie,dt,t,r,n,o,i,a,t==="comma"&&b&&J(w)?null:u,p,m,d,_,h,A,b,R,We))}return O}function Mo(s=U){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||U.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ur;if(typeof s.format<"u"){if(!Hr(Dr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Dr[t],n=U.filter;(typeof s.filter=="function"||J(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Fn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=U.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:U.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:U.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:U.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:U.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?U.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:U.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:U.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:U.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:U.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:U.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:U.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:U.strictNullHandling}}function ks(s,e={}){let t=s,r=Mo(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):J(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let a=Fn[r.arrayFormat],u=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let _=0;_<n.length;++_){let h=n[_];r.skipNulls&&t[h]===null||Mn(i,Ln(t[h],h,a,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let m=i.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),m.length>0?d+m:""}function Un(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var jn;function Rt(s){let e;return(jn??(e=new globalThis.TextEncoder,jn=e.encode.bind(e)))(s)}var Bn;function Os(s){let e;return(Bn??(e=new globalThis.TextDecoder,Bn=e.decode.bind(e)))(s)}var z,G,qe=class{constructor(){z.set(this,void 0),G.set(this,void 0),x(this,z,new Uint8Array,"f"),x(this,G,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Rt(e):e;x(this,z,Un([l(this,z,"f"),t]),"f");let r=[],n;for(;(n=jo(l(this,z,"f"),l(this,G,"f")))!=null;){if(n.carriage&&l(this,G,"f")==null){x(this,G,n.index,"f");continue}if(l(this,G,"f")!=null&&(n.index!==l(this,G,"f")+1||n.carriage)){r.push(Os(l(this,z,"f").subarray(0,l(this,G,"f")-1))),x(this,z,l(this,z,"f").subarray(l(this,G,"f")),"f"),x(this,G,null,"f");continue}let o=l(this,G,"f")!==null?n.preceding-1:n.preceding,i=Os(l(this,z,"f").subarray(0,o));r.push(i),x(this,z,l(this,z,"f").subarray(n.index),"f"),x(this,G,null,"f")}return r}flush(){return l(this,z,"f").length?this.decode(`
126
126
  `):[]}};z=new WeakMap,G=new WeakMap;qe.NEWLINE_CHARS=new Set([`
127
- `,"\r"]);qe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Lo(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Un(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var Jr={off:0,error:200,warn:300,info:400,debug:500},Os=(s,e,t)=>{if(s){if(wn(Jr,s))return s;M(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Jr))}`)}};function dr(){}function qr(s,e,t){return!e||Jr[s]>Jr[t]?dr:e[s].bind(e)}var jo={error:dr,warn:dr,info:dr,debug:dr},Dn=new WeakMap;function M(s){let e=s.logger,t=s.logLevel??"off";if(!e)return jo;let r=Dn.get(e);if(r&&r[0]===t)return r[1];let n={error:qr("error",e,t),warn:qr("warn",e,t),info:qr("info",e,t),debug:qr("debug",e,t)};return Dn.set(e,[t,n]),n}var fe=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var mr,ae=class s{constructor(e,t,r){this.iterator=e,mr.set(this,void 0),this.controller=t,x(this,mr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,i=r?M(r):console;async function*a(){if(o)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let u=!1;try{for await(let p of Bo(e,t))if(!u){if(p.data.startsWith("[DONE]")){u=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let m;try{m=JSON.parse(p.data)}catch(d){throw i.error("Could not parse message into JSON:",p.data),i.error("From chunk:",p.raw),d}if(m&&m.error)throw new B(void 0,m.error,void 0,e.headers);yield n?{event:p.event,data:m}:m}else{let m;try{m=JSON.parse(p.data)}catch(d){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),d}if(p.event=="error")throw new B(void 0,m.error,m.message,void 0);yield{event:p.event,data:m}}}u=!0}catch(p){if(fr(p))return;throw p}finally{u||t.abort()}}return new s(a,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let a=new qe,u=Ss(e);for await(let p of u)for(let m of a.decode(p))yield m;for(let p of a.flush())yield p}async function*i(){if(n)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let u of o())a||u&&(yield JSON.parse(u));a=!0}catch(u){if(fr(u))return;throw u}finally{a||t.abort()}}return new s(i,t,r)}[(mr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,l(this,mr,"f")),new s(()=>n(t),this.controller,l(this,mr,"f"))]}toReadableStream(){let e=this,t;return Is({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=Et(JSON.stringify(n)+`
128
- `);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Bo(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new Ts,r=new qe,n=Ss(s.body);for await(let o of Uo(n))for(let i of r.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*Uo(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Et(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Un(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Ts=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
129
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=Do(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Do(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Kr(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return M(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):ae.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let _=await t.json();return Ns(_,t)}return await t.text()})();return M(s).debug(`[${r}] response parsed`,fe({retryOfRequestLogID:n,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function Ns(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var gr,Je=class s extends Promise{constructor(e,t,r=Kr){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,gr.set(this,void 0),x(this,gr,e,"f")}_thenUnwrap(e){return new s(l(this,gr,"f"),this.responsePromise,async(t,r)=>Ns(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[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(l(this,gr,"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)}};gr=new WeakMap;var Vr,_r=class{constructor(e,t,r,n){Vr.set(this,void 0),x(this,Vr,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await l(this,Vr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Vr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},yr=class extends Je{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await Kr(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},le=class extends _r{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends _r{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...As(this.options.query),after:t}}:null}},he=class extends _r{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...As(this.options.query),after:e}}:null}};var Ls=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ct(s,e,t){return Ls(),new File(s,e??"unknown_file",t)}function br(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var Xr=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",pe=async(s,e)=>Fs(s.body)?{...s,body:await Wn(s.body,e)}:s,ee=async(s,e)=>({...s,body:await Wn(s.body,e)}),Hn=new WeakMap;function Wo(s){let e=typeof s=="function"?s:s.fetch,t=Hn.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return Hn.set(e,r),r}var Wn=async(s,e)=>{if(!await Wo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>Ms(t,r,n))),t},qn=s=>s instanceof Blob&&"name"in s,qo=s=>typeof s=="object"&&s!==null&&(s instanceof Response||Xr(s)||qn(s)),Fs=s=>{if(qo(s))return!0;if(Array.isArray(s))return s.some(Fs);if(s&&typeof s=="object"){for(let e in s)if(Fs(s[e]))return!0}return!1},Ms=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,Ct([await t.blob()],br(t)));else if(Xr(t))s.append(e,Ct([await new Response(Ur(t)).blob()],br(t)));else if(qn(t))s.append(e,t,br(t));else if(Array.isArray(t))await Promise.all(t.map(r=>Ms(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>Ms(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Jn=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Jo=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Jn(s),Ko=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function zr(s,e,t){if(Ls(),s=await s,Jo(s))return s instanceof File?s:Ct([await s.arrayBuffer()],s.name);if(Ko(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Ct(await js(n),e,t)}let r=await js(s);if(e||(e=br(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Ct(r,e,t)}async function js(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Jn(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Xr(s))for await(let t of s)e.push(...await js(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Vo(s)}`)}return e}function Vo(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var f=class{constructor(e){this._client=e}};function Vn(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Kn=Object.freeze(Object.create(null)),zo=(s=Vn)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],i=t.reduce((m,d,_)=>{/[?#]/.test(d)&&(n=!0);let h=r[_],A=(n?encodeURIComponent:s)(""+h);return _!==r.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Kn)??Kn)?.toString)&&(A=h+"",o.push({start:m.length+d.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),m+d+(_===r.length?"":A)},""),a=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=u.exec(a))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((m,d)=>m.start-d.start),o.length>0){let m=0,d=o.reduce((_,h)=>{let A=" ".repeat(h.start-m),b="^".repeat(h.length);return m=h.start+h.length,_+A+b},"");throw new y(`Path parameters result in path with invalid segments:
127
+ `,"\r"]);qe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jo(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Dn(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var qr={off:0,error:200,warn:300,info:400,debug:500},Ts=(s,e,t)=>{if(s){if(xn(qr,s))return s;M(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(qr))}`)}};function dr(){}function Wr(s,e,t){return!e||qr[s]>qr[t]?dr:e[s].bind(e)}var Bo={error:dr,warn:dr,info:dr,debug:dr},Hn=new WeakMap;function M(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Bo;let r=Hn.get(e);if(r&&r[0]===t)return r[1];let n={error:Wr("error",e,t),warn:Wr("warn",e,t),info:Wr("info",e,t),debug:Wr("debug",e,t)};return Hn.set(e,[t,n]),n}var he=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var mr,le=class s{constructor(e,t,r){this.iterator=e,mr.set(this,void 0),this.controller=t,x(this,mr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,i=r?M(r):console;async function*a(){if(o)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let u=!1;try{for await(let p of Uo(e,t))if(!u){if(p.data.startsWith("[DONE]")){u=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let m;try{m=JSON.parse(p.data)}catch(d){throw i.error("Could not parse message into JSON:",p.data),i.error("From chunk:",p.raw),d}if(m&&m.error)throw new B(void 0,m.error,void 0,e.headers);yield n?{event:p.event,data:m}:m}else{let m;try{m=JSON.parse(p.data)}catch(d){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),d}if(p.event=="error")throw new B(void 0,m.error,m.message,void 0);yield{event:p.event,data:m}}}u=!0}catch(p){if(fr(p))return;throw p}finally{u||t.abort()}}return new s(a,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let a=new qe,u=vs(e);for await(let p of u)for(let m of a.decode(p))yield m;for(let p of a.flush())yield p}async function*i(){if(n)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let u of o())a||u&&(yield JSON.parse(u));a=!0}catch(u){if(fr(u))return;throw u}finally{a||t.abort()}}return new s(i,t,r)}[(mr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,l(this,mr,"f")),new s(()=>n(t),this.controller,l(this,mr,"f"))]}toReadableStream(){let e=this,t;return Ss({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=Rt(JSON.stringify(n)+`
128
+ `);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Uo(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new Ns,r=new qe,n=vs(s.body);for await(let o of Do(n))for(let i of r.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*Do(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Rt(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Dn(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Ns=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
129
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=Ho(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Ho(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Jr(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return M(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):le.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let _=await t.json();return Fs(_,t)}return await t.text()})();return M(s).debug(`[${r}] response parsed`,he({retryOfRequestLogID:n,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function Fs(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var gr,Je=class s extends Promise{constructor(e,t,r=Jr){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,gr.set(this,void 0),x(this,gr,e,"f")}_thenUnwrap(e){return new s(l(this,gr,"f"),this.responsePromise,async(t,r)=>Fs(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[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(l(this,gr,"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)}};gr=new WeakMap;var Kr,_r=class{constructor(e,t,r,n){Kr.set(this,void 0),x(this,Kr,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await l(this,Kr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Kr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},yr=class extends Je{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await Jr(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ce=class extends _r{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends _r{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Is(this.options.query),after:t}}:null}},pe=class extends _r{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Is(this.options.query),after:e}}:null}};var js=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Et(s,e,t){return js(),new File(s,e??"unknown_file",t)}function br(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var Vr=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",de=async(s,e)=>Ms(s.body)?{...s,body:await qn(s.body,e)}:s,te=async(s,e)=>({...s,body:await qn(s.body,e)}),Wn=new WeakMap;function qo(s){let e=typeof s=="function"?s:s.fetch,t=Wn.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return Wn.set(e,r),r}var qn=async(s,e)=>{if(!await qo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>Ls(t,r,n))),t},Jn=s=>s instanceof Blob&&"name"in s,Jo=s=>typeof s=="object"&&s!==null&&(s instanceof Response||Vr(s)||Jn(s)),Ms=s=>{if(Jo(s))return!0;if(Array.isArray(s))return s.some(Ms);if(s&&typeof s=="object"){for(let e in s)if(Ms(s[e]))return!0}return!1},Ls=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,Et([await t.blob()],br(t)));else if(Vr(t))s.append(e,Et([await new Response(Br(t)).blob()],br(t)));else if(Jn(t))s.append(e,t,br(t));else if(Array.isArray(t))await Promise.all(t.map(r=>Ls(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>Ls(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Kn=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Ko=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Kn(s),Vo=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Xr(s,e,t){if(js(),s=await s,Ko(s))return s instanceof File?s:Et([await s.arrayBuffer()],s.name);if(Vo(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Et(await Bs(n),e,t)}let r=await Bs(s);if(e||(e=br(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Et(r,e,t)}async function Bs(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Kn(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Vr(s))for await(let t of s)e.push(...await Bs(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Xo(s)}`)}return e}function Xo(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var f=class{constructor(e){this._client=e}};function Xn(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Vn=Object.freeze(Object.create(null)),Go=(s=Xn)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],i=t.reduce((m,d,_)=>{/[?#]/.test(d)&&(n=!0);let h=r[_],A=(n?encodeURIComponent:s)(""+h);return _!==r.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Vn)??Vn)?.toString)&&(A=h+"",o.push({start:m.length+d.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),m+d+(_===r.length?"":A)},""),a=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=u.exec(a))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((m,d)=>m.start-d.start),o.length>0){let m=0,d=o.reduce((_,h)=>{let A=" ".repeat(h.start-m),b="^".repeat(h.length);return m=h.start+h.length,_+A+b},"");throw new y(`Path parameters result in path with invalid segments:
130
130
  ${o.map(_=>_.error).join(`
131
131
  `)}
132
132
  ${i}
133
- ${d}`)}return i},c=zo(Vn);var Ke=class extends f{list(e,t={},r){return this._client.getAPIList(c`/chat/completions/${e}/messages`,S,{query:t,...r})}};function wr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function xr(s){return s?.$brand==="auto-parseable-response-format"}function Ve(s){return s?.$brand==="auto-parseable-tool"}function Xn(s,e){return!e||!Bs(e)?{...s,choices:s.choices.map(t=>(Gn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ar(s,e)}function Ar(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new Pt;if(r.finish_reason==="content_filter")throw new Rt;return Gn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Zo(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Qo(e,r.message.content):null}}});return{...s,choices:t}}function Qo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function Zo(s,e){let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ve(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function zn(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return wr(t)&&(Ve(t)||t?.function.strict||!1)}function Bs(s){return xr(s.response_format)?!0:s.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Gn(s){for(let e of s||[])if(e.type!=="function")throw new y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Yn(s){for(let e of s??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var $t=s=>s?.role==="assistant",Us=s=>s?.role==="tool";var Ds,Gr,Yr,Ir,Sr,Qr,vr,de,Pr,Zr,es,kt,Qn,Ee=class{constructor(){Ds.add(this),this.controller=new AbortController,Gr.set(this,void 0),Yr.set(this,()=>{}),Ir.set(this,()=>{}),Sr.set(this,void 0),Qr.set(this,()=>{}),vr.set(this,()=>{}),de.set(this,{}),Pr.set(this,!1),Zr.set(this,!1),es.set(this,!1),kt.set(this,!1),x(this,Gr,new Promise((e,t)=>{x(this,Yr,e,"f"),x(this,Ir,t,"f")}),"f"),x(this,Sr,new Promise((e,t)=>{x(this,Qr,e,"f"),x(this,vr,t,"f")}),"f"),l(this,Gr,"f").catch(()=>{}),l(this,Sr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,Ds,"m",Qn).bind(this))},0)}_connected(){this.ended||(l(this,Yr,"f").call(this),this._emit("connect"))}get ended(){return l(this,Pr,"f")}get errored(){return l(this,Zr,"f")}get aborted(){return l(this,es,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,de,"f")[e]||(l(this,de,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,de,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(l(this,de,"f")[e]||(l(this,de,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,kt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,kt,!0,"f"),await l(this,Sr,"f")}_emit(e,...t){if(l(this,Pr,"f"))return;e==="end"&&(x(this,Pr,!0,"f"),l(this,Qr,"f").call(this));let r=l(this,de,"f")[e];if(r&&(l(this,de,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!l(this,kt,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!l(this,kt,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Gr=new WeakMap,Yr=new WeakMap,Ir=new WeakMap,Sr=new WeakMap,Qr=new WeakMap,vr=new WeakMap,de=new WeakMap,Pr=new WeakMap,Zr=new WeakMap,es=new WeakMap,kt=new WeakMap,Ds=new WeakSet,Qn=function(e){if(x(this,Zr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return x(this,es,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};function Zn(s){return typeof s.parse=="function"}var K,Hs,ts,Ws,qs,Js,eo,to,ei=10,Ot=class extends Ee{constructor(){super(...arguments),K.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let 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),Us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if($t(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,K,"m",Hs).call(this)}async finalMessage(){return await this.done(),l(this,K,"m",ts).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,K,"m",Ws).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,K,"m",qs).call(this)}async totalUsage(){return await this.done(),l(this,K,"m",Js).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,K,"m",ts).call(this);t&&this._emit("finalMessage",t);let r=l(this,K,"m",Hs).call(this);r&&this._emit("finalContent",r);let n=l(this,K,"m",Ws).call(this);n&&this._emit("finalFunctionToolCall",n);let o=l(this,K,"m",qs).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",l(this,K,"m",Js).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,K,"m",eo).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ar(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...a}=t,u=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:p=ei}=r||{},m=t.tools.map(h=>{if(Ve(h)){if(!h.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(let h of m)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);let _="tools"in t?m.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of t.messages)this._addMessage(h,!1);for(let h=0;h<p;++h){let b=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:_,messages:[...this.messages]},r)).choices[0]?.message;if(!b)throw new y("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(let R of b.tool_calls){if(R.type!=="function")continue;let v=R.id,{name:w,arguments:k}=R.function,P=d[w];if(P){if(u&&u!==w){let N=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:n,tool_call_id:v,content:N});continue}}else{let N=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(F=>JSON.stringify(F)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:v,content:N});continue}let E;try{E=Zn(P)?await P.parse(k):k}catch(N){let F=N instanceof Error?N.message:String(N);this._addMessage({role:n,tool_call_id:v,content:F});continue}let O=await P.function(E,this),C=l(this,K,"m",to).call(this,O);if(this._addMessage({role:n,tool_call_id:v,content:C}),u)return}}}};K=new WeakSet,Hs=function(){return l(this,K,"m",ts).call(this).content??null},ts=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if($t(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},Ws=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if($t(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},qs=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Us(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Js=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{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},eo=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},to=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Rr=class s extends Ot{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),$t(e)&&e.content&&this._emit("content",e.content)}};var H={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Ks=class extends Error{},Vs=class extends Error{};function ti(s,e=H.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ri(s.trim(),e)}var ri=(s,e)=>{let t=s.length,r=0,n=_=>{throw new Ks(`${_} at position ${r}`)},o=_=>{throw new Vs(`${_} at position ${r}`)},i=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?u():s[r]==="["?p():s.substring(r,r+4)==="null"||H.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||H.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||H.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||H.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||H.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||H.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):m()),a=()=>{let _=r,h=!1;for(r++;r<t&&(s[r]!=='"'||h&&s[r-1]==="\\");)h=s[r]==="\\"?!h:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(_,++r-Number(h)))}catch(A){o(String(A))}else if(H.STR&e)try{return JSON.parse(s.substring(_,r-Number(h))+'"')}catch{return JSON.parse(s.substring(_,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{r++,d();let _={};try{for(;s[r]!=="}";){if(d(),r>=t&&H.OBJ&e)return _;let h=a();d(),r++;try{let A=i();Object.defineProperty(_,h,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(H.OBJ&e)return _;throw A}d(),s[r]===","&&r++}}catch{if(H.OBJ&e)return _;n("Expected '}' at end of object")}return r++,_},p=()=>{r++;let _=[];try{for(;s[r]!=="]";)_.push(i()),d(),s[r]===","&&r++}catch{if(H.ARR&e)return _;n("Expected ']' at end of array")}return r++,_},m=()=>{if(r===0){s==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(h){if(H.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(h))}}let _=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(H.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(_,r))}catch{s.substring(_,r)==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(_,s.lastIndexOf("e")))}catch(A){o(String(A))}}},d=()=>{for(;r<t&&`
134
- \r `.includes(s[r]);)r++};return i()},Xs=s=>ti(s,H.ALL^H.NUM);var D,me,Tt,Ce,zs,rs,Gs,Ys,Qs,ss,Zs,ro,Xe=class s extends Ot{constructor(e){super(),D.add(this),me.set(this,void 0),Tt.set(this,void 0),Ce.set(this,void 0),x(this,me,e,"f"),x(this,Tt,[],"f")}get currentChatCompletionSnapshot(){return l(this,Ce,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,D,"m",zs).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)l(this,D,"m",Gs).call(this,i);if(o.controller.signal?.aborted)throw new L;return this._addChatCompletion(l(this,D,"m",ss).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),l(this,D,"m",zs).call(this),this._connected();let n=ae.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(l(this,D,"m",ss).call(this)),l(this,D,"m",Gs).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new L;return this._addChatCompletion(l(this,D,"m",ss).call(this))}[(me=new WeakMap,Tt=new WeakMap,Ce=new WeakMap,D=new WeakSet,zs=function(){this.ended||x(this,Ce,void 0,"f")},rs=function(t){let r=l(this,Tt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},l(this,Tt,"f")[t.index]=r,r)},Gs=function(t){if(this.ended)return;let r=l(this,D,"m",ro).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=l(this,D,"m",rs).call(this,o);o.finish_reason&&(l(this,D,"m",Qs).call(this,o),i.current_tool_call_index!=null&&l(this,D,"m",Ys).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(l(this,D,"m",Qs).call(this,o),i.current_tool_call_index!=null&&l(this,D,"m",Ys).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let u=o.message.tool_calls?.[a.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:a.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(u?.type,void 0))}}},Ys=function(t,r){if(l(this,D,"m",rs).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=l(this,me,"f")?.tools?.find(a=>wr(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ve(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Qs=function(t){let r=l(this,D,"m",rs).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=l(this,D,"m",Zs).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},ss=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,Ce,"f");if(!t)throw new y("request ended without sending any chunks");return x(this,Ce,void 0,"f"),x(this,Tt,[],"f"),si(t,l(this,me,"f"))},Zs=function(){let t=l(this,me,"f")?.response_format;return xr(t)?t:null},ro=function(t){var r,n,o,i;let a=l(this,Ce,"f"),{choices:u,...p}=t;a?Object.assign(a,p):a=x(this,Ce,{...p,choices:[]},"f");for(let{delta:m,finish_reason:d,index:_,logprobs:h=null,...A}of t.choices){let b=a.choices[_];if(b||(b=a.choices[_]={finish_reason:d,index:_,message:{},logprobs:h,...A}),h)if(!b.logprobs)b.logprobs=Object.assign({},h);else{let{content:O,refusal:C,...N}=h;Object.assign(b.logprobs,N),O&&((r=b.logprobs).content??(r.content=[]),b.logprobs.content.push(...O)),C&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...C))}if(d&&(b.finish_reason=d,l(this,me,"f")&&Bs(l(this,me,"f")))){if(d==="length")throw new Pt;if(d==="content_filter")throw new Rt}if(Object.assign(b,A),!m)continue;let{content:R,refusal:v,function_call:w,role:k,tool_calls:P,...E}=m;if(Object.assign(b.message,E),v&&(b.message.refusal=(b.message.refusal||"")+v),k&&(b.message.role=k),w&&(b.message.function_call?(w.name&&(b.message.function_call.name=w.name),w.arguments&&((o=b.message.function_call).arguments??(o.arguments=""),b.message.function_call.arguments+=w.arguments)):b.message.function_call=w),R&&(b.message.content=(b.message.content||"")+R,!b.message.refusal&&l(this,D,"m",Zs).call(this)&&(b.message.parsed=Xs(b.message.content))),P){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:O,id:C,type:N,function:F,...T}of P){let $=(i=b.message.tool_calls)[O]??(i[O]={});Object.assign($,T),C&&($.id=C),N&&($.type=N),F&&($.function??($.function={name:F.name??"",arguments:""})),F?.name&&($.function.name=F.name),F?.arguments&&($.function.arguments+=F.arguments,zn(l(this,me,"f"),$)&&($.function.parsed_arguments=Xs($.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function si(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...a}=s,u={...a,id:t,choices:r.map(({message:p,finish_reason:m,index:d,logprobs:_,...h})=>{if(!m)throw new y(`missing finish_reason for choice ${d}`);let{content:A=null,function_call:b,tool_calls:R,...v}=p,w=p.role;if(!w)throw new y(`missing role for choice ${d}`);if(b){let{arguments:k,name:P}=b;if(k==null)throw new y(`missing function_call.arguments for choice ${d}`);if(!P)throw new y(`missing function_call.name for choice ${d}`);return{...h,message:{content:A,function_call:{arguments:k,name:P},role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}return R?{...h,index:d,finish_reason:m,logprobs:_,message:{...v,role:w,content:A,refusal:p.refusal??null,tool_calls:R.map((k,P)=>{let{function:E,type:O,id:C,...N}=k,{arguments:F,name:T,...$}=E||{};if(C==null)throw new y(`missing choices[${d}].tool_calls[${P}].id
135
- ${ns(s)}`);if(O==null)throw new y(`missing choices[${d}].tool_calls[${P}].type
136
- ${ns(s)}`);if(T==null)throw new y(`missing choices[${d}].tool_calls[${P}].function.name
137
- ${ns(s)}`);if(F==null)throw new y(`missing choices[${d}].tool_calls[${P}].function.arguments
138
- ${ns(s)}`);return{...N,id:C,type:O,function:{...$,name:T,arguments:F}}})}}:{...h,message:{...v,content:A,role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Xn(u,e)}function ns(s){return JSON.stringify(s)}var Er=class s extends Xe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var ge=class extends f{constructor(){super(...arguments),this.messages=new Ke(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(c`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(c`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return Yn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ar(r,e))}runTools(e,t){return e.stream?Er.runTools(this._client,e,t):Rr.runTools(this._client,e,t)}stream(e,t){return Xe.createChatCompletion(this._client,e,t)}};ge.Messages=Ke;var $e=class extends f{constructor(){super(...arguments),this.completions=new ge(this._client)}};$e.Completions=ge;var so=Symbol("brand.privateNullableHeaders");function*oi(s){if(!s)return;if(so in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():xs(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=xs(r[1])?r[1]:[r[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var g=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of oi(r)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),t.add(a)):(e.append(o,i),t.delete(a))}}return{[so]:!0,values:e,nulls:t}};var Nt=class extends f{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var Ft=class extends f{create(e,t){return this._client.post("/audio/transcriptions",ee({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Mt=class extends f{create(e,t){return this._client.post("/audio/translations",ee({body:e,...t,__metadata:{model:e.model}},this._client))}};var ce=class extends f{constructor(){super(...arguments),this.transcriptions=new Ft(this._client),this.translations=new Mt(this._client),this.speech=new Nt(this._client)}};ce.Transcriptions=Ft;ce.Translations=Mt;ce.Speech=Nt;var ze=class extends f{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}};var Lt=class extends f{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/assistants/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var jt=class extends f{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Bt=class extends f{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var ke=class extends f{constructor(){super(...arguments),this.sessions=new jt(this._client),this.transcriptionSessions=new Bt(this._client)}};ke.Sessions=jt;ke.TranscriptionSessions=Bt;var Ut=class extends f{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Dt=class extends f{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",he,{query:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,he,{query:t,...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Oe=class extends f{constructor(){super(...arguments),this.sessions=new Ut(this._client),this.threads=new Dt(this._client)}};Oe.Sessions=Ut;Oe.Threads=Dt;var Ht=class extends f{create(e,t,r){return this._client.post(c`/threads/${e}/messages`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/messages/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/messages`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Wt=class extends f{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(c`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(c`/threads/${n}/runs/${e}/steps`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var no=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var Te=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()};var W,Ye,en,ue,os,te,Qe,qt,Ge,ls,Y,is,as,kr,Cr,$r,oo,io,ao,lo,co,uo,fo,_e=class extends Ee{constructor(){super(...arguments),W.add(this),en.set(this,[]),ue.set(this,{}),os.set(this,{}),te.set(this,void 0),Qe.set(this,void 0),qt.set(this,void 0),Ge.set(this,void 0),ls.set(this,void 0),Y.set(this,void 0),is.set(this,void 0),as.set(this,void 0),kr.set(this,void 0)}[(en=new WeakMap,ue=new WeakMap,os=new WeakMap,te=new WeakMap,Qe=new WeakMap,qt=new WeakMap,Ge=new WeakMap,ls=new WeakMap,Y=new WeakMap,is=new WeakMap,as=new WeakMap,kr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ye;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=ae.fromReadableStream(e,this.controller);for await(let o of n)l(this,W,"m",Cr).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}toReadableStream(){return new ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static createThreadAssistantStream(e,t,r){let n=new Ye;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,is,"f")}currentRun(){return l(this,as,"f")}currentMessageSnapshot(){return l(this,te,"f")}currentRunStepSnapshot(){return l(this,kr,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,ue,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,os,"f"))}async finalRun(){if(await this.done(),!l(this,Qe,"f"))throw Error("Final run was not received.");return l(this,Qe,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let a of i)l(this,W,"m",Cr).call(this,a);if(i.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(pr(o)&&pr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!pr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let u=o[a];u==null?o.push(i):o[a]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Ye=_e,Cr=function(e){if(!this.ended)switch(x(this,is,e,"f"),l(this,W,"m",ao).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":l(this,W,"m",fo).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":l(this,W,"m",io).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":l(this,W,"m",oo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},$r=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!l(this,Qe,"f"))throw Error("Final run has not been received");return l(this,Qe,"f")},oo=function(e){let[t,r]=l(this,W,"m",co).call(this,e,l(this,te,"f"));x(this,te,t,"f"),l(this,os,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=l(this,qt,"f")){if(l(this,Ge,"f"))switch(l(this,Ge,"f").type){case"text":this._emit("textDone",l(this,Ge,"f").text,l(this,te,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Ge,"f").image_file,l(this,te,"f"));break}x(this,qt,n.index,"f")}x(this,Ge,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,qt,"f")!==void 0){let n=e.data.content[l(this,qt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,l(this,te,"f"));break;case"text":this._emit("textDone",n.text,l(this,te,"f"));break}}l(this,te,"f")&&this._emit("messageDone",e.data),x(this,te,void 0,"f")}},io=function(e){let t=l(this,W,"m",lo).call(this,e);switch(x(this,kr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==l(this,ls,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,Y,"f")&&this._emit("toolCallDone",l(this,Y,"f")),x(this,ls,o.index,"f"),x(this,Y,t.step_details.tool_calls[o.index],"f"),l(this,Y,"f")&&this._emit("toolCallCreated",l(this,Y,"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":x(this,kr,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},ao=function(e){l(this,en,"f").push(e),this._emit("event",e)},lo=function(e){switch(e.event){case"thread.run.step.created":return l(this,ue,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,ue,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Ye.accumulateDelta(t,r.delta);l(this,ue,"f")[e.data.id]=n}return l(this,ue,"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":l(this,ue,"f")[e.data.id]=e.data;break}if(l(this,ue,"f")[e.data.id])return l(this,ue,"f")[e.data.id];throw new Error("No snapshot available")},co=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];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(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=l(this,W,"m",uo).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},uo=function(e,t){return Ye.accumulateDelta(t,e)},fo=function(e){switch(x(this,as,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,Qe,e.data,"f"),l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f"));break;case"thread.run.cancelling":break}};var Ze=class extends f{constructor(){super(...arguments),this.steps=new Wt(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/runs/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/runs`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(c`/threads/${n}/runs/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await oe(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return _e.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ze.Steps=Wt;var Ne=class extends f{constructor(){super(...arguments),this.runs=new Ze(this._client),this.messages=new Ht(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/threads/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ne.Runs=Ze;Ne.Messages=Ht;var re=class extends f{constructor(){super(...arguments),this.realtime=new ke(this._client),this.chatkit=new Oe(this._client),this.assistants=new Lt(this._client),this.threads=new Ne(this._client)}};re.Realtime=ke;re.ChatKit=Oe;re.Assistants=Lt;re.Threads=Ne;var et=class extends f{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Jt=class extends f{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var tt=class extends f{constructor(){super(...arguments),this.content=new Jt(this._client)}create(e,t,r){return this._client.post(c`/containers/${e}/files`,pe({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/containers/${e}/files`,S,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(c`/containers/${n}/files/${e}`,{...r,headers:g([{Accept:"*/*"},r?.headers])})}};tt.Content=Jt;var Fe=class extends f{constructor(){super(...arguments),this.files=new tt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Fe.Files=tt;var Kt=class extends f{create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:n},body:o,...r})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(c`/conversations/${n}/items/${e}`,{query:o,...r})}list(e,t={},r){return this._client.getAPIList(c`/conversations/${e}/items`,he,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(c`/conversations/${n}/items/${e}`,r)}};var Me=class extends f{constructor(){super(...arguments),this.items=new Kt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,r){return this._client.post(c`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}};Me.Items=Kt;var rt=class extends f{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&M(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(M(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let u=a.embedding;a.embedding=no(u)}),i)))}};var Vt=class extends f{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(c`/evals/${n}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(c`/evals/${n}/runs/${e}/output_items`,S,{query:o,...r})}};var st=class extends f{constructor(){super(...arguments),this.outputItems=new Vt(this._client)}create(e,t,r){return this._client.post(c`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(c`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/evals/${e}/runs`,S,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(c`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(c`/evals/${n}/runs/${e}`,r)}};st.OutputItems=Vt;var Le=class extends f{constructor(){super(...arguments),this.runs=new st(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,r){return this._client.post(c`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}};Le.Runs=st;var nt=class extends f{create(e,t){return this._client.post("/files",ee({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await oe(t),i=await this.retrieve(e),Date.now()-o>r)throw new Pe({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Xt=class extends f{};var zt=class extends f{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})}};var ot=class extends f{constructor(){super(...arguments),this.graders=new zt(this._client)}};ot.Graders=zt;var Gt=class extends f{create(e,t,r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,le,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(c`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}};var it=class extends f{constructor(){super(...arguments),this.permissions=new Gt(this._client)}};it.Permissions=Gt;var Yt=class extends f{list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r})}};var at=class extends f{constructor(){super(...arguments),this.checkpoints=new Yt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,S,{query:t,...r})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}};at.Checkpoints=Yt;var se=class extends f{constructor(){super(...arguments),this.methods=new Xt(this._client),this.jobs=new at(this._client),this.checkpoints=new it(this._client),this.alpha=new ot(this._client)}};se.Methods=Xt;se.Jobs=at;se.Checkpoints=it;se.Alpha=ot;var Qt=class extends f{};var je=class extends f{constructor(){super(...arguments),this.graderModels=new Qt(this._client)}};je.GraderModels=Qt;var lt=class extends f{createVariation(e,t){return this._client.post("/images/variations",ee({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",ee({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})}};var ct=class extends f{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",le,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}};var ut=class extends f{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Zt=class extends f{accept(e,t,r){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}};var er=class extends f{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var ye=class extends f{constructor(){super(...arguments),this.clientSecrets=new er(this._client),this.calls=new Zt(this._client)}};ye.ClientSecrets=er;ye.Calls=Zt;function ho(s,e){return!e||!Mi(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:tn(s,e)}function tn(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Bi(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Fi(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||cs(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Fi(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Mi(s){return!!xr(s.text?.format)}function Li(s){return s?.$brand==="auto-parseable-tool"}function ji(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Bi(s,e){let t=ji(s.tools??[],e.name);return{...e,...e,parsed_arguments:Li(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function cs(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var tr,us,Be,fs,po,mo,go,_o,hs=class s extends Ee{constructor(e){super(),tr.add(this),us.set(this,void 0),Be.set(this,void 0),fs.set(this,void 0),x(this,us,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,tr,"m",po).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of o)l(this,tr,"m",mo).call(this,a,i);if(o.controller.signal?.aborted)throw new L;return l(this,tr,"m",go).call(this)}[(us=new WeakMap,Be=new WeakMap,fs=new WeakMap,tr=new WeakSet,po=function(){this.ended||x(this,Be,void 0,"f")},mo=function(t,r){if(this.ended)return;let n=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=l(this,tr,"m",_o).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new y(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new y(`expected content to be 'output_text', got ${a.type}`);n("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},go=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,Be,"f");if(!t)throw new y("request ended without sending any events");x(this,Be,void 0,"f");let r=Ui(t,l(this,us,"f"));return x(this,fs,r,"f"),r},_o=function(t){let r=l(this,Be,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=x(this,Be,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new y(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{x(this,Be,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=l(this,fs,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function Ui(s,e){return ho(s,e)}var rr=class extends f{list(e,t={},r){return this._client.getAPIList(c`/responses/${e}/input_items`,S,{query:t,...r})}};var sr=class extends f{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var be=class extends f{constructor(){super(...arguments),this.inputItems=new rr(this._client),this.inputTokens=new sr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&cs(r),r))}retrieve(e,t={},r){return this._client.get(c`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&cs(n),n))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>tn(r,e))}stream(e,t){return hs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};be.InputItems=rr;be.InputTokens=sr;var nr=class extends f{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var or=class extends f{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var ft=class extends f{constructor(){super(...arguments),this.content=new or(this._client)}create(e,t={},r){return this._client.post(c`/skills/${e}/versions`,pe({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/skills/${e}/versions`,S,{query:t,...r})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(c`/skills/${n}/versions/${e}`,r)}};ft.Content=or;var we=class extends f{constructor(){super(...arguments),this.content=new nr(this._client),this.versions=new ft(this._client)}create(e={},t){return this._client.post("/skills",pe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,r){return this._client.post(c`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}};we.Content=nr;we.Versions=ft;var ir=class extends f{create(e,t,r){return this._client.post(c`/uploads/${e}/parts`,ee({body:t,...r},this._client))}};var Ue=class extends f{constructor(){super(...arguments),this.parts=new ir(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(c`/uploads/${e}/complete`,{body:t,...r})}};Ue.Parts=ir;var yo=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var ar=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/file_batches/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(c`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(c`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await oe(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),a=this._client,u=t.values(),p=[...r];async function m(_){for(let h of _){let A=await a.files.create({file:h,purpose:"assistants"},n);p.push(A.id)}}let d=Array(i).fill(u).map(m);return await yo(d),await this.createAndPoll(e,{file_ids:p})}};var lr=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(c`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/vector_stores/${e}/files`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await oe(a);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(c`/vector_stores/${n}/files/${e}/content`,le,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var xe=class extends f{constructor(){super(...arguments),this.files=new lr(this._client),this.fileBatches=new ar(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/vector_stores/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(c`/vector_stores/${e}/search`,le,{body:t,method:"post",...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};xe.Files=lr;xe.FileBatches=ar;var ht=class extends f{create(e,t){return this._client.post("/videos",pe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",he,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(c`/videos/${e}/content`,{query:t,...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(c`/videos/${e}/remix`,pe({body:t,...r},this._client))}};var cr,bo,ps,pt=class extends f{constructor(){super(...arguments),cr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,cr,"m",bo).call(this,r);let o=g([t]).values,i=l(this,cr,"m",ps).call(this,o,"webhook-signature"),a=l(this,cr,"m",ps).call(this,o,"webhook-timestamp"),u=l(this,cr,"m",ps).call(this,o,"webhook-id"),p=parseInt(a,10);if(isNaN(p))throw new ne("Invalid webhook timestamp format");let m=Math.floor(Date.now()/1e3);if(m-p>n)throw new ne("Webhook timestamp is too old");if(p>m+n)throw new ne("Webhook timestamp is too new");let d=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),_=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=u?`${u}.${a}.${e}`:`${a}.${e}`,A=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of d)try{let R=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",A,R,new TextEncoder().encode(h)))return}catch{continue}throw new ne("The given webhook signature does not match the expected signature")}};cr=new WeakSet,bo=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},ps=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var rn,sn,ds,wo,I=class{constructor({baseURL:e=Te("OPENAI_BASE_URL"),apiKey:t=Te("OPENAI_API_KEY"),organization:r=Te("OPENAI_ORG_ID")??null,project:n=Te("OPENAI_PROJECT_ID")??null,webhookSecret:o=Te("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(rn.add(this),ds.set(this,void 0),this.completions=new et(this),this.chat=new $e(this),this.embeddings=new rt(this),this.files=new nt(this),this.images=new lt(this),this.audio=new ce(this),this.moderations=new ut(this),this.models=new ct(this),this.fineTuning=new se(this),this.graders=new je(this),this.vectorStores=new xe(this),this.webhooks=new pt(this),this.beta=new re(this),this.batches=new ze(this),this.uploads=new Ue(this),this.responses=new be(this),this.realtime=new ye(this),this.conversations=new Me(this),this.evals=new Le(this),this.containers=new Fe(this),this.skills=new we(this),this.videos=new ht(this),t===void 0)throw new y("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Pn())throw new y(`It looks like you're running in a browser-like environment.
133
+ ${d}`)}return i},c=Go(Xn);var Ke=class extends f{list(e,t={},r){return this._client.getAPIList(c`/chat/completions/${e}/messages`,S,{query:t,...r})}};function wr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function xr(s){return s?.$brand==="auto-parseable-response-format"}function Ve(s){return s?.$brand==="auto-parseable-tool"}function zn(s,e){return!e||!Us(e)?{...s,choices:s.choices.map(t=>(Yn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ar(s,e)}function Ar(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new vt;if(r.finish_reason==="content_filter")throw new Pt;return Yn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>ei(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Zo(e,r.message.content):null}}});return{...s,choices:t}}function Zo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function ei(s,e){let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ve(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Gn(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return wr(t)&&(Ve(t)||t?.function.strict||!1)}function Us(s){return xr(s.response_format)?!0:s.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Yn(s){for(let e of s||[])if(e.type!=="function")throw new y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Qn(s){for(let e of s??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Ct=s=>s?.role==="assistant",Ds=s=>s?.role==="tool";var Hs,zr,Gr,Ir,Sr,Yr,vr,me,Pr,Qr,Zr,$t,Zn,$e=class{constructor(){Hs.add(this),this.controller=new AbortController,zr.set(this,void 0),Gr.set(this,()=>{}),Ir.set(this,()=>{}),Sr.set(this,void 0),Yr.set(this,()=>{}),vr.set(this,()=>{}),me.set(this,{}),Pr.set(this,!1),Qr.set(this,!1),Zr.set(this,!1),$t.set(this,!1),x(this,zr,new Promise((e,t)=>{x(this,Gr,e,"f"),x(this,Ir,t,"f")}),"f"),x(this,Sr,new Promise((e,t)=>{x(this,Yr,e,"f"),x(this,vr,t,"f")}),"f"),l(this,zr,"f").catch(()=>{}),l(this,Sr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,Hs,"m",Zn).bind(this))},0)}_connected(){this.ended||(l(this,Gr,"f").call(this),this._emit("connect"))}get ended(){return l(this,Pr,"f")}get errored(){return l(this,Qr,"f")}get aborted(){return l(this,Zr,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,me,"f")[e]||(l(this,me,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,me,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(l(this,me,"f")[e]||(l(this,me,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,$t,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,$t,!0,"f"),await l(this,Sr,"f")}_emit(e,...t){if(l(this,Pr,"f"))return;e==="end"&&(x(this,Pr,!0,"f"),l(this,Yr,"f").call(this));let r=l(this,me,"f")[e];if(r&&(l(this,me,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!l(this,$t,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!l(this,$t,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};zr=new WeakMap,Gr=new WeakMap,Ir=new WeakMap,Sr=new WeakMap,Yr=new WeakMap,vr=new WeakMap,me=new WeakMap,Pr=new WeakMap,Qr=new WeakMap,Zr=new WeakMap,$t=new WeakMap,Hs=new WeakSet,Zn=function(e){if(x(this,Qr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return x(this,Zr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};function eo(s){return typeof s.parse=="function"}var X,Ws,es,qs,Js,Ks,to,ro,ti=10,kt=class extends $e{constructor(){super(...arguments),X.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let 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),Ds(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ct(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,X,"m",Ws).call(this)}async finalMessage(){return await this.done(),l(this,X,"m",es).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,X,"m",qs).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,X,"m",Js).call(this)}async totalUsage(){return await this.done(),l(this,X,"m",Ks).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,X,"m",es).call(this);t&&this._emit("finalMessage",t);let r=l(this,X,"m",Ws).call(this);r&&this._emit("finalContent",r);let n=l(this,X,"m",qs).call(this);n&&this._emit("finalFunctionToolCall",n);let o=l(this,X,"m",Js).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",l(this,X,"m",Ks).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,X,"m",to).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ar(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...a}=t,u=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:p=ti}=r||{},m=t.tools.map(h=>{if(Ve(h)){if(!h.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(let h of m)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);let _="tools"in t?m.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of t.messages)this._addMessage(h,!1);for(let h=0;h<p;++h){let b=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:_,messages:[...this.messages]},r)).choices[0]?.message;if(!b)throw new y("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(let R of b.tool_calls){if(R.type!=="function")continue;let v=R.id,{name:w,arguments:k}=R.function,P=d[w];if(P){if(u&&u!==w){let N=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:n,tool_call_id:v,content:N});continue}}else{let N=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(F=>JSON.stringify(F)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:v,content:N});continue}let E;try{E=eo(P)?await P.parse(k):k}catch(N){let F=N instanceof Error?N.message:String(N);this._addMessage({role:n,tool_call_id:v,content:F});continue}let O=await P.function(E,this),C=l(this,X,"m",ro).call(this,O);if(this._addMessage({role:n,tool_call_id:v,content:C}),u)return}}}};X=new WeakSet,Ws=function(){return l(this,X,"m",es).call(this).content??null},es=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Ct(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},qs=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ct(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Js=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ds(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Ks=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{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},to=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ro=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Rr=class s extends kt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Ct(e)&&e.content&&this._emit("content",e.content)}};var H={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Vs=class extends Error{},Xs=class extends Error{};function ri(s,e=H.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return si(s.trim(),e)}var si=(s,e)=>{let t=s.length,r=0,n=_=>{throw new Vs(`${_} at position ${r}`)},o=_=>{throw new Xs(`${_} at position ${r}`)},i=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?u():s[r]==="["?p():s.substring(r,r+4)==="null"||H.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||H.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||H.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||H.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||H.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||H.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):m()),a=()=>{let _=r,h=!1;for(r++;r<t&&(s[r]!=='"'||h&&s[r-1]==="\\");)h=s[r]==="\\"?!h:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(_,++r-Number(h)))}catch(A){o(String(A))}else if(H.STR&e)try{return JSON.parse(s.substring(_,r-Number(h))+'"')}catch{return JSON.parse(s.substring(_,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{r++,d();let _={};try{for(;s[r]!=="}";){if(d(),r>=t&&H.OBJ&e)return _;let h=a();d(),r++;try{let A=i();Object.defineProperty(_,h,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(H.OBJ&e)return _;throw A}d(),s[r]===","&&r++}}catch{if(H.OBJ&e)return _;n("Expected '}' at end of object")}return r++,_},p=()=>{r++;let _=[];try{for(;s[r]!=="]";)_.push(i()),d(),s[r]===","&&r++}catch{if(H.ARR&e)return _;n("Expected ']' at end of array")}return r++,_},m=()=>{if(r===0){s==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(h){if(H.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(h))}}let _=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(H.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(_,r))}catch{s.substring(_,r)==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(_,s.lastIndexOf("e")))}catch(A){o(String(A))}}},d=()=>{for(;r<t&&`
134
+ \r `.includes(s[r]);)r++};return i()},zs=s=>ri(s,H.ALL^H.NUM);var D,ge,Ot,ke,Gs,ts,Ys,Qs,Zs,rs,en,so,Xe=class s extends kt{constructor(e){super(),D.add(this),ge.set(this,void 0),Ot.set(this,void 0),ke.set(this,void 0),x(this,ge,e,"f"),x(this,Ot,[],"f")}get currentChatCompletionSnapshot(){return l(this,ke,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,D,"m",Gs).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)l(this,D,"m",Ys).call(this,i);if(o.controller.signal?.aborted)throw new L;return this._addChatCompletion(l(this,D,"m",rs).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),l(this,D,"m",Gs).call(this),this._connected();let n=le.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(l(this,D,"m",rs).call(this)),l(this,D,"m",Ys).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new L;return this._addChatCompletion(l(this,D,"m",rs).call(this))}[(ge=new WeakMap,Ot=new WeakMap,ke=new WeakMap,D=new WeakSet,Gs=function(){this.ended||x(this,ke,void 0,"f")},ts=function(t){let r=l(this,Ot,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},l(this,Ot,"f")[t.index]=r,r)},Ys=function(t){if(this.ended)return;let r=l(this,D,"m",so).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=l(this,D,"m",ts).call(this,o);o.finish_reason&&(l(this,D,"m",Zs).call(this,o),i.current_tool_call_index!=null&&l(this,D,"m",Qs).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(l(this,D,"m",Zs).call(this,o),i.current_tool_call_index!=null&&l(this,D,"m",Qs).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let u=o.message.tool_calls?.[a.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:a.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(u?.type,void 0))}}},Qs=function(t,r){if(l(this,D,"m",ts).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=l(this,ge,"f")?.tools?.find(a=>wr(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ve(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Zs=function(t){let r=l(this,D,"m",ts).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=l(this,D,"m",en).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},rs=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,ke,"f");if(!t)throw new y("request ended without sending any chunks");return x(this,ke,void 0,"f"),x(this,Ot,[],"f"),ni(t,l(this,ge,"f"))},en=function(){let t=l(this,ge,"f")?.response_format;return xr(t)?t:null},so=function(t){var r,n,o,i;let a=l(this,ke,"f"),{choices:u,...p}=t;a?Object.assign(a,p):a=x(this,ke,{...p,choices:[]},"f");for(let{delta:m,finish_reason:d,index:_,logprobs:h=null,...A}of t.choices){let b=a.choices[_];if(b||(b=a.choices[_]={finish_reason:d,index:_,message:{},logprobs:h,...A}),h)if(!b.logprobs)b.logprobs=Object.assign({},h);else{let{content:O,refusal:C,...N}=h;Object.assign(b.logprobs,N),O&&((r=b.logprobs).content??(r.content=[]),b.logprobs.content.push(...O)),C&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...C))}if(d&&(b.finish_reason=d,l(this,ge,"f")&&Us(l(this,ge,"f")))){if(d==="length")throw new vt;if(d==="content_filter")throw new Pt}if(Object.assign(b,A),!m)continue;let{content:R,refusal:v,function_call:w,role:k,tool_calls:P,...E}=m;if(Object.assign(b.message,E),v&&(b.message.refusal=(b.message.refusal||"")+v),k&&(b.message.role=k),w&&(b.message.function_call?(w.name&&(b.message.function_call.name=w.name),w.arguments&&((o=b.message.function_call).arguments??(o.arguments=""),b.message.function_call.arguments+=w.arguments)):b.message.function_call=w),R&&(b.message.content=(b.message.content||"")+R,!b.message.refusal&&l(this,D,"m",en).call(this)&&(b.message.parsed=zs(b.message.content))),P){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:O,id:C,type:N,function:F,...T}of P){let $=(i=b.message.tool_calls)[O]??(i[O]={});Object.assign($,T),C&&($.id=C),N&&($.type=N),F&&($.function??($.function={name:F.name??"",arguments:""})),F?.name&&($.function.name=F.name),F?.arguments&&($.function.arguments+=F.arguments,Gn(l(this,ge,"f"),$)&&($.function.parsed_arguments=zs($.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function ni(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...a}=s,u={...a,id:t,choices:r.map(({message:p,finish_reason:m,index:d,logprobs:_,...h})=>{if(!m)throw new y(`missing finish_reason for choice ${d}`);let{content:A=null,function_call:b,tool_calls:R,...v}=p,w=p.role;if(!w)throw new y(`missing role for choice ${d}`);if(b){let{arguments:k,name:P}=b;if(k==null)throw new y(`missing function_call.arguments for choice ${d}`);if(!P)throw new y(`missing function_call.name for choice ${d}`);return{...h,message:{content:A,function_call:{arguments:k,name:P},role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}return R?{...h,index:d,finish_reason:m,logprobs:_,message:{...v,role:w,content:A,refusal:p.refusal??null,tool_calls:R.map((k,P)=>{let{function:E,type:O,id:C,...N}=k,{arguments:F,name:T,...$}=E||{};if(C==null)throw new y(`missing choices[${d}].tool_calls[${P}].id
135
+ ${ss(s)}`);if(O==null)throw new y(`missing choices[${d}].tool_calls[${P}].type
136
+ ${ss(s)}`);if(T==null)throw new y(`missing choices[${d}].tool_calls[${P}].function.name
137
+ ${ss(s)}`);if(F==null)throw new y(`missing choices[${d}].tool_calls[${P}].function.arguments
138
+ ${ss(s)}`);return{...N,id:C,type:O,function:{...$,name:T,arguments:F}}})}}:{...h,message:{...v,content:A,role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return zn(u,e)}function ss(s){return JSON.stringify(s)}var Er=class s extends Xe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var _e=class extends f{constructor(){super(...arguments),this.messages=new Ke(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(c`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(c`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return Qn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ar(r,e))}runTools(e,t){return e.stream?Er.runTools(this._client,e,t):Rr.runTools(this._client,e,t)}stream(e,t){return Xe.createChatCompletion(this._client,e,t)}};_e.Messages=Ke;var Oe=class extends f{constructor(){super(...arguments),this.completions=new _e(this._client)}};Oe.Completions=_e;var no=Symbol("brand.privateNullableHeaders");function*ii(s){if(!s)return;if(no in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():As(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=As(r[1])?r[1]:[r[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var g=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of ii(r)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),t.add(a)):(e.append(o,i),t.delete(a))}}return{[no]:!0,values:e,nulls:t}};var Tt=class extends f{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var Nt=class extends f{create(e,t){return this._client.post("/audio/transcriptions",te({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Ft=class extends f{create(e,t){return this._client.post("/audio/translations",te({body:e,...t,__metadata:{model:e.model}},this._client))}};var ue=class extends f{constructor(){super(...arguments),this.transcriptions=new Nt(this._client),this.translations=new Ft(this._client),this.speech=new Tt(this._client)}};ue.Transcriptions=Nt;ue.Translations=Ft;ue.Speech=Tt;var ze=class extends f{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}};var Mt=class extends f{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/assistants/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Lt=class extends f{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var jt=class extends f{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Te=class extends f{constructor(){super(...arguments),this.sessions=new Lt(this._client),this.transcriptionSessions=new jt(this._client)}};Te.Sessions=Lt;Te.TranscriptionSessions=jt;var Bt=class extends f{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Ut=class extends f{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",pe,{query:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,pe,{query:t,...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Ne=class extends f{constructor(){super(...arguments),this.sessions=new Bt(this._client),this.threads=new Ut(this._client)}};Ne.Sessions=Bt;Ne.Threads=Ut;var Dt=class extends f{create(e,t,r){return this._client.post(c`/threads/${e}/messages`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/messages/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/messages`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ht=class extends f{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(c`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(c`/threads/${n}/runs/${e}/steps`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var oo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var Fe=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()};var W,Ye,tn,fe,ns,re,Qe,Wt,Ge,as,Y,os,is,kr,Cr,$r,io,ao,lo,co,uo,fo,ho,ye=class extends $e{constructor(){super(...arguments),W.add(this),tn.set(this,[]),fe.set(this,{}),ns.set(this,{}),re.set(this,void 0),Qe.set(this,void 0),Wt.set(this,void 0),Ge.set(this,void 0),as.set(this,void 0),Y.set(this,void 0),os.set(this,void 0),is.set(this,void 0),kr.set(this,void 0)}[(tn=new WeakMap,fe=new WeakMap,ns=new WeakMap,re=new WeakMap,Qe=new WeakMap,Wt=new WeakMap,Ge=new WeakMap,as=new WeakMap,Y=new WeakMap,os=new WeakMap,is=new WeakMap,kr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ye;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=le.fromReadableStream(e,this.controller);for await(let o of n)l(this,W,"m",Cr).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static createThreadAssistantStream(e,t,r){let n=new Ye;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,os,"f")}currentRun(){return l(this,is,"f")}currentMessageSnapshot(){return l(this,re,"f")}currentRunStepSnapshot(){return l(this,kr,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,fe,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,ns,"f"))}async finalRun(){if(await this.done(),!l(this,Qe,"f"))throw Error("Final run was not received.");return l(this,Qe,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let a of i)l(this,W,"m",Cr).call(this,a);if(i.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(pr(o)&&pr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!pr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let u=o[a];u==null?o.push(i):o[a]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Ye=ye,Cr=function(e){if(!this.ended)switch(x(this,os,e,"f"),l(this,W,"m",lo).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":l(this,W,"m",ho).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":l(this,W,"m",ao).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":l(this,W,"m",io).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},$r=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!l(this,Qe,"f"))throw Error("Final run has not been received");return l(this,Qe,"f")},io=function(e){let[t,r]=l(this,W,"m",uo).call(this,e,l(this,re,"f"));x(this,re,t,"f"),l(this,ns,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=l(this,Wt,"f")){if(l(this,Ge,"f"))switch(l(this,Ge,"f").type){case"text":this._emit("textDone",l(this,Ge,"f").text,l(this,re,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Ge,"f").image_file,l(this,re,"f"));break}x(this,Wt,n.index,"f")}x(this,Ge,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,Wt,"f")!==void 0){let n=e.data.content[l(this,Wt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,l(this,re,"f"));break;case"text":this._emit("textDone",n.text,l(this,re,"f"));break}}l(this,re,"f")&&this._emit("messageDone",e.data),x(this,re,void 0,"f")}},ao=function(e){let t=l(this,W,"m",co).call(this,e);switch(x(this,kr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==l(this,as,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,Y,"f")&&this._emit("toolCallDone",l(this,Y,"f")),x(this,as,o.index,"f"),x(this,Y,t.step_details.tool_calls[o.index],"f"),l(this,Y,"f")&&this._emit("toolCallCreated",l(this,Y,"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":x(this,kr,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},lo=function(e){l(this,tn,"f").push(e),this._emit("event",e)},co=function(e){switch(e.event){case"thread.run.step.created":return l(this,fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,fe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Ye.accumulateDelta(t,r.delta);l(this,fe,"f")[e.data.id]=n}return l(this,fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":l(this,fe,"f")[e.data.id]=e.data;break}if(l(this,fe,"f")[e.data.id])return l(this,fe,"f")[e.data.id];throw new Error("No snapshot available")},uo=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];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(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=l(this,W,"m",fo).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},fo=function(e,t){return Ye.accumulateDelta(t,e)},ho=function(e){switch(x(this,is,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,Qe,e.data,"f"),l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f"));break;case"thread.run.cancelling":break}};var Ze=class extends f{constructor(){super(...arguments),this.steps=new Ht(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/runs/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/runs`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(c`/threads/${n}/runs/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return ye.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ze.Steps=Ht;var Me=class extends f{constructor(){super(...arguments),this.runs=new Ze(this._client),this.messages=new Dt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/threads/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return ye.createThreadAssistantStream(e,this._client.beta.threads,t)}};Me.Runs=Ze;Me.Messages=Dt;var se=class extends f{constructor(){super(...arguments),this.realtime=new Te(this._client),this.chatkit=new Ne(this._client),this.assistants=new Mt(this._client),this.threads=new Me(this._client)}};se.Realtime=Te;se.ChatKit=Ne;se.Assistants=Mt;se.Threads=Me;var et=class extends f{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var qt=class extends f{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var tt=class extends f{constructor(){super(...arguments),this.content=new qt(this._client)}create(e,t,r){return this._client.post(c`/containers/${e}/files`,de({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/containers/${e}/files`,S,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(c`/containers/${n}/files/${e}`,{...r,headers:g([{Accept:"*/*"},r?.headers])})}};tt.Content=qt;var Le=class extends f{constructor(){super(...arguments),this.files=new tt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Le.Files=tt;var Jt=class extends f{create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:n},body:o,...r})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(c`/conversations/${n}/items/${e}`,{query:o,...r})}list(e,t={},r){return this._client.getAPIList(c`/conversations/${e}/items`,pe,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(c`/conversations/${n}/items/${e}`,r)}};var je=class extends f{constructor(){super(...arguments),this.items=new Jt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,r){return this._client.post(c`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}};je.Items=Jt;var rt=class extends f{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&M(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(M(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let u=a.embedding;a.embedding=oo(u)}),i)))}};var Kt=class extends f{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(c`/evals/${n}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(c`/evals/${n}/runs/${e}/output_items`,S,{query:o,...r})}};var st=class extends f{constructor(){super(...arguments),this.outputItems=new Kt(this._client)}create(e,t,r){return this._client.post(c`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(c`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/evals/${e}/runs`,S,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(c`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(c`/evals/${n}/runs/${e}`,r)}};st.OutputItems=Kt;var Be=class extends f{constructor(){super(...arguments),this.runs=new st(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,r){return this._client.post(c`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}};Be.Runs=st;var nt=class extends f{create(e,t){return this._client.post("/files",te({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ie(t),i=await this.retrieve(e),Date.now()-o>r)throw new Ee({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Vt=class extends f{};var Xt=class extends f{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})}};var ot=class extends f{constructor(){super(...arguments),this.graders=new Xt(this._client)}};ot.Graders=Xt;var zt=class extends f{create(e,t,r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ce,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(c`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}};var it=class extends f{constructor(){super(...arguments),this.permissions=new zt(this._client)}};it.Permissions=zt;var Gt=class extends f{list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r})}};var at=class extends f{constructor(){super(...arguments),this.checkpoints=new Gt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,S,{query:t,...r})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}};at.Checkpoints=Gt;var ne=class extends f{constructor(){super(...arguments),this.methods=new Vt(this._client),this.jobs=new at(this._client),this.checkpoints=new it(this._client),this.alpha=new ot(this._client)}};ne.Methods=Vt;ne.Jobs=at;ne.Checkpoints=it;ne.Alpha=ot;var Yt=class extends f{};var Ue=class extends f{constructor(){super(...arguments),this.graderModels=new Yt(this._client)}};Ue.GraderModels=Yt;var lt=class extends f{createVariation(e,t){return this._client.post("/images/variations",te({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",te({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})}};var ct=class extends f{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ce,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}};var ut=class extends f{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Qt=class extends f{accept(e,t,r){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}};var Zt=class extends f{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var be=class extends f{constructor(){super(...arguments),this.clientSecrets=new Zt(this._client),this.calls=new Qt(this._client)}};be.ClientSecrets=Zt;be.Calls=Qt;function po(s,e){return!e||!Li(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:rn(s,e)}function rn(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Ui(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Mi(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||ls(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Mi(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Li(s){return!!xr(s.text?.format)}function ji(s){return s?.$brand==="auto-parseable-tool"}function Bi(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Ui(s,e){let t=Bi(s.tools??[],e.name);return{...e,...e,parsed_arguments:ji(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ls(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var er,cs,De,us,mo,go,_o,yo,fs=class s extends $e{constructor(e){super(),er.add(this),cs.set(this,void 0),De.set(this,void 0),us.set(this,void 0),x(this,cs,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,er,"m",mo).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of o)l(this,er,"m",go).call(this,a,i);if(o.controller.signal?.aborted)throw new L;return l(this,er,"m",_o).call(this)}[(cs=new WeakMap,De=new WeakMap,us=new WeakMap,er=new WeakSet,mo=function(){this.ended||x(this,De,void 0,"f")},go=function(t,r){if(this.ended)return;let n=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=l(this,er,"m",yo).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new y(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new y(`expected content to be 'output_text', got ${a.type}`);n("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},_o=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,De,"f");if(!t)throw new y("request ended without sending any events");x(this,De,void 0,"f");let r=Di(t,l(this,cs,"f"));return x(this,us,r,"f"),r},yo=function(t){let r=l(this,De,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=x(this,De,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new y(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{x(this,De,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=l(this,us,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function Di(s,e){return po(s,e)}var tr=class extends f{list(e,t={},r){return this._client.getAPIList(c`/responses/${e}/input_items`,S,{query:t,...r})}};var rr=class extends f{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var we=class extends f{constructor(){super(...arguments),this.inputItems=new tr(this._client),this.inputTokens=new rr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ls(r),r))}retrieve(e,t={},r){return this._client.get(c`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ls(n),n))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>rn(r,e))}stream(e,t){return fs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};we.InputItems=tr;we.InputTokens=rr;var sr=class extends f{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var nr=class extends f{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var ft=class extends f{constructor(){super(...arguments),this.content=new nr(this._client)}create(e,t={},r){return this._client.post(c`/skills/${e}/versions`,de({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/skills/${e}/versions`,S,{query:t,...r})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(c`/skills/${n}/versions/${e}`,r)}};ft.Content=nr;var xe=class extends f{constructor(){super(...arguments),this.content=new sr(this._client),this.versions=new ft(this._client)}create(e={},t){return this._client.post("/skills",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,r){return this._client.post(c`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}};xe.Content=sr;xe.Versions=ft;var or=class extends f{create(e,t,r){return this._client.post(c`/uploads/${e}/parts`,te({body:t,...r},this._client))}};var He=class extends f{constructor(){super(...arguments),this.parts=new or(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(c`/uploads/${e}/complete`,{body:t,...r})}};He.Parts=or;var bo=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var ir=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/file_batches/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(c`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(c`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),a=this._client,u=t.values(),p=[...r];async function m(_){for(let h of _){let A=await a.files.create({file:h,purpose:"assistants"},n);p.push(A.id)}}let d=Array(i).fill(u).map(m);return await bo(d),await this.createAndPoll(e,{file_ids:p})}};var ar=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(c`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/vector_stores/${e}/files`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(c`/vector_stores/${n}/files/${e}/content`,ce,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ae=class extends f{constructor(){super(...arguments),this.files=new ar(this._client),this.fileBatches=new ir(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/vector_stores/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(c`/vector_stores/${e}/search`,ce,{body:t,method:"post",...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};Ae.Files=ar;Ae.FileBatches=ir;var ht=class extends f{create(e,t){return this._client.post("/videos",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",pe,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(c`/videos/${e}/content`,{query:t,...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(c`/videos/${e}/remix`,de({body:t,...r},this._client))}};var lr,wo,hs,pt=class extends f{constructor(){super(...arguments),lr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,lr,"m",wo).call(this,r);let o=g([t]).values,i=l(this,lr,"m",hs).call(this,o,"webhook-signature"),a=l(this,lr,"m",hs).call(this,o,"webhook-timestamp"),u=l(this,lr,"m",hs).call(this,o,"webhook-id"),p=parseInt(a,10);if(isNaN(p))throw new oe("Invalid webhook timestamp format");let m=Math.floor(Date.now()/1e3);if(m-p>n)throw new oe("Webhook timestamp is too old");if(p>m+n)throw new oe("Webhook timestamp is too new");let d=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),_=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=u?`${u}.${a}.${e}`:`${a}.${e}`,A=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of d)try{let R=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",A,R,new TextEncoder().encode(h)))return}catch{continue}throw new oe("The given webhook signature does not match the expected signature")}};lr=new WeakSet,wo=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},hs=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var sn,nn,ps,xo,I=class{constructor({baseURL:e=Fe("OPENAI_BASE_URL"),apiKey:t=Fe("OPENAI_API_KEY"),organization:r=Fe("OPENAI_ORG_ID")??null,project:n=Fe("OPENAI_PROJECT_ID")??null,webhookSecret:o=Fe("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(sn.add(this),ps.set(this,void 0),this.completions=new et(this),this.chat=new Oe(this),this.embeddings=new rt(this),this.files=new nt(this),this.images=new lt(this),this.audio=new ue(this),this.moderations=new ut(this),this.models=new ct(this),this.fineTuning=new ne(this),this.graders=new Ue(this),this.vectorStores=new Ae(this),this.webhooks=new pt(this),this.beta=new se(this),this.batches=new ze(this),this.uploads=new He(this),this.responses=new we(this),this.realtime=new be(this),this.conversations=new je(this),this.evals=new Be(this),this.containers=new Le(this),this.skills=new xe(this),this.videos=new ht(this),t===void 0)throw new y("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Rn())throw new y(`It looks like you're running in a browser-like environment.
139
139
 
140
140
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
141
141
  If you understand the risks and have appropriate mitigations in place,
@@ -144,27 +144,27 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
144
144
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
145
145
 
146
146
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
147
- `);this.baseURL=a.baseURL,this.timeout=a.timeout??sn.DEFAULT_TIMEOUT,this.logger=a.logger??console;let u="warn";this.logLevel=u,this.logLevel=Os(a.logLevel,"ClientOptions.logLevel",this)??Os(Te("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??En(),x(this,ds,$n,"f"),this._options=a,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=o}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 g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return $s(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Re}`}defaultIdempotencyKey(){return`stainless-node-retry-${ws()}`}makeStatusError(e,t,r,n){return B.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof y?r:new y(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new y(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!l(this,rn,"m",wo).call(this)&&r||this.baseURL,o=yn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return bn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Je(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:a,timeout:u}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:a,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(M(this).debug(`[${p}] sending request`,fe({retryOfRequestLogID:r,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new L;let _=new AbortController,h=await this.fetchWithTimeout(a,i,u,_).catch(hr),A=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new L;let w=fr(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return M(this).info(`[${p}] connection ${w?"timed out":"failed"} - ${v}`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (${v})`,fe({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),this.retryRequest(n,t,r??p);throw M(this).info(`[${p}] connection ${w?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (error; no more retries left)`,fe({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),w?new Pe:new ve({cause:h})}let b=[...h.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,w])=>", "+v+": "+JSON.stringify(w)).join(""),R=`[${p}${m}${b}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-d}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(t&&v){let C=`retrying, ${t} attempts remaining`;return await Cn(h.body),M(this).info(`${R} - ${C}`),M(this).debug(`[${p}] response error (${C})`,fe({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),this.retryRequest(n,t,r??p,h.headers)}let w=v?"error; no more retries left":"error; not retryable";M(this).info(`${R} - ${w}`);let k=await h.text().catch(C=>hr(C).message),P=An(k),E=P?void 0:k;throw M(this).debug(`[${p}] response error (${w})`,fe({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:E,durationMs:Date.now()-d})),this.makeStatusError(h.status,P,E,h.headers)}return M(this).info(R),M(this).debug(`[${p}] response start`,fe({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),{response:h,options:n,controller:_,requestLogID:p,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new yr(this,r,e)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...a}=t||{},u=this._makeAbort(n);o&&o.addEventListener("abort",u,{once:!0});let p=setTimeout(u,r),m=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:n.signal,...m?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,i=n?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let a=n?.get("retry-after");if(a&&!o){let u=parseFloat(a);Number.isNaN(u)?o=Date.parse(a)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await oe(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:a}=r,u=this.buildURL(o,i,a);"timeout"in r&&xn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:m}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=g([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Rn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.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}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Ur(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:l(this,ds,"f").call(this,{body:e,headers:r})}};sn=I,ds=new WeakMap,rn=new WeakSet,wo=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=sn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=B;I.APIConnectionError=ve;I.APIConnectionTimeoutError=Pe;I.APIUserAbortError=L;I.NotFoundError=xt;I.ConflictError=At;I.RateLimitError=St;I.BadRequestError=yt;I.AuthenticationError=bt;I.InternalServerError=vt;I.PermissionDeniedError=wt;I.UnprocessableEntityError=It;I.InvalidWebhookSignatureError=ne;I.toFile=zr;I.Completions=et;I.Chat=$e;I.Embeddings=rt;I.Files=nt;I.Images=lt;I.Audio=ce;I.Moderations=ut;I.Models=ct;I.FineTuning=se;I.Graders=je;I.VectorStores=xe;I.Webhooks=pt;I.Beta=re;I.Batches=ze;I.Uploads=Ue;I.Responses=be;I.Realtime=ye;I.Conversations=Me;I.Evals=Le;I.Containers=Fe;I.Skills=we;I.Videos=ht;async function Gi(s,e,t){await s.evaluate(()=>{let m=document.getElementById("playwright-highlight-container");m&&m.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(d=>d()),window._highlightCleanupFunctions=[])});let r=await s.screenshot({type:"png",fullPage:!1}),{default:n}=await import("sharp"),o=n(r),i=await o.metadata(),a=i.width||0,u=i.height||0;Z.log(`Screenshot actual dimensions: ${a}x${u}, viewport: ${e}x${t}`);let p;return a!==e||u!==t?(Z.log(`Resizing screenshot from ${a}x${u} to ${e}x${t}`),p=await o.resize(e,t).png().toBuffer()):p=r,p.toString("base64")}async function nn(s,e,t){let r=await s.evaluateHandle(u=>document.elementFromPoint(u.x,u.y),{x:e,y:t});if(!r)throw new Error(`No element found at (${e}, ${t})`);let n=r.asElement();if(!n)throw await r.dispose(),new Error(`No element found at (${e}, ${t})`);let o=await n.boundingBox();if(!o)throw await r.dispose(),new Error("Element has no bounding box");let i=e-(o.x+o.width/2),a=t-(o.y+o.height/2);return{relative_x:i,relative_y:a,element:n}}async function Yi(s,e){return e?{xpath:void 0,locator:(e?await un(s,e):null)||void 0,frame_path:[]}:{xpath:void 0,locator:void 0,frame_path:[]}}async function Qi(s,e){let t=null,r=null;switch(e.type){case"click":{let o=e.button==="right"?"right_click_by_coordinates":"click_by_coordinates";if(e.x===void 0||e.y===void 0)break;let i=await nn(s,e.x,e.y);t={action_name:o,kwargs:{relative_x:i.relative_x,relative_y:i.relative_y}},r=i.element;break}case"double_click":{if(e.x===void 0||e.y===void 0)break;let o=await nn(s,e.x,e.y);t={action_name:"double_click_by_coordinates",kwargs:{relative_x:o.relative_x,relative_y:o.relative_y}},r=o.element;break}case"drag":{if(!e.path||e.path.length<2)break;let o=e.path[0].x,i=e.path[0].y,a=e.path[1].x,u=e.path[1].y,p=await nn(s,o,i);t={action_name:"drag_drop",kwargs:{relative_x:p.relative_x,relative_y:p.relative_y,delta_x:a-o,delta_y:u-i}},r=p.element;break}}let n=await Yi(s,r);return{action_data:t,locatorInfo:n}}async function ms(s,e,t={}){try{let{page:r}=e,n=r.viewportSize();if(!n)return{status:"error",error:"Viewport size not available"};let o=n.width,i=n.height;Z.log(`Viewport size: ${o}x${i}`);let a=await Gi(r,o,i),u=ln().env?.OPENAI_API_KEY;if(!u)return{status:"error",error:"OpenAI API key not found. Set OPENAI_API_KEY environment variable or configure via SDK config."};let p=new I({apiKey:u});Z.log("Sending request to OpenAI CUA...");let m=[{role:"user",content:[{type:"input_text",text:`
147
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??nn.DEFAULT_TIMEOUT,this.logger=a.logger??console;let u="warn";this.logLevel=u,this.logLevel=Ts(a.logLevel,"ClientOptions.logLevel",this)??Ts(Fe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Cn(),x(this,ps,kn,"f"),this._options=a,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=o}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 g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ks(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${xs()}`}makeStatusError(e,t,r,n){return B.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof y?r:new y(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new y(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!l(this,sn,"m",xo).call(this)&&r||this.baseURL,o=bn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return wn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Je(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:a,timeout:u}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:a,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(M(this).debug(`[${p}] sending request`,he({retryOfRequestLogID:r,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new L;let _=new AbortController,h=await this.fetchWithTimeout(a,i,u,_).catch(hr),A=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new L;let w=fr(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return M(this).info(`[${p}] connection ${w?"timed out":"failed"} - ${v}`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (${v})`,he({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),this.retryRequest(n,t,r??p);throw M(this).info(`[${p}] connection ${w?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (error; no more retries left)`,he({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),w?new Ee:new Re({cause:h})}let b=[...h.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,w])=>", "+v+": "+JSON.stringify(w)).join(""),R=`[${p}${m}${b}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-d}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(t&&v){let C=`retrying, ${t} attempts remaining`;return await $n(h.body),M(this).info(`${R} - ${C}`),M(this).debug(`[${p}] response error (${C})`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),this.retryRequest(n,t,r??p,h.headers)}let w=v?"error; no more retries left":"error; not retryable";M(this).info(`${R} - ${w}`);let k=await h.text().catch(C=>hr(C).message),P=In(k),E=P?void 0:k;throw M(this).debug(`[${p}] response error (${w})`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:E,durationMs:Date.now()-d})),this.makeStatusError(h.status,P,E,h.headers)}return M(this).info(R),M(this).debug(`[${p}] response start`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),{response:h,options:n,controller:_,requestLogID:p,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new yr(this,r,e)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...a}=t||{},u=this._makeAbort(n);o&&o.addEventListener("abort",u,{once:!0});let p=setTimeout(u,r),m=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:n.signal,...m?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,i=n?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let a=n?.get("retry-after");if(a&&!o){let u=parseFloat(a);Number.isNaN(u)?o=Date.parse(a)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ie(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:a}=r,u=this.buildURL(o,i,a);"timeout"in r&&An("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:m}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=g([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...En(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.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}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Br(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:l(this,ps,"f").call(this,{body:e,headers:r})}};nn=I,ps=new WeakMap,sn=new WeakSet,xo=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=nn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=B;I.APIConnectionError=Re;I.APIConnectionTimeoutError=Ee;I.APIUserAbortError=L;I.NotFoundError=wt;I.ConflictError=xt;I.RateLimitError=It;I.BadRequestError=_t;I.AuthenticationError=yt;I.InternalServerError=St;I.PermissionDeniedError=bt;I.UnprocessableEntityError=At;I.InvalidWebhookSignatureError=oe;I.toFile=Xr;I.Completions=et;I.Chat=Oe;I.Embeddings=rt;I.Files=nt;I.Images=lt;I.Audio=ue;I.Moderations=ut;I.Models=ct;I.FineTuning=ne;I.Graders=Ue;I.VectorStores=Ae;I.Webhooks=pt;I.Beta=se;I.Batches=ze;I.Uploads=He;I.Responses=we;I.Realtime=be;I.Conversations=je;I.Evals=Be;I.Containers=Le;I.Skills=xe;I.Videos=ht;async function Yi(s,e,t){await s.evaluate(()=>{let m=document.getElementById("playwright-highlight-container");m&&m.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(d=>d()),window._highlightCleanupFunctions=[])});let r=await s.screenshot({type:"png",fullPage:!1}),{default:n}=await import("sharp"),o=n(r),i=await o.metadata(),a=i.width||0,u=i.height||0;ee.log(`Screenshot actual dimensions: ${a}x${u}, viewport: ${e}x${t}`);let p;return a!==e||u!==t?(ee.log(`Resizing screenshot from ${a}x${u} to ${e}x${t}`),p=await o.resize(e,t).png().toBuffer()):p=r,p.toString("base64")}async function on(s,e,t){let r=await s.evaluateHandle(u=>document.elementFromPoint(u.x,u.y),{x:e,y:t});if(!r)throw new Error(`No element found at (${e}, ${t})`);let n=r.asElement();if(!n)throw await r.dispose(),new Error(`No element found at (${e}, ${t})`);let o=await n.boundingBox();if(!o)throw await r.dispose(),new Error("Element has no bounding box");let i=e-(o.x+o.width/2),a=t-(o.y+o.height/2);return{relative_x:i,relative_y:a,element:n}}async function Qi(s,e){return e?{xpath:void 0,locator:(e?await fn(s,e):null)||void 0,frame_path:[]}:{xpath:void 0,locator:void 0,frame_path:[]}}async function Zi(s,e){let t=null,r=null;switch(e.type){case"click":{let o=e.button==="right"?"right_click_by_coordinates":"click_by_coordinates";if(e.x===void 0||e.y===void 0)break;let i=await on(s,e.x,e.y);t={action_name:o,kwargs:{relative_x:i.relative_x,relative_y:i.relative_y}},r=i.element;break}case"double_click":{if(e.x===void 0||e.y===void 0)break;let o=await on(s,e.x,e.y);t={action_name:"double_click_by_coordinates",kwargs:{relative_x:o.relative_x,relative_y:o.relative_y}},r=o.element;break}case"drag":{if(!e.path||e.path.length<2)break;let o=e.path[0].x,i=e.path[0].y,a=e.path[1].x,u=e.path[1].y,p=await on(s,o,i);t={action_name:"drag_drop",kwargs:{relative_x:p.relative_x,relative_y:p.relative_y,delta_x:a-o,delta_y:u-i}},r=p.element;break}}let n=await Qi(s,r);return{action_data:t,locatorInfo:n}}async function ds(s,e,t={}){try{let{page:r}=e,n=r.viewportSize();if(!n)return{status:"error",error:"Viewport size not available"};let o=n.width,i=n.height;ee.log(`Viewport size: ${o}x${i}`);let a=await Yi(r,o,i),u=un().env?.OPENAI_API_KEY;if(!u)return{status:"error",error:"OpenAI API key not found. Set OPENAI_API_KEY environment variable or configure via SDK config."};let p=new I({apiKey:u});ee.log("Sending request to OpenAI CUA...");let m=[{role:"user",content:[{type:"input_text",text:`
148
148
  You will be given an action to execute and screenshot of the current screen.
149
149
  Output one computer_call object that will accomplish this action.
150
150
  Action: ${s}
151
- `},{type:"input_image",detail:"auto",image_url:`data:image/png;base64,${a}`}]}],d=await p.responses.create({model:"computer-use-preview",tools:[{type:"computer_use_preview",display_width:o,display_height:i,environment:"browser"}],input:m,truncation:"auto",temperature:.1});Z.log("Received response from OpenAI CUA");let _=d.output.filter(R=>R.type==="computer_call")[0]??null;if(!_)return{status:"error",reasoning:d.output_text||""||"Invalid action generation response",error:"No computer_call action generated"};let h=_.action;Z.log(`Generated action: ${JSON.stringify(h)}`);let{action_data:A,locatorInfo:b}=await Qi(r,h);return A?{status:"success",actionEntity:{action_description:s,action_data:A,locator:b.locator||void 0,xpath:b.xpath||void 0,frame_path:b.frame_path},reasoning:"Action generated successfully using pure vision mode",goalAccomplished:!0}:{status:"error",error:"Failed to map action to ActionDataEntity"}}catch(r){return Z.error("Error generating CUA action",r),{status:"error",error:r.message||"Failed to generate action with pure vision"}}}async function Zi(s){let e=s.context().pages(),t=null,r=[];for(let o=0;o<e.length;o++){let i=e[o];i===s&&(t=o);let a="(title unavailable)";try{a=await Promise.race([i.title(),new Promise((p,m)=>setTimeout(()=>m(new Error("timeout")),1e3))])}catch{}let u=`Tab ${o}: ${i.url()}`;a&&(u+=` - ${a.slice(0,50)}`),r.push(u)}let n=r.length>0?r.join(`
151
+ `},{type:"input_image",detail:"auto",image_url:`data:image/png;base64,${a}`}]}],d=await p.responses.create({model:"computer-use-preview",tools:[{type:"computer_use_preview",display_width:o,display_height:i,environment:"browser"}],input:m,truncation:"auto",temperature:.1});ee.log("Received response from OpenAI CUA");let _=d.output.filter(R=>R.type==="computer_call")[0]??null;if(!_)return{status:"error",reasoning:d.output_text||""||"Invalid action generation response",error:"No computer_call action generated"};let h=_.action;ee.log(`Generated action: ${JSON.stringify(h)}`);let{action_data:A,locatorInfo:b}=await Zi(r,h);return A?{status:"success",actionEntity:{action_description:s,action_data:A,locator:b.locator||void 0,xpath:b.xpath||void 0,frame_path:b.frame_path},reasoning:"Action generated successfully using pure vision mode",goalAccomplished:!0}:{status:"error",error:"Failed to map action to ActionDataEntity"}}catch(r){return ee.error("Error generating CUA action",r),{status:"error",error:r.message||"Failed to generate action with pure vision"}}}function ms(s,e){return s?{prompt_tokens:s.promptTokens||s.inputTokens||0,completion_tokens:s.completionTokens||s.outputTokens||0,total_tokens:s.totalTokens||0,model:e}:null}async function ea(s){let e=s.context().pages(),t=null,r=[];for(let o=0;o<e.length;o++){let i=e[o];i===s&&(t=o);let a="(title unavailable)";try{a=await Promise.race([i.title(),new Promise((p,m)=>setTimeout(()=>m(new Error("timeout")),1e3))])}catch{}let u=`Tab ${o}: ${i.url()}`;a&&(u+=` - ${a.slice(0,50)}`),r.push(u)}let n=r.length>0?r.join(`
152
152
  `):"";return{currentTabText:t!==null?`Current tab: ${t}
153
- `:"",tabsText:n}}async function ea(s,e){let{currentTabText:t,tabsText:r}=await Zi(s);return{elementsText:e,currentUrl:s.url(),currentTitle:await s.title(),currentTabText:t,tabsText:r}}async function gs(s,e){let{page:t,domService:r,agentServices:n}=s,o=typeof e=="boolean"?{useCleanScreenshot:e}:e||{},i=n.getInteractiveClassNames(),{domState:a,screenshotBase64:u,slicedScreenshotsBase64:p}=await r.getClickableElementsWithScreenshot(t,{interactiveClassNames:i,useCleanScreenshot:o.useCleanScreenshot,useSlicedScreenshots:o.useSlicedScreenshots,resizeSlicedScreenshots:o.resizeSlicedScreenshots,useAccessibilityTree:o.useAccessibilityTree,actionIntent:o.actionIntent}),m=a.elementTree.clickableElementsToString(),d=await ea(t,m);return p&&(d.slicedScreenshotsBase64=p),{domTree:m,screenshotBase64:u,slicedScreenshotsBase64:p,domState:a,pageContext:d}}import{z as _s}from"zod";function ta(s){let e=s.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(t=>t.test(e))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(t=>t.test(e))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(t=>t.test(e))?"click":"all"}function ra(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}function sa(s){return s.map(e=>({role:e.role,content:Array.isArray(e.content)?e.content.map(t=>{if(t.type==="image"){let r=t.image,n=ra(r);if(n)return{type:"image",file:n};let o=typeof r=="string"?r:"";return{type:"image",file:o.startsWith("data:")?o:`data:image/png;base64,${o}`}}return{type:"text",text:t.text}}):e.content}))}async function xo(s,e,t={}){let{page:r,agentServices:n}=e,o=n.getModel(),i=t.temperature??0,a=n.retrieveKnowledges(s).catch(X=>(Z.log(`Failed to retrieve knowledges: ${X.message}`),[])),u=n.isSlicedScreenshotsEnabled(),p=n.isResizeSlicedScreenshotsEnabled(),m=n.isKnowledgeImagesEnabled(),d=n.isAccessibilityTreeEnabled(),_=n.isActionIntentFilteringEnabled(),h=_?ta(s):"all";_&&h!=="all"&&Z.log(`Action intent filtering: detected '${h}' intent from statement`);let{screenshotBase64:A,domState:b,pageContext:R}=await gs(e,{useSlicedScreenshots:u,resizeSlicedScreenshots:p,useAccessibilityTree:d,actionIntent:h});e.domState=b;let v=new pn(_t).getToolDefinitions().map(X=>{let gt=X.function;return`${gt.name}: ${gt.description}
154
- Parameters: ${JSON.stringify(gt.parameters,null,2)}`}).join(`
153
+ `:"",tabsText:n}}async function ta(s,e){let{currentTabText:t,tabsText:r}=await ea(s);return{elementsText:e,currentUrl:s.url(),currentTitle:await s.title(),currentTabText:t,tabsText:r}}async function gs(s,e){let{page:t,domService:r,agentServices:n}=s,o=typeof e=="boolean"?{useCleanScreenshot:e}:e||{},i=n.getInteractiveClassNames(),a=n.getIframeFallbackDomains(),{domState:u,screenshotBase64:p,slicedScreenshotsBase64:m}=await r.getClickableElementsWithScreenshot(t,{interactiveClassNames:i,playwrightFrameFallbackDomains:a,useCleanScreenshot:o.useCleanScreenshot,useSlicedScreenshots:o.useSlicedScreenshots,resizeSlicedScreenshots:o.resizeSlicedScreenshots,useAccessibilityTree:o.useAccessibilityTree,actionIntent:o.actionIntent}),d=u.elementTree.clickableElementsToString(),_=await ta(t,d);return m&&(_.slicedScreenshotsBase64=m),{domTree:d,screenshotBase64:p,slicedScreenshotsBase64:m,domState:u,pageContext:_}}import{z as _s}from"zod";function ra(s){let e=s.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(t=>t.test(e))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(t=>t.test(e))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(t=>t.test(e))?"click":"all"}function sa(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}function na(s){return s.map(e=>({role:e.role,content:Array.isArray(e.content)?e.content.map(t=>{if(t.type==="image"){let r=t.image,n=sa(r);if(n)return{type:"image",file:n};let o=typeof r=="string"?r:"";return{type:"image",file:o.startsWith("data:")?o:`data:image/png;base64,${o}`}}return{type:"text",text:t.text}}):e.content}))}async function Ao(s,e,t={}){let{page:r,agentServices:n}=e,o=n.getModel(),i=t.temperature??0,a=n.retrieveKnowledges(s).catch(q=>(ee.log(`Failed to retrieve knowledges: ${q.message}`),[])),u=n.isSlicedScreenshotsEnabled(),p=n.isResizeSlicedScreenshotsEnabled(),m=n.isKnowledgeImagesEnabled(),d=n.isAccessibilityTreeEnabled(),_=n.isActionIntentFilteringEnabled(),h=_?ra(s):"all";_&&h!=="all"&&ee.log(`Action intent filtering: detected '${h}' intent from statement`);let{screenshotBase64:A,domState:b,pageContext:R}=await gs(e,{useSlicedScreenshots:u,resizeSlicedScreenshots:p,useAccessibilityTree:d,actionIntent:h});e.domState=b;let v=new dn(gt).getToolDefinitions().map(q=>{let mt=q.function;return`${mt.name}: ${mt.description}
154
+ Parameters: ${JSON.stringify(mt.parameters,null,2)}`}).join(`
155
155
 
156
- `),w=gn(v),k=await a,P=_n(R,s,e.variables,e.executionHistory,k.length>0?k:void 0,A,u,void 0,m,e.sensitiveKeys),E=[];t.chatHistory&&t.chatHistory.length>0&&t.chatHistory.forEach(X=>{X.role==="user"?E.push({role:"user",content:X.content}):X.role==="assistant"&&E.push({role:"assistant",content:X.content})}),E.push({role:"user",content:P});let O=sa(E),C=_t.buildActionUnionSchema(),N=_s.object({thought:_s.string().describe("Step by step reasoning of your decision making process").optional().default(""),description:_s.string().describe("Detailed description of the action to be performed").optional().default(""),action:C,completes_instruction:_s.boolean().describe("Whether this action completes the given instruction").optional().default(!1)}),F=Array.isArray(P)?P.filter(X=>X.type==="image").length:0,T=Tr(o,F),$=await Fr({model:Or(o),system:w,messages:E,temperature:i,output:Nr.object({schema:N}),providerOptions:T}),Q=$.output,Ae=JSON.stringify(Q,null,2);cn.debug(`Generate Action Raw Output: ${Ae}`);let dt=[],De=jr($.usage,o);De&&dt.push(De);let He={systemPrompt:w,userPrompt:O,rawLlmResponse:Ae,tokenUsages:dt},Ie=Q.thought||"",We=Q.description||"",mt=Q.action||{},j=Q.completes_instruction||!1;if(!mt||Object.keys(mt).length===0)return{status:"error",reasoning:Ie||We||"No action generated",goalAccomplished:j,error:"Agent did not generate any action",debugInfo:He};let q=Object.keys(mt)[0];if(q==="done")return{status:"error",reasoning:Ie||We||"Task marked as done",goalAccomplished:j,error:"Agent indicated task is done without generating an action",debugInfo:He};if(q==="perform_accurate_operation")return await ms(s,e,t);let V=mt[q]||{},Se={};if(typeof V.element_index=="number"){let X=V.element_index;if(X<0)return{status:"error",reasoning:Ie||We||"No action generated",goalAccomplished:j,error:"Agent did not generate any action",debugInfo:He};let gt=b.selectorMap.get(X);gt&&(Se=await fn(r,gt))}let an=We;return q==="verify"&&(an=s,V.statement=s),{status:"success",actionEntity:{...Se,action_description:an||Ie||`${q}(${JSON.stringify(V)})`,action_data:{action_name:q,kwargs:V}},reasoning:Ie||We,goalAccomplished:j,debugInfo:He}}import{z as ys}from"zod";function na(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}var oa=ys.object({screenshotDescription:ys.string().describe(`Description of the screenshot content, listing out key elements along with their Set of Mark indices,
156
+ `),w=_n(v),k=await a,P=yn(R,s,e.variables,e.executionHistory,k.length>0?k:void 0,A,u,void 0,m,e.sensitiveKeys),E=[];t.chatHistory&&t.chatHistory.length>0&&t.chatHistory.forEach(q=>{q.role==="user"?E.push({role:"user",content:q.content}):q.role==="assistant"&&E.push({role:"assistant",content:q.content})}),E.push({role:"user",content:P});let O=na(E),C=gt.buildActionUnionSchema(),N=_s.object({thought:_s.string().describe("Step by step reasoning of your decision making process").optional().default(""),description:_s.string().describe("Detailed description of the action to be performed").optional().default(""),action:C,completes_instruction:_s.boolean().describe("Whether this action completes the given instruction").optional().default(!1)}),F=Array.isArray(P)?P.filter(q=>q.type==="image").length:0,T=Tr(o,F),$=await Fr({model:Or(o),system:w,messages:E,temperature:i,output:Nr.object({schema:N}),providerOptions:T}),Ie=$.reasoningText;ws.info(`Action Generation Reasoning: ${Ie}`);let Q=$.output,dt=JSON.stringify(Q,null,2);ws.info(`Generate Action Raw Output: ${dt}`);let We=[],cr=ms($.usage,o);cr&&We.push(cr);let Se={systemPrompt:w,userPrompt:O,rawLlmResponse:dt,tokenUsages:We},ve=Q.thought||"",Pe=Q.description||"",j=Q.action||{},K=Q.completes_instruction||!1;if(!j||Object.keys(j).length===0)return{status:"error",reasoning:ve||Pe||"No action generated",goalAccomplished:K,error:"Agent did not generate any action",debugInfo:Se};let V=Object.keys(j)[0];if(V==="done")return{status:"error",reasoning:ve||Pe||"Task marked as done",goalAccomplished:K,error:"Agent indicated task is done without generating an action",debugInfo:Se};if(V==="perform_accurate_operation")return await ds(s,e,t);if(!K){let q="Can't complete the instruction in one action";return{status:"error",reasoning:ve||Pe||q,goalAccomplished:!1,error:q,debugInfo:Se}}let Z=j[V]||{},ln={};if(typeof Z.element_index=="number"){let q=Z.element_index;if(q<0)return{status:"error",reasoning:ve||Pe||"No action generated",goalAccomplished:K,error:"Agent did not generate any action",debugInfo:Se};let mt=b.selectorMap.get(q);mt&&(ln=await hn(r,mt))}let cn=Pe;return V==="verify"&&(cn=s,Z.statement=s),{status:"success",actionEntity:{...ln,action_description:cn||ve||`${V}(${JSON.stringify(Z)})`,action_data:{action_name:V,kwargs:Z}},reasoning:ve||Pe,goalAccomplished:K,debugInfo:Se}}import{z as ys}from"zod";function oa(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}var ia=ys.object({screenshotDescription:ys.string().describe(`Description of the screenshot content, listing out key elements along with their Set of Mark indices,
157
157
  and a description of their location: formatting example: [12] A red button with text "Submit", next to [11]
158
158
  [45] A modal dialog titled "Confirmation",
159
- in the center of the screen`),explanation:ys.string().describe("Step by step reasoning explaining your conclusion about the statement"),conclusion:ys.enum(["true","false","unknown"]).describe("Whether the statement is true, false, or unknown if you cannot make a conclusion")});async function on(s,e,t={}){return t.usePureVision?ms(s,e,t):xo(s,e,t)}function ia(){let s=new Date,e=s.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/Los_Angeles"}),t=s.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZoneName:"short",timeZone:"America/Los_Angeles"});return{dateString:e,timeString:t}}function aa(){return`# Role
159
+ in the center of the screen`),explanation:ys.string().describe("Step by step reasoning explaining your conclusion about the statement"),conclusion:ys.enum(["true","false","unknown"]).describe("Whether the statement is true, false, or unknown if you cannot make a conclusion")});async function an(s,e,t={}){return t.usePureVision?ds(s,e,t):Ao(s,e,t)}function aa(){let s=new Date,e=s.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/Los_Angeles"}),t=s.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZoneName:"short",timeZone:"America/Los_Angeles"});return{dateString:e,timeString:t}}function la(){return`# Role
160
160
  You are an experienced QA person for web applications.
161
161
  You are tasked to verify the validity of a given statement based on the screenshot and element tree of a web page.
162
- `}async function Ao(s,e,t={}){let{page:r,executionHistory:n}=e,o=e.agentServices.getModel();try{let i=e.agentServices.isSlicedScreenshotsEnabled(),a=e.agentServices.isResizeSlicedScreenshotsEnabled(),u=e.agentServices.isKnowledgeImagesEnabled(),p=e.agentServices.isAccessibilityTreeEnabled(),{domTree:m,screenshotBase64:d,slicedScreenshotsBase64:_,domState:h,pageContext:A}=await gs(e,{useCleanScreenshot:t.useCleanScreenshotForAssertion,useSlicedScreenshots:i,resizeSlicedScreenshots:a,useAccessibilityTree:p});e.domState=h;let b="";n&&n.length>0&&(b=`
162
+ `}async function Io(s,e,t={}){let{page:r,executionHistory:n}=e,o=e.agentServices.getModel();try{let i=e.agentServices.isSlicedScreenshotsEnabled(),a=e.agentServices.isResizeSlicedScreenshotsEnabled(),u=e.agentServices.isKnowledgeImagesEnabled(),p=e.agentServices.isAccessibilityTreeEnabled(),{domTree:m,screenshotBase64:d,slicedScreenshotsBase64:_,domState:h,pageContext:A}=await gs(e,{useCleanScreenshot:t.useCleanScreenshotForAssertion,useSlicedScreenshots:i,resizeSlicedScreenshots:a,useAccessibilityTree:p});e.domState=h;let b="";n&&n.length>0&&(b=`
163
163
  # Previous actions in this session:
164
- ${n.map(([j,q],V)=>`${V+1}. Action: ${j}
165
- Result: ${q}`).join(`
164
+ ${n.map(([j,K],V)=>`${V+1}. Action: ${j}
165
+ Result: ${K}`).join(`
166
166
  `)}
167
- `);let{dateString:R,timeString:v}=ia(),w=`
167
+ `);let{dateString:R,timeString:v}=aa(),w=`
168
168
  # User statement
169
169
  "${s}"
170
170
 
@@ -203,7 +203,7 @@ ${m}
203
203
 
204
204
  ## Screenshot
205
205
  ${i&&_?"The following images are sliced screenshots of the current webpage (left, middle, right sections).":"The image provided is a screenshot of the current webpage."}
206
- `,k="";if(e.variables&&Object.keys(e.variables).length>0){let j=[];for(let q of Object.keys(e.variables))if(!e.sensitiveKeys?.has(q)){let V=e.variables[q],Se=typeof V=="string"?V:JSON.stringify(V);j.push(` - ${q}: "${Se}"`)}j.length>0&&(k=`
206
+ `,k="";if(e.variables&&Object.keys(e.variables).length>0){let j=[];for(let K of Object.keys(e.variables))if(!e.sensitiveKeys?.has(K)){let V=e.variables[K],Z=typeof V=="string"?V:JSON.stringify(V);j.push(` - ${K}: "${Z}"`)}j.length>0&&(k=`
207
207
  ## Available Variables
208
208
  The following non-sensitive variables are available:
209
209
  ${j.join(`
@@ -213,4 +213,4 @@ ${b}
213
213
 
214
214
  Today is ${R}. Current local time is ${v}.
215
215
  Based on the above information, please determine if the statement is true.
216
- `,E=await e.agentServices.retrieveKnowledges(s),O=[{type:"text",text:w}],C=0;if(i&&_&&_.length>0)for(let j of _)O.push({type:"image",image:j}),C++;else O.push({type:"image",image:d}),C=1;if(E&&E.length>0){let j=Br(E,u);O.push(...j)}O.push({type:"text",text:P});let N=E?mn(E,u):0,F=C+N,T=Tr(o,F),$=aa(),Q=await Fr({model:Or(o),system:$,messages:[{role:"user",content:O}],output:Nr.object({schema:oa}),temperature:0,providerOptions:T}),{conclusion:Ae,explanation:dt}=Q.output,De=JSON.stringify(Q.output,null,2),He=[],Ie=jr(Q.usage,o);Ie&&He.push(Ie);let We=[{role:"user",content:O.map(j=>{if(j.type==="text")return{type:"text",text:j.text};if(j.type==="image"){let q=j.image,V=na(q);if(V)return{type:"image",file:V};let Se=typeof q=="string"?q:"";return{type:"image",file:Se.startsWith("data:")?Se:`data:image/png;base64,${Se}`}}return{type:"text",text:"[unknown content type]"}})}],mt={systemPrompt:$,userPrompt:We,rawLlmResponse:De,screenshotWithSom:d,tokenUsages:He,retrievedKnowledges:E&&E.length>0?E:void 0,elementTree:m};return{success:Ae==="true",explanation:dt,debugInfo:mt}}catch(i){return{success:!1,error:i.message}}}async function la(s,e){try{if(!s.action_data)return{success:!1,error:"Action entity missing action_data"};let{action_name:t,kwargs:r}=s.action_data;if(_t.has(t)){let n=await _t.execute(t,r,e),o=n?.success!==!1,i=n?.error||n?.message;return{success:o,error:o?void 0:i}}else{let{page:n,agentServices:o}=e;return await(await ca()).execute(n,s,o),{success:!0,error:void 0}}}catch(t){return{success:!1,error:t.message}}}var bs=null;async function ca(){if(bs)return bs;let s=await import("./handler-BAP4TGW6.js");return bs=new s.default,bs}async function rg(s,e,t,r={},n){let o=n||{page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},i=t.replaceVariables(s),a=await on(i,o,r);return a.status==="error"?{status:"error",completed:a.goalAccomplished||!1,actionEntities:[],explanation:a.reasoning,error:a.error,debugInfo:a.debugInfo}:{status:"success",completed:a.goalAccomplished||!1,actionEntities:a.actionEntity?[a.actionEntity]:[],explanation:a.reasoning,debugInfo:a.debugInfo}}async function sg(s,e,t,r={},n){let o=n||{page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},i=t.replaceVariables(s),a=await on(i,o,r);if(a.status==="error"||!a.actionEntity)return{status:"error",completed:a.goalAccomplished||!1,actionEntities:[],explanation:a.reasoning,error:a.error||"No action generated",debugInfo:a.debugInfo};let{actionEntity:u,reasoning:p,goalAccomplished:m,debugInfo:d}=a,_=await la(u,o);return _.success?(p&&t.addNote(p),{status:"success",completed:m||!1,actionEntities:[u],explanation:p,debugInfo:d}):{status:"error",completed:!1,actionEntities:[u],error:_.error||"Action execution failed",debugInfo:d}}async function ng(s,e,t,r={}){let n={page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},o=t.replaceVariables(s);return r.useCleanScreenshotForAssertion??(r.useCleanScreenshotForAssertion=t.isUseCleanScreenshotForAssertion()),Ao(o,n,r)}async function og(s,e,t,r,n={}){let{runTaskLoop:o}=await import("./task-VW6MUEKX.js"),i=r?u=>{r(u)}:void 0,a=await o(s,{page:e,agentServices:t,domService:void 0,executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},{maxSteps:n.maxSteps,onEvent:i,abortSignal:n.abortSignal});return{status:a.success?"success":"error",completed:a.completed,actionEntities:a.trajectory.actions,explanation:a.summary,error:a.error,tokenUsages:a.metadata.tokenUsages}}export{fa as a,pn as b,ms as c,la as d,rg as e,sg as f,ng as g,og as h};
216
+ `,E=await e.agentServices.retrieveKnowledges(s),O=[{type:"text",text:w}],C=0;if(i&&_&&_.length>0)for(let j of _)O.push({type:"image",image:j}),C++;else O.push({type:"image",image:d}),C=1;if(E&&E.length>0){let j=jr(E,u);O.push(...j)}O.push({type:"text",text:P});let N=E?gn(E,u):0,F=C+N,T=Tr(o,F),$=la(),Ie=await Fr({model:Or(o),system:$,messages:[{role:"user",content:O}],output:Nr.object({schema:ia}),temperature:0,providerOptions:T}),{conclusion:Q,explanation:dt}=Ie.output,We=JSON.stringify(Ie.output,null,2),cr=[],Se=ms(Ie.usage,o);Se&&cr.push(Se);let ve=[{role:"user",content:O.map(j=>{if(j.type==="text")return{type:"text",text:j.text};if(j.type==="image"){let K=j.image,V=oa(K);if(V)return{type:"image",file:V};let Z=typeof K=="string"?K:"";return{type:"image",file:Z.startsWith("data:")?Z:`data:image/png;base64,${Z}`}}return{type:"text",text:"[unknown content type]"}})}],Pe={systemPrompt:$,userPrompt:ve,rawLlmResponse:We,screenshotWithSom:d,tokenUsages:cr,retrievedKnowledges:E&&E.length>0?E:void 0,elementTree:m};return{success:Q==="true",explanation:dt,debugInfo:Pe}}catch(i){return{success:!1,error:i.message}}}async function ca(s,e){try{if(!s.action_data)return{success:!1,error:"Action entity missing action_data"};let{action_name:t,kwargs:r}=s.action_data;if(gt.has(t)){let n=await gt.execute(t,r,e),o=n?.success!==!1,i=n?.error||n?.message;return{success:o,error:o?void 0:i}}else{let{page:n,agentServices:o}=e;return await(await ua()).execute(n,s,o),{success:!0,error:void 0}}}catch(t){return{success:!1,error:t.message}}}var bs=null;async function ua(){if(bs)return bs;let s=await import("./handler-J6CCKSPE.js");return bs=new s.default,bs}async function sg(s,e,t,r={},n){let o=n||{page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},i=t.replaceVariables(s),a=await an(i,o,r);return a.status==="error"?{status:"error",completed:a.goalAccomplished||!1,actionEntities:[],explanation:a.reasoning,error:a.error,debugInfo:a.debugInfo}:{status:"success",completed:a.goalAccomplished||!1,actionEntities:a.actionEntity?[a.actionEntity]:[],explanation:a.reasoning,debugInfo:a.debugInfo}}async function ng(s,e,t,r={},n){let o=n||{page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},i=t.replaceVariables(s),a=await an(i,o,r);if(a.status==="error"||!a.actionEntity)return{status:"error",completed:a.goalAccomplished||!1,actionEntities:[],explanation:a.reasoning,error:a.error||"No action generated",debugInfo:a.debugInfo};let{actionEntity:u,reasoning:p,goalAccomplished:m,debugInfo:d}=a,_=await ca(u,o);return _.success?(p&&t.addNote(p),{status:"success",completed:m||!1,actionEntities:[u],explanation:p,debugInfo:d}):{status:"error",completed:!1,actionEntities:[u],error:_.error||"Action execution failed",debugInfo:d}}async function og(s,e,t,r={}){let n={page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},o=t.replaceVariables(s);return r.useCleanScreenshotForAssertion??(r.useCleanScreenshotForAssertion=t.isUseCleanScreenshotForAssertion()),Io(o,n,r)}async function ig(s,e,t,r,n={}){let{runTaskLoop:o}=await import("./task-EDC5BGTS.js"),i=r?u=>{r(u)}:void 0,a=await o(s,{page:e,agentServices:t,domService:void 0,executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},{maxSteps:n.maxSteps,onEvent:i,abortSignal:n.abortSignal});return{status:a.success?"success":"error",completed:a.completed,actionEntities:a.trajectory.actions,explanation:a.summary,error:a.error,tokenUsages:a.metadata.tokenUsages}}export{ha as a,dn as b,ds as c,ca as d,sg as e,ng as f,og as g,ig as h};