@swifty.js/swifty 0.0.1-canary

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{a as b,b as d,c as $,d as G,e as u,f as W}from"./chunk-H7VXSMJR.js";import"./chunk-X3UA5OZL.js";import*as w from"fs/promises";import*as P from"fs";import*as p from"path";import*as J from"child_process";import*as V from"crypto";import*as Y from"readline";function O(r){if(r.inputSchema.type!=="object")throw new Error(`JSON schema for tool "${r.name}" must be an object, but got ${r.inputSchema.type}`);return{type:"custom",name:r.name,input_schema:r.inputSchema,description:r.description,run:r.run,parse:t=>t,...r.close?{close:r.close}:{}}}import*as E from"fs/promises";import*as h from"path";import{randomUUID as nt}from"crypto";var x=493,st=420;async function ot(r){try{return await E.realpath(r)}catch{return r}}async function at(r){let t=[],e=r;for(;;){let i;try{i=await E.realpath(e)}catch{let n=!1;try{n=(await E.lstat(e)).isSymbolicLink()}catch{}if(n){e=h.resolve(h.dirname(e),await E.readlink(e));continue}let s=h.dirname(e);if(s===e)return r;t.push(h.basename(e)),e=s;continue}return t.length?h.join(i,...t.reverse()):i}}async function j(r,t,e){let i=e?.allowOutside??!1;if(h.isAbsolute(t)){if(!i)throw new u(`absolute path ${JSON.stringify(t)} not permitted`);return h.resolve(t)}let n=await ot(h.resolve(r)),s=h.resolve(n,t);if(i)return s;let o=await at(s),a=n.endsWith(h.sep)?n:n+h.sep;if(o!==n&&!o.startsWith(a))throw new u(`path ${JSON.stringify(t)} escapes workdir`);return o}async function q(r,t){let e=h.dirname(r),i=h.join(e,`.tmp-${process.pid}-${nt()}`),n;try{n=await E.open(i,"wx",st),await n.writeFile(t,"utf-8"),await n.sync(),await n.close(),n=void 0,await E.rename(i,r)}catch(s){throw n&&await n.close().catch(()=>{}),await E.unlink(i).catch(()=>{}),s}}function A(r,t){switch(r?.code){case"ENOENT":return`${t}: no such file or directory`;case"EACCES":case"EPERM":return`${t}: permission denied`;case"ENOTDIR":return`${t}: not a directory`;case"EISDIR":return`${t}: is a directory`;case"ELOOP":return`${t}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${t}: file name too long`;case"ENOSPC":return`${t}: no space left on device`;case"EMFILE":case"ENFILE":return`${t}: too many open files`;default:return`${t}: ${r instanceof Error?r.message:String(r)}`}}import*as g from"fs/promises";import*as H from"fs";import*as m from"path";import{execFile as ct}from"child_process";import{promisify as lt}from"util";import{Readable as ft}from"stream";import{pipeline as ut}from"stream/promises";var dt=lt(ct);async function pt(r){let{client:t,sessionId:e}=r;if(!t||!e)return async()=>{};let i=G(t),n=await t.beta.sessions.retrieve(e),s=m.resolve(r.workdir,"skills"),o=[];for(let a of n.agent.skills)try{let c=await z(t,a.skill_id,a.version),f=await t.beta.skills.versions.retrieve(c,{skill_id:a.skill_id}),l=m.basename(f.name.trim());(l===""||l==="."||l==="..")&&(l=a.skill_id);let v=m.resolve(s,l);if(v!==s&&!v.startsWith(s+m.sep)){i.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:f.name});continue}let T=await t.beta.skills.versions.download(c,{skill_id:a.skill_id});await g.rm(v,{recursive:!0,force:!0}),await g.mkdir(v,{recursive:!0,mode:x}),o.push(v),await K(T,v),i.info("downloaded skill",{component:"agent-tool-context",skill_id:a.skill_id,version:c,dest:v})}catch(c){i.warn("failed to download skill",{component:"agent-tool-context",skill_id:a.skill_id,error:String(c)})}return async()=>{for(let a of o)await g.rm(a,{recursive:!0,force:!0}).catch(c=>{i.warn("failed to clean up skill",{component:"agent-tool-context",dest:a,error:String(c)})})}}async function z(r,t,e){if(/^\d+$/.test(e))return e;let i;for await(let n of r.beta.skills.versions.list(t))/^\d+$/.test(n.version)&&(i===void 0||BigInt(n.version)>BigInt(i))&&(i=n.version);if(i===void 0)throw new $(`skill ${JSON.stringify(t)} has no concrete version to resolve ${JSON.stringify(e)} against`);return i}function ht(r){for(let t of r.split(`
5
+ `)){let e=t.trim();if(e&&(m.isAbsolute(e)||e.split(/[\\/]/).includes("..")))throw new $(`refusing to extract unsafe archive member: ${e}`)}}function mt(r){for(let t of r.split(`
6
+ `)){let e=t.trimStart()[0];if(e==="l"||e==="h"||e==="b"||e==="c"||e==="p"||e==="s")throw new $("refusing to extract archive with symlink/hardlink/device member")}}async function B(r,t){try{let{stdout:e}=await dt(r,t);return e}catch(e){throw e!=null&&typeof e=="object"&&e.code==="ENOENT"?new $(`skill extraction requires the \`${r}\` command, but it was not found on PATH`):e}}function wt(r){let t,e=!1;for(let i of r.split(`
7
+ `)){let n=i.trim().split("/").filter(o=>o!==""&&o!==".");if(n.length===0)continue;let s=n[0];if(t===void 0)t=s;else if(s!==t)return"";n.length>1&&(e=!0)}return t!==void 0&&e?t:""}async function K(r,t){let e=m.join(t,`.skill-archive-${process.pid}-${Date.now()}`);if(!r.body)throw new $("skill download response had no body");await ut(ft.fromWeb(r.body),H.createWriteStream(e));let i=m.join(m.dirname(t),`.skill-stage-${process.pid}-${Date.now()}`);try{let n=await yt(e,4),s=n.length>=4&&n[0]===80&&n[1]===75&&n[2]===3&&n[3]===4,o=s?"unzip":"tar",a=await B(o,s?["-Z1",e]:["-tf",e]);ht(a),mt(await B(o,s?["-Z",e]:["-tvf",e]));let c=wt(a);await g.mkdir(i,{recursive:!0,mode:x}),await B(o,s?["-oq",e,"-d",i]:["-xf",e,"-C",i]);let f=c?m.join(i,c):i;for(let l of await g.readdir(f))await g.rename(m.join(f,l),m.join(t,l))}finally{await g.rm(e,{force:!0}),await g.rm(i,{recursive:!0,force:!0})}}async function yt(r,t){let e=await g.open(r,"r");try{let i=Buffer.alloc(t),{bytesRead:n}=await e.read(i,0,t,0);return i.subarray(0,n)}finally{await e.close()}}var F,y,_,I,S,k,U,X=100*1024,Q=12e4,bt=256*1024,R=100*1024,gt=2e3,_t=200,vt=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,$t=w.glob;function tt(r){return r===void 0?bt:r}function ae(r){return[kt(r),Ot(r),St(r),Tt(r),xt(r),At(r)]}function M(r,t){return j(r.workdir,t,{allowOutside:r.unrestrictedPaths??!1})}function Et(){let r={};for(let[t,e]of Object.entries(process.env))t.startsWith("ANTHROPIC_")||(r[t]=e);return r}var C=class{constructor(t,e=Et()){F.add(this),y.set(this,void 0),_.set(this,""),I.set(this,!1),S.set(this,!1),k.set(this,null),b(this,y,J.spawn("/bin/bash",["--noprofile","--norc"],{cwd:t,env:{...e,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),d(this,y,"f").stdout.setEncoding("utf8"),d(this,y,"f").stderr.setEncoding("utf8"),d(this,y,"f").stdout.on("data",i=>d(this,F,"m",U).call(this,i)),d(this,y,"f").stderr.on("data",i=>d(this,F,"m",U).call(this,i)),d(this,y,"f").once("close",()=>{b(this,S,!0,"f");let i=d(this,k,"f");b(this,k,null,"f"),i?.resolve()})}get closed(){return d(this,S,"f")}async exec(t,e={}){if(d(this,S,"f"))throw new $("bash session terminated");let i=e.timeoutMs??Q,n=e.signal;if(n?.aborted)throw new $("bash command aborted");b(this,_,"","f"),b(this,I,!1,"f");let s=`__ANT_CMD_${V.randomUUID()}_DONE__`,o=`${s.slice(0,8)}''${s.slice(8)}`,a=`{ ${t}
8
+ } </dev/null 2>&1; printf '\\n${o}%d\\n' $?
9
+ `;if(d(this,y,"f").stdin.write(a),d(this,_,"f").indexOf(s)<0){let{promise:et,resolve:rt}=W();b(this,k,{sentinel:s,resolve:rt},"f");let L,N;try{await Promise.race([et,new Promise((it,D)=>{L=setTimeout(()=>D(new $(`bash command timed out after ${i}ms`)),i)}),new Promise((it,D)=>{n&&(N=()=>D(new $("bash command aborted")),n.addEventListener("abort",N,{once:!0}))})])}finally{L&&clearTimeout(L),N&&n&&n.removeEventListener("abort",N),b(this,k,null,"f")}}let c=d(this,_,"f").indexOf(s);if(c<0)throw new $("bash session terminated");let l=d(this,_,"f").slice(c+s.length).match(/^(-?\d+)/),v=l?parseInt(l[1],10):-1,T=d(this,_,"f").slice(0,c).replace(vt,"").replace(/\n+$/,"");return d(this,I,"f")&&(T=`[output truncated]
10
+ ${T}`),{output:T,exitCode:v}}close(){if(d(this,S,"f"))return;b(this,S,!0,"f");let t=d(this,k,"f");b(this,k,null,"f"),t?.resolve(),d(this,y,"f").stdout.destroy(),d(this,y,"f").stderr.destroy(),d(this,y,"f").stdin.destroy();try{process.kill(-d(this,y,"f").pid,"SIGKILL")}catch{d(this,y,"f").kill("SIGKILL")}d(this,y,"f").unref()}};y=new WeakMap,_=new WeakMap,I=new WeakMap,S=new WeakMap,k=new WeakMap,F=new WeakSet,U=function(t){if(b(this,_,d(this,_,"f")+t,"f"),d(this,_,"f").length>X&&(b(this,_,d(this,_,"f").slice(d(this,_,"f").length-X),"f"),b(this,I,!0,"f")),d(this,k,"f")&&d(this,_,"f").indexOf(d(this,k,"f").sentinel)>=0){let e=d(this,k,"f");b(this,k,null,"f"),e.resolve()}};function kt(r){let t,e=Promise.resolve();return O({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:i,restart:n,timeout_ms:s},o)=>{let a=e,c=W();e=c.promise;try{await a}catch{}try{if(n&&(t?.close(),t=void 0),!i){if(n)return"bash session restarted";throw new u("bash: command is required")}t??(t=new C(r.workdir,r.env));try{let{output:f,exitCode:l}=await t.exec(i,{timeoutMs:s??Q,signal:o?.signal});if(l!==0)throw new u(f||`exit ${l}`);return f}catch(f){throw f instanceof u?f:(t.close(),t=void 0,new u(`bash: ${f instanceof Error?f.message:String(f)}`))}}finally{c.resolve()}},close:()=>{t?.close(),t=void 0}})}function Ot(r){return O({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:t,view_range:e})=>{if(!t)throw new u("read: file_path is required");let i=await M(r,t),n;try{let l=await w.stat(i);if(!l.isFile())throw new u(`read: ${t} is not a regular file`);let v=tt(r.maxFileBytes);if(v!==null&&l.size>v)throw new u(`read: ${t} is ${l.size} bytes, exceeds ${v}-byte limit. Use bash (head/tail/sed) to read a slice.`);n=await w.readFile(i,"utf8")}catch(l){throw l instanceof u?l:new u(`read: ${A(l,t)}`)}if(!e)return n;if(e.length!==2)throw new u("read: view_range must be [start_line, end_line]");let[s,o]=e,a=n.split(`
11
+ `),c=Math.max(0,s-1),f=o>0?o:a.length;return a.slice(c,f).join(`
12
+ `)}})}function St(r){return O({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:t,content:e})=>{if(!t)throw new u("write: file_path is required");let i=await M(r,t);try{await w.mkdir(p.dirname(i),{recursive:!0,mode:x}),await q(i,e??"")}catch(n){throw new u(`write: ${A(n,t)}`)}return`wrote ${Buffer.byteLength(e??"")} bytes to ${t}`}})}function Tt(r){return O({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:t,old_string:e,new_string:i,replace_all:n})=>{if(!t)throw new u("edit: file_path is required");if(!e)throw new u("edit: old_string is required");let s=await M(r,t),o;try{let f=await w.stat(s);if(!f.isFile())throw new u(`edit: ${t} is not a regular file`);let l=tt(r.maxFileBytes);if(l!==null&&f.size>l)throw new u(`edit: ${t} is ${f.size} bytes, exceeds ${l}-byte limit. Use bash (sed/awk) to edit a large file.`);o=await w.readFile(s,"utf8")}catch(f){throw f instanceof u?f:new u(`edit: ${A(f,t)}`)}let a=o.split(e).length-1;if(a===0)throw new u(`edit: old_string not found in ${t}`);let c;if(n)c=o.split(e).join(i);else{if(a>1)throw new u(`edit: old_string appears ${a} times in ${t} (must be unique)`);c=o.replace(e,()=>i)}try{await q(s,c)}catch(f){throw new u(`edit: write: ${A(f,t)}`)}return`edited ${t} (${n?a:1} replacement(s))`}})}function xt(r){return O({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:t,path:e})=>{if(!t)throw new u("glob: pattern is required");let i=p.resolve(r.workdir),n=t;if(p.isAbsolute(t)){if(!r.unrestrictedPaths)throw new u("glob: absolute pattern not permitted");i=p.parse(t).root,n=p.relative(i,t)}else e&&(i=await M(r,e));if(!r.unrestrictedPaths&&n.split(/[\\/]/).includes(".."))throw new u('glob: ".." is not permitted in the pattern');let s=[];try{for await(let o of $t(n,{cwd:i,withFileTypes:!0,exclude:a=>a.name===".git"||a.name==="node_modules"})){if(!o.isFile())continue;let a=p.join(o.parentPath,o.name);if(!r.unrestrictedPaths&&!Mt(i,a))continue;let c=0;try{c=(await w.stat(a)).mtimeMs}catch{}s.push({path:a,mtime:c})}}catch(o){throw new u(`glob: ${o instanceof Error?o.message:String(o)}`)}return s.length===0?"no matches":(s.sort((o,a)=>a.mtime-o.mtime),s.slice(0,_t).map(o=>o.path).join(`
13
+ `))}})}function At(r){return O({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:t,path:e},i)=>{if(!t)throw new u("grep: pattern is required");let n=p.resolve(r.workdir);e&&(n=await M(r,e));let s=await Lt();return s?It(s,t,n,i?.signal):Rt(t,n,i?.signal)}})}function It(r,t,e,i){return new Promise((n,s)=>{let o=J.spawn(r,["-n","--no-heading","-e",t,"--",e],{...i?{signal:i}:{}}),a="",c="",f=!1;o.stdout.on("data",l=>{f||(a+=l,a.length>R&&(f=!0,a=a.slice(0,R),o.kill("SIGKILL")))}),o.stderr.on("data",l=>c+=l),o.on("close",l=>{if(i?.aborted)return s(new u("grep: aborted"));if(f)return n(a+`
14
+ [output truncated at ${R} bytes]`);if(l===0)return n(a);if(l===1)return n("no matches");s(new u(`grep: rg failed: ${c||`exit ${l}`}`))}),o.on("error",l=>{if(i?.aborted)return s(new u("grep: aborted"));s(new u(`grep: rg failed: ${l.message}`))})})}async function Rt(r,t,e){let i;try{i=new RegExp(r)}catch(c){throw new u(`grep: invalid regex: ${c instanceof Error?c.message:String(c)}`)}let n=[],s=R,o=c=>(s-=c.length+1,s<0?(n.push(`[output truncated at ${R} bytes]`),!1):(n.push(c),!0));if((await w.stat(t).catch(()=>null))?.isFile()?await Z(t,i,o):await Pt(t,"",c=>Z(p.join(t,c),i,o),e),e?.aborted)throw new u("grep: aborted");return n.length===0?"no matches":n.join(`
15
+ `)}async function Z(r,t,e){let i=P.createReadStream(r,{encoding:"utf8"}),n=Y.createInterface({input:i,crlfDelay:1/0}),s=0;try{for await(let o of n)if(s++,!(o.length>gt)&&t.test(o)&&!e(`${r}:${s}:${o}`))return!1}catch{}finally{i.destroy()}return!0}function Mt(r,t){let e=p.relative(r,t);return e===""||!e.startsWith(".."+p.sep)&&e!==".."&&!p.isAbsolute(e)}var Nt=40,Ft=5e4;async function Pt(r,t,e,i){let n=Ft;async function s(o,a){if(a>Nt)return!0;if(i?.aborted)return!1;let c;try{c=await w.readdir(p.join(r,o),{withFileTypes:!0})}catch{return!0}for(let f of c){if(f.name===".git"||f.name==="node_modules")continue;if(n--<=0||i?.aborted)return!1;let l=o?p.join(o,f.name):f.name;if(f.isDirectory()){if(!await s(l,a+1))return!1}else if(f.isFile()&&await e(l)===!1)return!1}return!0}await s(t,0)}async function Lt(){let r=(process.env.PATH??"").split(p.delimiter);for(let t of r){let e=p.join(t,"rg");try{return await w.access(e,P.constants.X_OK),e}catch{}}return null}export{C as BashSession,ae as betaAgentToolset20260401,kt as betaBashTool,Tt as betaEditTool,xt as betaGlobTool,At as betaGrepTool,Ot as betaReadTool,St as betaWriteTool,K as extractSkillArchive,M as resolvePath,z as resolveSkillVersion,pt as setupSkills};
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{$ as Cn,N as kr,O as vs,P as Os,Q as Ts,X as xn,Y as Qr,Z as Rn,_ as Sn,da as Ns,e as Pn,ea as js}from"./chunk-XWWKIJ5J.js";import"./chunk-NCPOPA4A.js";import"./chunk-X3UA5OZL.js";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 u(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 Ls=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Ls=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 $r(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Er=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 _=class extends Error{},O=class s extends _{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 Ie({message:r,cause:Er(t)});let o=t?.error;return e===400?new mt(e,o,r,n):e===401?new ft(e,o,r,n):e===403?new _t(e,o,r,n):e===404?new gt(e,o,r,n):e===409?new yt(e,o,r,n):e===422?new At(e,o,r,n):e===429?new bt(e,o,r,n):e>=500?new wt(e,o,r,n):new s(e,o,r,n)}},L=class extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Ie=class extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Pe=class extends Ie{constructor({message:e}={}){super({message:e??"Request timed out."})}},mt=class extends O{},ft=class extends O{},_t=class extends O{},gt=class extends O{},yt=class extends O{},At=class extends O{},bt=class extends O{},wt=class extends O{},It=class extends _{constructor(){super("Could not parse response content as the length limit was reached")}},Pt=class extends _{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ae=class extends Error{constructor(e){super(e)}},Fe=class extends O{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let c=t;o=c.error;let l=c.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},vr=class extends _{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var Jo=/^[a-z][a-z0-9+.-]*:/i,kn=s=>Jo.test(s),J=s=>(J=Array.isArray,J(s)),Ks=J;function Zr(s){return typeof s!="object"?{}:s??{}}function Ms(s){if(!s)return!0;for(let e in s)return!1;return!0}function $n(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Or(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var En=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${s} must be an integer`);if(e<0)throw new _(`${s} must be a positive integer`);return e};var vn=s=>{try{return JSON.parse(s)}catch{return}};var ce=s=>new Promise(e=>setTimeout(e,s));var xe="6.45.0";var jn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Xo(){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 Go=()=>{let s=Xo();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"X-Stainless-OS":Tn(Deno.build.os),"X-Stainless-Arch":On(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":xe,"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":xe,"X-Stainless-OS":Tn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":On(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Vo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"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":xe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Vo(){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,c=r[3]||0;return{browser:e,version:`${n}.${o}.${c}`}}}return null}var On=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Tn=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"),Nn,Ln=()=>Nn??(Nn=Go());function es(){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 Fs(...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 ts(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Fs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Us(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 Bs(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 Mn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ds="RFC3986",zs=s=>String(s),qs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:zs},Fn="RFC1738";var rs=(s,e)=>(rs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),rs(s,e)),ue=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Ws=1024,Un=(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(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let c="";for(let l=0;l<o.length;l+=Ws){let m=o.length>=Ws?o.slice(l,l+Ws):o,p=[];for(let I=0;I<m.length;++I){let h=m.charCodeAt(I);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===Fn&&(h===40||h===41)){p[p.length]=m.charAt(I);continue}if(h<128){p[p.length]=ue[h];continue}if(h<2048){p[p.length]=ue[192|h>>6]+ue[128|h&63];continue}if(h<55296||h>=57344){p[p.length]=ue[224|h>>12]+ue[128|h>>6&63]+ue[128|h&63];continue}I+=1,h=65536+((h&1023)<<10|m.charCodeAt(I)&1023),p[p.length]=ue[240|h>>18]+ue[128|h>>12&63]+ue[128|h>>6&63]+ue[128|h&63]}c+=p.join("")}return c};function Bn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Hs(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 zn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},qn=function(s,e){Array.prototype.push.apply(s,J(e)?e:[e])},Dn,F={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Un,encodeValuesOnly:!1,format:Ds,formatter:zs,indices:!1,serializeDate(s){return(Dn??(Dn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Qo(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Js={};function Wn(s,e,t,r,n,o,c,l,m,p,I,h,f,w,g,y,b,P){let A=s,k=P,C=0,Y=!1;for(;(k=k.get(Js))!==void 0&&!Y;){let j=k.get(s);if(C+=1,typeof j<"u"){if(j===C)throw new RangeError("Cyclic object value");Y=!0}typeof k.get(Js)>"u"&&(C=0)}if(typeof p=="function"?A=p(e,A):A instanceof Date?A=f?.(A):t==="comma"&&J(A)&&(A=Hs(A,function(j){return j instanceof Date?f?.(j):j})),A===null){if(o)return m&&!y?m(e,F.encoder,b,"key",w):e;A=""}if(Qo(A)||Bn(A)){if(m){let j=y?e:m(e,F.encoder,b,"key",w);return[g?.(j)+"="+g?.(m(A,F.encoder,b,"value",w))]}return[g?.(e)+"="+g?.(String(A))]}let D=[];if(typeof A>"u")return D;let v;if(t==="comma"&&J(A))y&&m&&(A=Hs(A,m)),v=[{value:A.length>0?A.join(",")||null:void 0}];else if(J(p))v=p;else{let j=Object.keys(A);v=I?j.sort(I):j}let T=l?String(e).replace(/\./g,"%2E"):String(e),H=r&&J(A)&&A.length===1?T+"[]":T;if(n&&J(A)&&A.length===0)return H+"[]";for(let j=0;j<v.length;++j){let M=v[j],wn=typeof M=="object"&&typeof M.value<"u"?M.value:A[M];if(c&&wn===null)continue;let Es=h&&l?M.replace(/\./g,"%2E"):M,Wo=J(A)?typeof t=="function"?t(H,Es):H:H+(h?"."+Es:"["+Es+"]");P.set(s,C);let In=new WeakMap;In.set(Js,P),qn(D,Wn(wn,Wo,t,r,n,o,c,l,t==="comma"&&y&&J(A)?null:m,p,I,h,f,w,g,y,b,In))}return D}function Zo(s=F){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||F.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=Ds;if(typeof s.format<"u"){if(!rs(qs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=qs[t],n=F.filter;(typeof s.filter=="function"||J(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in zn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=F.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let c=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:F.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:F.addQueryPrefix,allowDots:c,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:F.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:F.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?F.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:F.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:F.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:F.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:F.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:F.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:F.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:F.strictNullHandling}}function Hn(s,e={}){let t=s,r=Zo(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):J(r.filter)&&(o=r.filter,n=o);let c=[];if(typeof t!="object"||t===null)return"";let l=zn[r.arrayFormat],m=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let f=0;f<n.length;++f){let w=n[f];r.skipNulls&&t[w]===null||qn(c,Wn(t[w],w,l,m,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 I=c.join(r.delimiter),h=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),I.length>0?h+I:""}function Jn(s){return Hn(s,{arrayFormat:"brackets"})}function Vn(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 Xn;function xt(s){let e;return(Xn??(e=new globalThis.TextEncoder,Xn=e.encode.bind(e)))(s)}var Gn;function Xs(s){let e;return(Gn??(e=new globalThis.TextDecoder,Gn=e.decode.bind(e)))(s)}var Q,Z,Ue=class{constructor(){Q.set(this,void 0),Z.set(this,void 0),x(this,Q,new Uint8Array,"f"),x(this,Z,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?xt(e):e;x(this,Q,Vn([u(this,Q,"f"),t]),"f");let r=[],n;for(;(n=ti(u(this,Q,"f"),u(this,Z,"f")))!=null;){if(n.carriage&&u(this,Z,"f")==null){x(this,Z,n.index,"f");continue}if(u(this,Z,"f")!=null&&(n.index!==u(this,Z,"f")+1||n.carriage)){r.push(Xs(u(this,Q,"f").subarray(0,u(this,Z,"f")-1))),x(this,Q,u(this,Q,"f").subarray(u(this,Z,"f")),"f"),x(this,Z,null,"f");continue}let o=u(this,Z,"f")!==null?n.preceding-1:n.preceding,c=Xs(u(this,Q,"f").subarray(0,o));r.push(c),x(this,Q,u(this,Q,"f").subarray(n.index),"f"),x(this,Z,null,"f")}return r}flush(){return u(this,Q,"f").length?this.decode(`
5
+ `):[]}};Q=new WeakMap,Z=new WeakMap;Ue.NEWLINE_CHARS=new Set([`
6
+ `,"\r"]);Ue.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ti(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 Yn(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 ns={off:0,error:200,warn:300,info:400,debug:500},Gs=(s,e,t)=>{if(s){if($n(ns,s))return s;N(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(ns))}`)}};function Tr(){}function ss(s,e,t){return!e||ns[s]>ns[t]?Tr:e[s].bind(e)}var ri={error:Tr,warn:Tr,info:Tr,debug:Tr},Qn=new WeakMap;function N(s){let e=s.logger,t=s.logLevel??"off";if(!e)return ri;let r=Qn.get(e);if(r&&r[0]===t)return r[1];let n={error:ss("error",e,t),warn:ss("warn",e,t),info:ss("info",e,t),debug:ss("debug",e,t)};return Qn.set(e,[t,n]),n}var me=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()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Nr,le=class s{constructor(e,t,r){this.iterator=e,Nr.set(this,void 0),this.controller=t,x(this,Nr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,c=r?N(r):console;async function*l(){if(o)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{for await(let p of si(e,t))if(!m){if(p.data.startsWith("[DONE]")){m=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let I;try{I=JSON.parse(p.data)}catch(h){throw c.error("Could not parse message into JSON:",p.data),c.error("From chunk:",p.raw),h}if(I&&I.error)throw new O(void 0,I.error,void 0,e.headers);yield n?{event:p.event,data:I}:I}else{let I;try{I=JSON.parse(p.data)}catch(h){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),h}if(p.event=="error")throw new O(void 0,I.error,I.message,void 0);yield{event:p.event,data:I}}}m=!0}catch(p){if($r(p))return;throw p}finally{m||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new Ue,m=Us(e);for await(let p of m)for(let I of l.decode(p))yield I;for(let p of l.flush())yield p}async function*c(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let m of o())l||m&&(yield JSON.parse(m));l=!0}catch(m){if($r(m))return;throw m}finally{l||t.abort()}}return new s(c,t,r)}[(Nr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let c=r.next();e.push(c),t.push(c)}return o.shift()}});return[new s(()=>n(e),this.controller,u(this,Nr,"f")),new s(()=>n(t),this.controller,u(this,Nr,"f"))]}toReadableStream(){let e=this,t;return Fs({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let c=xt(JSON.stringify(n)+`
7
+ `);r.enqueue(c)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*si(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("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 _("Attempted to iterate over a response with no body");let t=new Vs,r=new Ue,n=Us(s.body);for await(let o of ni(n))for(let c of r.decode(o)){let l=t.decode(c);l&&(yield l)}for(let o of r.flush()){let c=t.decode(o);c&&(yield c)}}async function*ni(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"?xt(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Yn(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Vs=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(`
8
+ `),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]=oi(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function oi(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function os(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,c=await(async()=>{if(e.options.stream)return N(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 m=t.headers.get("content-type")?.split(";")[0]?.trim();if(m?.includes("application/json")||m?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let f=await t.json();return Ys(f,t)}return await t.text()})();return N(s).debug(`[${r}] response parsed`,me({retryOfRequestLogID:n,url:t.url,status:t.status,body:c,durationMs:Date.now()-o})),c}function Ys(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 jr,Be=class s extends Promise{constructor(e,t,r=os){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,jr.set(this,void 0),x(this,jr,e,"f")}_thenUnwrap(e){return new s(u(this,jr,"f"),this.responsePromise,async(t,r)=>Ys(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(u(this,jr,"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)}};jr=new WeakMap;var is,Rt=class{constructor(e,t,r,n){is.set(this,void 0),x(this,is,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 _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,is,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(is=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Lr=class extends Be{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await os(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},X=class extends Rt{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 Rt{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:{...Zr(this.options.query),after:t}}:null}},E=class extends Rt{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:{...Zr(this.options.query),after:e}}:null}},K=class extends Rt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Zr(this.options.query),after:e}}:null}};var ai={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},ci="urn:ietf:params:oauth:grant-type:token-exchange",as=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??es()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),t={grant_type:ci,subject_token:e,subject_token_type:ai[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let m=await r.text(),p;try{p=JSON.parse(m)}catch{}throw r.status===400||r.status===401||r.status===403?new Fe(r.status,p,r.headers):O.generate(r.status,p,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new _("Token exchange response missing 'access_token' field");let o=n.access_token,c=n.expires_in??3600,l=Date.now()+c*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var en=()=>{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 St(s,e,t){return en(),new File(s,e??"unknown_file",t)}function Kr(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 cs=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Re=async(s,e)=>Qs(s.body)?{...s,body:await eo(s.body,e)}:s,G=async(s,e)=>({...s,body:await eo(s.body,e)}),Zn=new WeakMap;function ui(s){let e=typeof s=="function"?s:s.fetch,t=Zn.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 Zn.set(e,r),r}var eo=async(s,e)=>{if(!await ui(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])=>Zs(t,r,n))),t},to=s=>s instanceof Blob&&"name"in s,li=s=>typeof s=="object"&&s!==null&&(s instanceof Response||cs(s)||to(s)),Qs=s=>{if(li(s))return!0;if(Array.isArray(s))return s.some(Qs);if(s&&typeof s=="object"){for(let e in s)if(Qs(s[e]))return!0}return!1},Zs=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,St([await t.blob()],Kr(t)));else if(cs(t))s.append(e,St([await new Response(ts(t)).blob()],Kr(t)));else if(to(t))s.append(e,t,Kr(t));else if(Array.isArray(t))await Promise.all(t.map(r=>Zs(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>Zs(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 ro=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",pi=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&ro(s),hi=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function us(s,e,t){if(en(),s=await s,pi(s))return s instanceof File?s:St([await s.arrayBuffer()],s.name);if(hi(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),St(await tn(n),e,t)}let r=await tn(s);if(e||(e=Kr(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return St(r,e,t)}async function tn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(ro(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(cs(s))for await(let t of s)e.push(...await tn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${di(s)}`)}return e}function di(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var a=class{constructor(e){this._client=e}};function no(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var so=Object.freeze(Object.create(null)),fi=(s=no)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],c=t.reduce((I,h,f)=>{/[?#]/.test(h)&&(n=!0);let w=r[f],g=(n?encodeURIComponent:s)(""+w);return f!==r.length&&(w==null||typeof w=="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??so)??so)?.toString)&&(g=w+"",o.push({start:I.length+h.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),I+h+(f===r.length?"":g)},""),l=c.split(/[?#]/,1)[0],m=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=m.exec(l))!==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((I,h)=>I.start-h.start),o.length>0){let I=0,h=o.reduce((f,w)=>{let g=" ".repeat(w.start-I),y="^".repeat(w.length);return I=w.start+w.length,f+g+y},"");throw new _(`Path parameters result in path with invalid segments:
9
+ ${o.map(f=>f.error).join(`
10
+ `)}
11
+ ${c}
12
+ ${h}`)}return c},i=fi(no);var De=class extends a{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,S,{query:t,...r,__security:{bearerAuth:!0}})}};function Mr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function Fr(s){return s?.$brand==="auto-parseable-response-format"}function ze(s){return s?.$brand==="auto-parseable-tool"}function io(s,e){return!e||!rn(e)?{...s,choices:s.choices.map(t=>(co(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ur(s,e)}function Ur(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new It;if(r.finish_reason==="content_filter")throw new Pt;return co(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>yi(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?gi(e,r.message.content):null}}});return{...s,choices:t}}function gi(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 yi(s,e){let t=s.tools?.find(r=>Mr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ze(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function ao(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Mr(r)&&r.function?.name===e.function.name);return Mr(t)&&(ze(t)||t?.function.strict||!1)}function rn(s){return Fr(s.response_format)?!0:s.tools?.some(e=>ze(e)||e.type==="function"&&e.function.strict===!0)??!1}function co(s){for(let e of s||[])if(e.type!=="function")throw new _(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function uo(s){for(let e of s??[]){if(e.type!=="function")throw new _(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new _(`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",sn=s=>s?.role==="tool";var ls,ps,hs,Br,Dr,ds,zr,fe,ms,qr,fs,_s,kt,lo,po,Se=class{constructor(){ls.add(this),this.controller=new AbortController,ps.set(this,void 0),hs.set(this,()=>{}),Br.set(this,()=>{}),Dr.set(this,void 0),ds.set(this,()=>{}),zr.set(this,()=>{}),fe.set(this,{}),ms.set(this,[]),qr.set(this,!1),fs.set(this,!1),_s.set(this,!1),kt.set(this,!1),x(this,ps,new Promise((e,t)=>{x(this,hs,e,"f"),x(this,Br,t,"f")}),"f"),x(this,Dr,new Promise((e,t)=>{x(this,ds,e,"f"),x(this,zr,t,"f")}),"f"),u(this,ps,"f").catch(()=>{}),u(this,Dr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},u(this,ls,"m",po).bind(this))},0)}_connected(){this.ended||(u(this,hs,"f").call(this),this._emit("connect"))}get ended(){return u(this,qr,"f")}get errored(){return u(this,fs,"f")}get aborted(){return u(this,_s,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),u(this,ms,"f").push({signal:e,listener:t})}on(e,t){return(u(this,fe,"f")[e]||(u(this,fe,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,fe,"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(u(this,fe,"f")[e]||(u(this,fe,"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 u(this,Dr,"f")}_emit(e,...t){if(u(this,qr,"f"))return;e==="end"&&(u(this,ls,"m",lo).call(this),x(this,qr,!0,"f"),u(this,ds,"f").call(this));let r=u(this,fe,"f")[e];if(r&&(u(this,fe,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,kt,"f")&&!r?.length&&Promise.reject(n),u(this,Br,"f").call(this,n),u(this,zr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,kt,"f")&&!r?.length&&Promise.reject(n),u(this,Br,"f").call(this,n),u(this,zr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};ps=new WeakMap,hs=new WeakMap,Br=new WeakMap,Dr=new WeakMap,ds=new WeakMap,zr=new WeakMap,fe=new WeakMap,ms=new WeakMap,qr=new WeakMap,fs=new WeakMap,_s=new WeakMap,kt=new WeakMap,ls=new WeakSet,lo=function(){for(let{signal:e,listener:t}of u(this,ms,"f").splice(0))e.removeEventListener("abort",t)},po=function(e){if(x(this,fs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return x(this,_s,!0,"f"),this._emit("abort",e);if(e instanceof _)return this._emit("error",e);if(e instanceof Error){let t=new _(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new _(String(e)))};function ho(s){return typeof s.parse=="function"}var V,nn,gs,on,an,cn,mo,fo,Ai=10,$t=class extends Se{constructor(){super(...arguments),V.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),sn(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 _("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,V,"m",nn).call(this)}async finalMessage(){return await this.done(),u(this,V,"m",gs).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,V,"m",on).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,V,"m",an).call(this)}async totalUsage(){return await this.done(),u(this,V,"m",cn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=u(this,V,"m",gs).call(this);t&&this._emit("finalMessage",t);let r=u(this,V,"m",nn).call(this);r&&this._emit("finalContent",r);let n=u(this,V,"m",on).call(this);n&&this._emit("finalFunctionToolCall",n);let o=u(this,V,"m",an).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(c=>c.usage)&&this._emit("totalUsage",u(this,V,"m",cn).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),u(this,V,"m",mo).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ur(n,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,n){let o="tool",{tool_choice:c="auto",stream:l,...m}=t,p=typeof c!="string"&&c.type==="function"&&c?.function?.name,{maxChatCompletions:I=Ai,afterCompletion:h}=n||{},f=t.tools.map(b=>{if(ze(b)){if(!b.$callback)throw new _("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:b.$callback,name:b.function.name,description:b.function.description||"",parameters:b.function.parameters,parse:b.$parseRaw,strict:!0}}}return b}),w={};for(let b of f)b.type==="function"&&(w[b.function.name||b.function.function.name]=b.function);let g="tools"in t?f.map(b=>b.type==="function"?{type:"function",function:{name:b.function.name||b.function.function.name,parameters:b.function.parameters,description:b.function.description,strict:b.function.strict}}:b):void 0;for(let b of t.messages)this._addMessage(b,!1);let y=async b=>{if(b.type!=="function")return{message:void 0,functionCalled:!1};let P=b.id,{name:A,arguments:k}=b.function,C=w[A];if(!C){let v=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(w).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:P,content:v},functionCalled:!1}}if(p&&p!==A){let v=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:o,tool_call_id:P,content:v},functionCalled:!1}}let Y;if(ho(C)){let v;try{v=await C.parse(k)}catch(T){let H=T instanceof Error?T.message:String(T);return{message:{role:o,tool_call_id:P,content:H},functionCalled:!1}}Y=await C.function(v,r)}else Y=await C.function(k,r);let D=u(this,V,"m",fo).call(this,Y);return{message:{role:o,tool_call_id:P,content:D},functionCalled:!0}};for(let b=0;b<I;++b){let P=await this._createChatCompletion(e,{...m,tool_choice:c,tools:g,messages:[...this.messages]},n),A=P.choices[0]?.message;if(!A)throw new _("missing message in ChatCompletion response");if(!A.tool_calls?.length){await h?.(P,r);return}if(p||t.parallel_tool_calls===!1)for(let k of A.tool_calls){let C=await y(k);if(C.message&&this._addMessage(C.message),p&&C.functionCalled){await h?.(P,r);return}}else{let k=await Promise.allSettled(A.tool_calls.map(y));for(let C of k)if(C.status==="rejected")throw C.reason;for(let C of k)C.status==="fulfilled"&&C.value.message&&this._addMessage(C.value.message)}await h?.(P,r)}}};V=new WeakSet,nn=function(){return u(this,V,"m",gs).call(this).content??null},gs=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 _("stream ended without producing a ChatCompletionMessage with role=assistant")},on=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ct(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},an=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(sn(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}},cn=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},mo=function(e){if(e.n!=null&&e.n>1)throw new _("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},fo=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Wr=class s extends $t{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,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Ct(e)&&e.content&&this._emit("content",e.content)}};var B={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},un=class extends Error{},ln=class extends Error{};function bi(s,e=B.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return wi(s.trim(),e)}var wi=(s,e)=>{let t=s.length,r=0,n=f=>{throw new un(`${f} at position ${r}`)},o=f=>{throw new ln(`${f} at position ${r}`)},c=()=>(h(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?m():s[r]==="["?p():s.substring(r,r+4)==="null"||B.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||B.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||B.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||B.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||B.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||B.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):I()),l=()=>{let f=r,w=!1;for(r++;r<t&&(s[r]!=='"'||w&&s[r-1]==="\\");)w=s[r]==="\\"?!w:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(f,++r-Number(w)))}catch(g){o(String(g))}else if(B.STR&e)try{return JSON.parse(s.substring(f,r-Number(w))+'"')}catch{return JSON.parse(s.substring(f,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},m=()=>{r++,h();let f={};try{for(;s[r]!=="}";){if(h(),r>=t&&B.OBJ&e)return f;let w=l();h(),r++;try{let g=c();Object.defineProperty(f,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(B.OBJ&e)return f;throw g}h(),s[r]===","&&r++}}catch{if(B.OBJ&e)return f;n("Expected '}' at end of object")}return r++,f},p=()=>{r++;let f=[];try{for(;s[r]!=="]";)f.push(c()),h(),s[r]===","&&r++}catch{if(B.ARR&e)return f;n("Expected ']' at end of array")}return r++,f},I=()=>{if(r===0){s==="-"&&B.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(w){if(B.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(w))}}let f=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(B.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(f,r))}catch{s.substring(f,r)==="-"&&B.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(f,s.lastIndexOf("e")))}catch(g){o(String(g))}}},h=()=>{for(;r<t&&`
13
+ \r `.includes(s[r]);)r++};return c()},pn=s=>bi(s,B.ALL^B.NUM);var U,_e,Et,Ce,hn,ys,dn,mn,fn,As,_n,_o,qe=class s extends $t{constructor(e){super(),U.add(this),_e.set(this,void 0),Et.set(this,void 0),Ce.set(this,void 0),x(this,_e,e,"f"),x(this,Et,[],"f")}get currentChatCompletionSnapshot(){return u(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,this._listenForAbort(r?.signal),u(this,U,"m",hn).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)u(this,U,"m",dn).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addChatCompletion(u(this,U,"m",As).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,U,"m",hn).call(this),this._connected();let r=le.fromReadableStream(e,this.controller),n;for await(let o of r)n&&n!==o.id&&this._addChatCompletion(u(this,U,"m",As).call(this)),u(this,U,"m",dn).call(this,o),n=o.id;if(r.controller.signal?.aborted)throw new L;return this._addChatCompletion(u(this,U,"m",As).call(this))}[(_e=new WeakMap,Et=new WeakMap,Ce=new WeakMap,U=new WeakSet,hn=function(){this.ended||x(this,Ce,void 0,"f")},ys=function(t){let r=u(this,Et,"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},u(this,Et,"f")[t.index]=r,r)},dn=function(t){if(this.ended)return;let r=u(this,U,"m",_o).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 c=u(this,U,"m",ys).call(this,o);o.finish_reason&&(u(this,U,"m",fn).call(this,o),c.current_tool_call_index!=null&&u(this,U,"m",mn).call(this,o,c.current_tool_call_index));for(let l of n.delta.tool_calls??[])c.current_tool_call_index!==l.index&&(u(this,U,"m",fn).call(this,o),c.current_tool_call_index!=null&&u(this,U,"m",mn).call(this,o,c.current_tool_call_index)),c.current_tool_call_index=l.index;for(let l of n.delta.tool_calls??[]){let m=o.message.tool_calls?.[l.index];m?.type&&(m?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:m.function?.name,index:l.index,arguments:m.function.arguments,parsed_arguments:m.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(m?.type,void 0))}}},mn=function(t,r){if(u(this,U,"m",ys).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 c=u(this,_e,"f")?.tools?.find(l=>Mr(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:ze(c)?c.$parseRaw(o.function.arguments):c?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},fn=function(t){let r=u(this,U,"m",ys).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=u(this,U,"m",_n).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}))},As=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=u(this,Ce,"f");if(!t)throw new _("request ended without sending any chunks");return x(this,Ce,void 0,"f"),x(this,Et,[],"f"),Ii(t,u(this,_e,"f"))},_n=function(){let t=u(this,_e,"f")?.response_format;return Fr(t)?t:null},_o=function(t){var r,n,o,c;let l=u(this,Ce,"f"),{choices:m,...p}=t;l?Object.assign(l,p):l=x(this,Ce,{...p,choices:[]},"f");for(let{delta:I,finish_reason:h,index:f,logprobs:w=null,...g}of t.choices){let y=l.choices[f];if(y||(y=l.choices[f]={finish_reason:h,index:f,message:{},logprobs:w,...g}),w)if(!y.logprobs)y.logprobs=Object.assign({},w);else{let{content:D,refusal:v,...T}=w;Object.assign(y.logprobs,T),D&&((r=y.logprobs).content??(r.content=[]),y.logprobs.content.push(...D)),v&&((n=y.logprobs).refusal??(n.refusal=[]),y.logprobs.refusal.push(...v))}if(h&&(y.finish_reason=h,u(this,_e,"f")&&rn(u(this,_e,"f")))){if(h==="length")throw new It;if(h==="content_filter")throw new Pt}if(Object.assign(y,g),!I)continue;let{content:b,refusal:P,function_call:A,role:k,tool_calls:C,...Y}=I;if(Object.assign(y.message,Y),P&&(y.message.refusal=(y.message.refusal||"")+P),k&&(y.message.role=k),A&&(y.message.function_call?(A.name&&(y.message.function_call.name=A.name),A.arguments&&((o=y.message.function_call).arguments??(o.arguments=""),y.message.function_call.arguments+=A.arguments)):y.message.function_call=A),b&&(y.message.content=(y.message.content||"")+b,!y.message.refusal&&u(this,U,"m",_n).call(this)&&(y.message.parsed=y.message.content.trim()?pn(y.message.content):null)),C){y.message.tool_calls||(y.message.tool_calls=[]);for(let{index:D,id:v,type:T,function:H,...j}of C){let M=(c=y.message.tool_calls)[D]??(c[D]={});Object.assign(M,j),v&&(M.id=v),T&&(M.type=T),H&&(M.function??(M.function={name:H.name??"",arguments:""})),H?.name&&(M.function.name=H.name),H?.arguments&&(M.function.arguments+=H.arguments,ao(u(this,_e,"f"),M)&&(M.function.parsed_arguments=pn(M.function.arguments)))}}}return l},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,c)=>t.push({resolve:o,reject:c})).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 Ii(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:c,...l}=s,m={...l,id:t,choices:r.map(({message:p,finish_reason:I,index:h,logprobs:f,...w})=>{if(!I)throw new _(`missing finish_reason for choice ${h}`);let{content:g=null,function_call:y,tool_calls:b,...P}=p,A=p.role;if(!A)throw new _(`missing role for choice ${h}`);if(y){let{arguments:k,name:C}=y;if(k==null)throw new _(`missing function_call.arguments for choice ${h}`);if(!C)throw new _(`missing function_call.name for choice ${h}`);return{...w,message:{content:g,function_call:{arguments:k,name:C},role:A,refusal:p.refusal??null},finish_reason:I,index:h,logprobs:f}}return b?{...w,index:h,finish_reason:I,logprobs:f,message:{...P,role:A,content:g,refusal:p.refusal??null,tool_calls:b.map((k,C)=>{let{function:Y,type:D,id:v,...T}=k,{arguments:H,name:j,...M}=Y||{};if(v==null)throw new _(`missing choices[${h}].tool_calls[${C}].id
14
+ ${bs(s)}`);if(D==null)throw new _(`missing choices[${h}].tool_calls[${C}].type
15
+ ${bs(s)}`);if(j==null)throw new _(`missing choices[${h}].tool_calls[${C}].function.name
16
+ ${bs(s)}`);if(H==null)throw new _(`missing choices[${h}].tool_calls[${C}].function.arguments
17
+ ${bs(s)}`);return{...T,id:v,type:D,function:{...M,name:j,arguments:H}}})}}:{...w,message:{...P,content:g,role:A,refusal:p.refusal??null},finish_reason:I,index:h,logprobs:f}}),created:n,model:o,object:"chat.completion",...c?{system_fingerprint:c}:{}};return io(m,e)}function bs(s){return JSON.stringify(s)}var Hr=class s extends qe{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,n,o)),n}};var ge=class extends a{constructor(){super(...arguments),this.messages=new De(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return uo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ur(r,e))}runTools(e,t){return e.stream?Hr.runTools(this._client,e,t):Wr.runTools(this._client,e,t)}stream(e,t){return qe.createChatCompletion(this._client,e,t)}};ge.Messages=De;var ke=class extends a{constructor(){super(...arguments),this.completions=new ge(this._client)}};ke.Completions=ge;var vt=class extends a{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",S,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ot=class extends a{list(e={},t){return this._client.getAPIList("/organization/audit_logs",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Tt=class extends a{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",X,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",X,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var Nt=class extends a{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}};var jt=class extends a{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Lt=class extends a{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",K,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends a{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Mt=class extends a{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends a{create(e,t,r){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends a{create(e,t,r){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/users`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var $e=class extends a{constructor(){super(...arguments),this.users=new Ut(this._client),this.roles=new Ft(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",K,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};$e.Users=Ut;$e.Roles=Ft;var Bt=class extends a{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Dt=class extends a{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends a{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends a{create(e,t,r){return this._client.post(i`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/projects/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends a{create(e,t,r){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends a{create(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends a{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,K,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var We=class extends a{constructor(){super(...arguments),this.roles=new Vt(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/groups`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};We.Roles=Vt;var Yt=class extends a{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,K,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var He=class extends a{constructor(){super(...arguments),this.roles=new Yt(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/users`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};He.Roles=Yt;var z=class extends a{constructor(){super(...arguments),this.users=new He(this._client),this.serviceAccounts=new Xt(this._client),this.apiKeys=new Bt(this._client),this.rateLimits=new Ht(this._client),this.modelPermissions=new Wt(this._client),this.hostedToolPermissions=new qt(this._client),this.groups=new We(this._client),this.roles=new Jt(this._client),this.dataRetention=new zt(this._client),this.spendAlerts=new Gt(this._client),this.certificates=new Dt(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};z.Users=He;z.ServiceAccounts=Xt;z.APIKeys=Bt;z.RateLimits=Ht;z.ModelPermissions=Wt;z.HostedToolPermissions=qt;z.Groups=We;z.Roles=Jt;z.DataRetention=zt;z.SpendAlerts=Gt;z.Certificates=Dt;var Qt=class extends a{create(e,t,r){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/users/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Je=class extends a{constructor(){super(...arguments),this.roles=new Qt(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Je.Roles=Qt;var q=class extends a{constructor(){super(...arguments),this.auditLogs=new Ot(this._client),this.adminAPIKeys=new vt(this._client),this.usage=new Mt(this._client),this.invites=new jt(this._client),this.users=new Je(this._client),this.groups=new $e(this._client),this.roles=new Lt(this._client),this.dataRetention=new Nt(this._client),this.spendAlerts=new Kt(this._client),this.certificates=new Tt(this._client),this.projects=new z(this._client)}};q.AuditLogs=Ot;q.AdminAPIKeys=vt;q.Usage=Mt;q.Invites=jt;q.Users=Je;q.Groups=$e;q.Roles=Lt;q.DataRetention=Nt;q.SpendAlerts=Kt;q.Certificates=Tt;q.Projects=z;var Ee=class extends a{constructor(){super(...arguments),this.organization=new q(this._client)}};Ee.Organization=q;var go=Symbol("brand.privateNullableHeaders");function*Qi(s){if(!s)return;if(go 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():Ks(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=Ks(r[1])?r[1]:[r[1]],c=!1;for(let l of o)l!==void 0&&(e&&!c&&(c=!0,yield[n,null]),yield[n,l])}}var d=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,c]of Qi(r)){let l=o.toLowerCase();n.has(l)||(e.delete(o),n.add(l)),c===null?(e.delete(o),t.add(l)):(e.append(o,c),t.delete(l))}}return{[go]:!0,values:e,nulls:t}};var Zt=class extends a{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:d([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var er=class extends a{create(e,t){return this._client.post("/audio/transcriptions",G({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var tr=class extends a{create(e,t){return this._client.post("/audio/translations",G({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var pe=class extends a{constructor(){super(...arguments),this.transcriptions=new er(this._client),this.translations=new tr(this._client),this.speech=new Zt(this._client)}};pe.Transcriptions=er;pe.Translations=tr;pe.Speech=Zt;var Xe=class extends a{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var rr=class extends a{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var sr=class extends a{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var nr=class extends a{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ve=class extends a{constructor(){super(...arguments),this.sessions=new sr(this._client),this.transcriptionSessions=new nr(this._client)}};ve.Sessions=sr;ve.TranscriptionSessions=nr;var or=class extends a{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var ir=class extends a{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",E,{query:e,...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,E,{query:t,...r,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Oe=class extends a{constructor(){super(...arguments),this.sessions=new or(this._client),this.threads=new ir(this._client)}};Oe.Sessions=or;Oe.Threads=ir;var ar=class extends a{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,S,{query:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var cr=class extends a{retrieve(e,t,r){let{thread_id:n,run_id:o,...c}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:c,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,S,{query:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var yo=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 se=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()||void 0};var W,Ve,gn,he,ws,ne,Ye,ur,Ge,xs,ee,Is,Ps,Gr,Jr,Xr,Ao,bo,wo,Io,Po,xo,Ro,ye=class extends Se{constructor(){super(...arguments),W.add(this),gn.set(this,[]),he.set(this,{}),ws.set(this,{}),ne.set(this,void 0),Ye.set(this,void 0),ur.set(this,void 0),Ge.set(this,void 0),xs.set(this,void 0),ee.set(this,void 0),Is.set(this,void 0),Ps.set(this,void 0),Gr.set(this,void 0)}[(gn=new WeakMap,he=new WeakMap,ws=new WeakMap,ne=new WeakMap,Ye=new WeakMap,ur=new WeakMap,Ge=new WeakMap,xs=new WeakMap,ee=new WeakMap,Is=new WeakMap,Ps=new WeakMap,Gr=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,c)=>t.push({resolve:o,reject:c})).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 Ve;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=le.fromReadableStream(e,this.controller);for await(let n of r)u(this,W,"m",Jr).call(this,n);if(r.controller.signal?.aborted)throw new L;return this._addRun(u(this,W,"m",Xr).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Ve;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},c=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of c)u(this,W,"m",Jr).call(this,l);if(c.controller.signal?.aborted)throw new L;return this._addRun(u(this,W,"m",Xr).call(this))}static createThreadAssistantStream(e,t,r){let n=new Ve;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 Ve;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return u(this,Is,"f")}currentRun(){return u(this,Ps,"f")}currentMessageSnapshot(){return u(this,ne,"f")}currentRunStepSnapshot(){return u(this,Gr,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,he,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,ws,"f"))}async finalRun(){if(await this.done(),!u(this,Ye,"f"))throw Error("Final run was not received.");return u(this,Ye,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let c of o)u(this,W,"m",Jr).call(this,c);if(o.controller.signal?.aborted)throw new L;return this._addRun(u(this,W,"m",Xr).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},c=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of c)u(this,W,"m",Jr).call(this,l);if(c.controller.signal?.aborted)throw new L;return this._addRun(u(this,W,"m",Xr).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(Or(o)&&Or(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(c=>typeof c=="string"||typeof c=="number")){o.push(...n);continue}for(let c of n){if(!Or(c))throw new Error(`Expected array delta entry to be an object but got: ${c}`);let l=c.index;if(l==null)throw console.error(c),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let m=o[l];m==null?o.push(c):o[l]=this.accumulateDelta(m,c)}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)}};Ve=ye,Jr=function(e){if(!this.ended)switch(x(this,Is,e,"f"),u(this,W,"m",wo).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":u(this,W,"m",Ro).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":u(this,W,"m",bo).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":u(this,W,"m",Ao).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Xr=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");if(!u(this,Ye,"f"))throw Error("Final run has not been received");return u(this,Ye,"f")},Ao=function(e){let[t,r]=u(this,W,"m",Po).call(this,e,u(this,ne,"f"));x(this,ne,t,"f"),u(this,ws,"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,c=t.content[n.index];if(c&&c.type=="text")this._emit("textDelta",o,c.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=u(this,ur,"f")){if(u(this,Ge,"f"))switch(u(this,Ge,"f").type){case"text":this._emit("textDone",u(this,Ge,"f").text,u(this,ne,"f"));break;case"image_file":this._emit("imageFileDone",u(this,Ge,"f").image_file,u(this,ne,"f"));break}x(this,ur,n.index,"f")}x(this,Ge,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,ur,"f")!==void 0){let n=e.data.content[u(this,ur,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,u(this,ne,"f"));break;case"text":this._emit("textDone",n.text,u(this,ne,"f"));break}}u(this,ne,"f")&&this._emit("messageDone",e.data),x(this,ne,void 0,"f")}},bo=function(e){let t=u(this,W,"m",Io).call(this,e);switch(x(this,Gr,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==u(this,xs,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(u(this,ee,"f")&&this._emit("toolCallDone",u(this,ee,"f")),x(this,xs,o.index,"f"),x(this,ee,t.step_details.tool_calls[o.index],"f"),u(this,ee,"f")&&this._emit("toolCallCreated",u(this,ee,"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,Gr,void 0,"f"),e.data.step_details.type=="tool_calls"&&u(this,ee,"f")&&(this._emit("toolCallDone",u(this,ee,"f")),x(this,ee,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},wo=function(e){u(this,gn,"f").push(e),this._emit("event",e)},Io=function(e){switch(e.event){case"thread.run.step.created":return u(this,he,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=u(this,he,"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=Ve.accumulateDelta(t,r.delta);u(this,he,"f")[e.data.id]=n}return u(this,he,"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":u(this,he,"f")[e.data.id]=e.data;break}if(u(this,he,"f")[e.data.id])return u(this,he,"f")[e.data.id];throw new Error("No snapshot available")},Po=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 c=t.content[o.index];t.content[o.index]=u(this,W,"m",xo).call(this,o,c)}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")},xo=function(e,t){return Ve.accumulateDelta(t,e)},Ro=function(e){switch(x(this,Ps,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,Ye,e.data,"f"),u(this,ee,"f")&&(this._emit("toolCallDone",u(this,ee,"f")),x(this,ee,void 0,"f"));break;case"thread.run.cancelling":break}};var Qe=class extends a{constructor(){super(...arguments),this.steps=new cr(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,S,{query:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}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=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:c}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=c.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ce(l);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(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!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)}};Qe.Steps=cr;var Te=class extends a{constructor(){super(...arguments),this.runs=new Qe(this._client),this.messages=new ar(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!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)}};Te.Runs=Qe;Te.Messages=ar;var oe=class extends a{constructor(){super(...arguments),this.realtime=new ve(this._client),this.chatkit=new Oe(this._client),this.assistants=new rr(this._client),this.threads=new Te(this._client)}};oe.Realtime=ve;oe.ChatKit=Oe;oe.Assistants=rr;oe.Threads=Te;var Ze=class extends a{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var lr=class extends a{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var et=class extends a{constructor(){super(...arguments),this.content=new lr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/containers/${e}/files`,S,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};et.Content=lr;var Ne=class extends a{constructor(){super(...arguments),this.files=new et(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/containers/${e}`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Ne.Files=et;var pr=class extends a{create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/conversations/${e}/items`,E,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var je=class extends a{constructor(){super(...arguments),this.items=new pr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};je.Items=pr;var tt=class extends a{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&N(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t,__security:{bearerAuth:!0}});return r?o:(N(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(c=>(c&&c.data&&c.data.forEach(l=>{let m=l.embedding;l.embedding=yo(m)}),c)))}};var hr=class extends a{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,S,{query:o,...r,__security:{bearerAuth:!0}})}};var rt=class extends a{constructor(){super(...arguments),this.outputItems=new hr(this._client)}create(e,t,r){return this._client.post(i`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/evals/${e}/runs`,S,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};rt.OutputItems=hr;var Le=class extends a{constructor(){super(...arguments),this.runs=new rt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Le.Runs=rt;var st=class extends a{create(e,t){return this._client.post("/files",G({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(i`/files/${e}/content`,{...t,headers:d([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),c=await this.retrieve(e);for(;!c.status||!n.has(c.status);)if(await ce(t),c=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 c}};var dr=class extends a{};var mr=class extends a{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};var nt=class extends a{constructor(){super(...arguments),this.graders=new mr(this._client)}};nt.Graders=mr;var fr=class extends a{create(e,t,r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ot=class extends a{constructor(){super(...arguments),this.permissions=new fr(this._client)}};ot.Permissions=fr;var _r=class extends a{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r,__security:{bearerAuth:!0}})}};var it=class extends a{constructor(){super(...arguments),this.checkpoints=new _r(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,S,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};it.Checkpoints=_r;var ie=class extends a{constructor(){super(...arguments),this.methods=new dr(this._client),this.jobs=new it(this._client),this.checkpoints=new ot(this._client),this.alpha=new nt(this._client)}};ie.Methods=dr;ie.Jobs=it;ie.Checkpoints=ot;ie.Alpha=nt;var gr=class extends a{};var Ke=class extends a{constructor(){super(...arguments),this.graderModels=new gr(this._client)}};Ke.GraderModels=gr;var at=class extends a{createVariation(e,t){return this._client.post("/images/variations",G({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",G({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var ct=class extends a{retrieve(e,t){return this._client.get(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",X,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var ut=class extends a{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var yr=class extends a{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Ar=class extends a{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ae=class extends a{constructor(){super(...arguments),this.clientSecrets=new Ar(this._client),this.calls=new yr(this._client)}};Ae.ClientSecrets=Ar;Ae.Calls=yr;function So(s,e){if(!e||!$a(e)){let t={...s,output_parsed:null,output:s.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)};return Co(s,t)&&te(t),t}return yn(s,e)}function yn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:t?Oa(e,o):null};if(o.type==="message"){let c=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?ka(e,l.text):null}:l);return{...o,content:c}}return o}),n=Object.assign({},s,{output:r});return Co(s,n)&&te(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let c of o.content)if(c.type==="output_text"&&c.parsed!==null)return c.parsed}return null}}),n}function ka(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function $a(s){return!!Fr(s.text?.format)}function Ea(s){return s?.$brand==="auto-parseable-tool"}function va(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Oa(s,e){let t=va(s.tools??[],e.name);return{...e,...e,parsed_arguments:Ea(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Co(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function te(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("")}function $o(s,e){if(!e){if(s.type!=="response.created")throw new _(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return ko(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&te(e);break}case"response.output_item.done":{$(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&te(e);break}case"response.content_part.added":{let t=$(e,s.output_index),r=t.type,n=s.part;r==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&te(e)):r==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=$(e,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")re(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&te(e);else if(t.type==="reasoning"&&r.type==="reasoning_text"){let n=t.content;if(!n)throw new _(`missing content at index ${s.content_index}`);re(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(t.content,s.content_index);if(r.type!=="output_text")throw new _(`expected content to be 'output_text', got ${r.type}`);r.text+=s.delta,e.output_text+=s.delta}break}case"response.output_text.done":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(t.content,s.content_index);if(r.type!=="output_text")throw new _(`expected content to be 'output_text', got ${r.type}`);r.text=s.text,te(e)}break}case"response.output_text.annotation.added":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(t.content,s.content_index);if(r.type!=="output_text")throw new _(`expected content to be 'output_text', got ${r.type}`);r.annotations[s.annotation_index]=structuredClone(s.annotation)}break}case"response.refusal.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(t.content,s.content_index);if(r.type!=="refusal")throw new _(`expected content to be 'refusal', got ${r.type}`);r.refusal+=s.delta}break}case"response.refusal.done":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(t.content,s.content_index);if(r.type!=="refusal")throw new _(`expected content to be 'refusal', got ${r.type}`);r.refusal=s.refusal}break}case"response.function_call_arguments.delta":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new _(`missing content at index ${s.content_index}`);let r=re(t.content,s.content_index);if(r.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=s.delta}break}case"response.reasoning_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new _(`missing content at index ${s.content_index}`);let r=re(t.content,s.content_index);if(r.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${r.type}`);r.text=s.text}break}case"response.reasoning_summary_part.added":{let t=$(e,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=$(e,s.output_index);t.type==="reasoning"&&(re(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=re(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=re(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+s.delta);break}case"response.code_interpreter_call_code.done":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=ko(s.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:Ta(s)}return e}function ko(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&te(e),e}function $(s,e){let t=s.output[e];if(!t)throw new _(`missing output at index ${e}`);return t}function re(s,e){let t=s[e];if(!t)throw new _(`missing content at index ${e}`);return t}function Ta(s){throw new _(`Unhandled response stream event: ${JSON.stringify(s)}`)}var Vr,Rs,lt,Ss,Eo,vo,Oo,Cs=class s extends Se{constructor(e){super(),Vr.add(this),Rs.set(this,void 0),lt.set(this,void 0),Ss.set(this,void 0),x(this,Rs,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){this._listenForAbort(r?.signal),u(this,Vr,"m",Eo).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let c of n)u(this,Vr,"m",vo).call(this,c,o);if(n.controller.signal?.aborted)throw new L;return u(this,Vr,"m",Oo).call(this)}[(Rs=new WeakMap,lt=new WeakMap,Ss=new WeakMap,Vr=new WeakSet,Eo=function(){this.ended||x(this,lt,void 0,"f")},vo=function(t,r){if(this.ended)return;let n=(c,l)=>{(r==null||l.sequence_number>r)&&this._emit(c,l)},o=$o(t,u(this,lt,"f"));switch(x(this,lt,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let c=o.output[t.output_index];if(!c)throw new _(`missing output at index ${t.output_index}`);if(c.type==="message"){let l=c.content[t.content_index];if(!l)throw new _(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new _(`expected content to be 'output_text', got ${l.type}`);n("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let c=o.output[t.output_index];if(!c)throw new _(`missing output at index ${t.output_index}`);c.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:c.arguments});break}default:n(t.type,t);break}},Oo=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=u(this,lt,"f");if(!t)throw new _("request ended without sending any events");x(this,lt,void 0,"f");let r=Na(t,u(this,Rs,"f"));return x(this,Ss,r,"f"),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,c)=>t.push({resolve:o,reject:c})).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=u(this,Ss,"f");if(!e)throw new _("stream ended without producing a ChatCompletion");return e}};function Na(s,e){return So(s,e)}var br=class extends a{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,S,{query:t,...r,__security:{bearerAuth:!0}})}};var wr=class extends a{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var de=class extends a{constructor(){super(...arguments),this.inputItems=new br(this._client),this.inputTokens=new wr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&te(r),r))}retrieve(e,t={},r){return this._client.get(i`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&te(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>yn(r,e))}stream(e,t){return Cs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(i`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};de.InputItems=br;de.InputTokens=wr;var Ir=class extends a{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:d([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Pr=class extends a{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var pt=class extends a{constructor(){super(...arguments),this.content=new Pr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/skills/${e}/versions`,S,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};pt.Content=Pr;var be=class extends a{constructor(){super(...arguments),this.content=new Ir(this._client),this.versions=new pt(this._client)}create(e={},t){return this._client.post("/skills",Re({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};be.Content=Ir;be.Versions=pt;var xr=class extends a{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,G({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Me=class extends a{constructor(){super(...arguments),this.parts=new xr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(i`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};Me.Parts=xr;var To=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 Rr=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}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(i`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:c}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=c.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ce(l);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,c=Math.min(o,t.length),l=this._client,m=t.values(),p=[...r];async function I(f){for(let w of f){let g=await l.files.create({file:w,purpose:"assistants"},n);p.push(g.id)}}let h=Array(c).fill(m).map(I);return await To(h),await this.createAndPoll(e,{file_ids:p})}};var Sr=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,S,{query:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}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=d([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(),c=o.data;switch(c.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=o.response.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ce(l);break;case"failed":case"completed":return c}}}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(i`/vector_stores/${n}/files/${e}/content`,X,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var we=class extends a{constructor(){super(...arguments),this.files=new Sr(this._client),this.fileBatches=new Rr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/vector_stores/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(i`/vector_stores/${e}/search`,X,{body:t,method:"post",...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};we.Files=Sr;we.FileBatches=Rr;var ht=class extends a{create(e,t){return this._client.post("/videos",G({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",E,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",G({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",G({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",G({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(i`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(i`/videos/${e}/remix`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Cr,No,ks,dt=class extends a{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");u(this,Cr,"m",No).call(this,r);let o=d([t]).values,c=u(this,Cr,"m",ks).call(this,o,"webhook-signature"),l=u(this,Cr,"m",ks).call(this,o,"webhook-timestamp"),m=u(this,Cr,"m",ks).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new ae("Invalid webhook timestamp format");let I=Math.floor(Date.now()/1e3);if(I-p>n)throw new ae("Webhook timestamp is too old");if(p>I+n)throw new ae("Webhook timestamp is too new");let h=c.split(" ").map(y=>y.startsWith("v1,")?y.substring(3):y),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),w=m?`${m}.${l}.${e}`:`${l}.${e}`,g=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let y of h)try{let b=Buffer.from(y,"base64");if(await crypto.subtle.verify("HMAC",g,b,new TextEncoder().encode(w)))return}catch{continue}throw new ae("The given webhook signature does not match the expected signature")}};Cr=new WeakSet,No=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")},ks=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 Lo=Symbol.for("openai.node.providerDefinitions.v1"),Ko=globalThis,Mo=Ko[Lo],Fo=Mo??new WeakMap;Mo||Object.defineProperty(Ko,Lo,{value:Fo});function Uo(s){let e=Fo.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var An,bn,Yr,Bo,za="workload-identity-auth",R=class{constructor(e={}){An.add(this),Yr.set(this,void 0),this.completions=new Ze(this),this.chat=new ke(this),this.embeddings=new tt(this),this.files=new st(this),this.images=new at(this),this.audio=new pe(this),this.moderations=new ut(this),this.models=new ct(this),this.fineTuning=new ie(this),this.graders=new Ke(this),this.vectorStores=new we(this),this.webhooks=new dt(this),this.beta=new oe(this),this.batches=new Xe(this),this.uploads=new Me(this),this.admin=new Ee(this),this.responses=new de(this),this.realtime=new Ae(this),this.conversations=new je(this),this.evals=new Le(this),this.containers=new Ne(this),this.skills=new be(this),this.videos=new ht(this);let t=e.provider;if(t){let y=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(b=>e[b]!=null);if(y.length)throw new _(`The \`provider\` option cannot be used with ${y.map(b=>`\`${b}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=t?null:se("OPENAI_BASE_URL"),apiKey:n=t?null:se("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:se("OPENAI_ADMIN_KEY")??null,organization:c=t?null:se("OPENAI_ORG_ID")??null,project:l=t?null:se("OPENAI_PROJECT_ID")??null,webhookSecret:m=se("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,...I}=e,h=t?Uo(t):void 0,f={apiKey:n,adminAPIKey:o,organization:c,project:l,webhookSecret:m,workloadIdentity:p,provider:t,...I,baseURL:h?.baseURL??(r||"https://api.openai.com/v1")};if(n&&p)throw new _("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!h&&!n&&!o&&!p)throw new _("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&jn())throw new _(`It looks like you're running in a browser-like environment.
18
+
19
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
20
+ If you understand the risks and have appropriate mitigations in place,
21
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
22
+
23
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
24
+
25
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
26
+ `);this.baseURL=f.baseURL,this.timeout=f.timeout??bn.DEFAULT_TIMEOUT,this.logger=f.logger??console;let w="warn";this.logLevel=w,this.logLevel=Gs(f.logLevel,"ClientOptions.logLevel",this)??Gs(se("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??w,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??es(),x(this,Yr,Mn,"f");let g=t?void 0:se("OPENAI_CUSTOM_HEADERS");if(g){let y={};for(let b of g.split(`
27
+ `)){let P=b.indexOf(":");P>=0&&(y[b.substring(0,P).trim()]=b.substring(P+1).trim())}f.defaultHeaders=d([y,f.defaultHeaders])}this._options=f,this._provider=h,p&&(this._workloadIdentityAuth=new as(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=c,this.project=l,this.webhookSecret=m}withOptions(e){let t=this._options.provider,r=e.provider??t,n={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return d([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return d([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return d([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return d([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Jn(e)}getUserAgent(){return`${this.constructor.name}/JS ${xe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ls()}`}makeStatusError(e,t,r,n){return O.generate(e,t,r,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof _?r:new _(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new _(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!u(this,An,"m",Bo).call(this)&&r||this.baseURL,o=kn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),c=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!Ms(c)||!Ms(l))&&(t={...l,...c,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&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 Be(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:c,url:l,timeout:m}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(c,{url:l,options:n}),await this._provider?.prepareRequest?.(c,{url:l,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),I=r===void 0?"":`, retryOf: ${r}`,h=Date.now();if(N(this).debug(`[${p}] sending request`,me({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:c.headers})),n.signal?.aborted)throw new L;let f=n.__security??{bearerAuth:!0},w=new AbortController,g=await this.fetchWithAuth(l,c,m,w,f).catch(Er),y=Date.now();if(g instanceof globalThis.Error){let A=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new L;let k=$r(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(t)return N(this).info(`[${p}] connection ${k?"timed out":"failed"} - ${A}`),N(this).debug(`[${p}] connection ${k?"timed out":"failed"} (${A})`,me({retryOfRequestLogID:r,url:l,durationMs:y-h,message:g.message})),this.retryRequest(n,t,r??p);throw N(this).info(`[${p}] connection ${k?"timed out":"failed"} - error; no more retries left`),N(this).debug(`[${p}] connection ${k?"timed out":"failed"} (error; no more retries left)`,me({retryOfRequestLogID:r,url:l,durationMs:y-h,message:g.message})),g instanceof Fe||g instanceof vr?g:k?new Pe:new Ie({message:qa(g),cause:g})}let b=[...g.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,k])=>", "+A+": "+JSON.stringify(k)).join(""),P=`[${p}${I}${b}] ${c.method} ${l} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-h}ms`;if(!g.ok){if(g.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Bs(g.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??p);let A=await this.shouldRetry(g);if(t&&A){let T=`retrying, ${t} attempts remaining`;return await Bs(g.body),N(this).info(`${P} - ${T}`),N(this).debug(`[${p}] response error (${T})`,me({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),this.retryRequest(n,t,r??p,g.headers)}let k=A?"error; no more retries left":"error; not retryable";N(this).info(`${P} - ${k}`);let C=await g.text().catch(T=>Er(T).message),Y=vn(C),D=Y?void 0:C;throw N(this).debug(`[${p}] response error (${k})`,me({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,message:D,durationMs:Date.now()-h})),this.makeStatusError(g.status,Y,D,g.headers)}return N(this).info(P),N(this).debug(`[${p}] response start`,me({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),{response:g,options:n,controller:w,requestLogID:p,retryOfRequestLogID:r,startTime:h}}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 Lr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,m=l.get("Authorization");if(!m||m===`Bearer ${za}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:c,...l}=t||{},m=this._makeAbort(n);o&&o.addEventListener("abort",m,{once:!0});let p=setTimeout(m,r),I=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,h={signal:n.signal,...I?{duplex:"half"}:{},method:"GET",...l};c&&(h.method=c.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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,c=n?.get("retry-after-ms");if(c){let m=parseFloat(c);Number.isNaN(m)||(o=m)}let l=n?.get("retry-after");if(l&&!o){let m=parseFloat(l);Number.isNaN(m)?o=Date.parse(l)-Date.now():o=m*1e3}if(o===void 0){let m=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,m)}return await ce(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,c=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return c*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:c,defaultBaseURL:l}=r,m=this.buildURL(o,c,l);"timeout"in r&&En("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:I,isStreamingBody:h}=this.buildBody({options:r});h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&I instanceof globalThis.ReadableStream&&{duplex:"half"},...I&&{body:I},...this.fetchOptions??{},...r.fetchOptions??{}},url:m,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 c=d([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))}:{},...Ln(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(c,e.__security??{bearerAuth:!0}),c.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...u(this,Yr,"f").call(this,{body:t,headers:d([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=d([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,c=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!c}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ts(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...u(this,Yr,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};bn=R,Yr=new WeakMap,An=new WeakSet,Bo=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=bn;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=_;R.APIError=O;R.APIConnectionError=Ie;R.APIConnectionTimeoutError=Pe;R.APIUserAbortError=L;R.NotFoundError=gt;R.ConflictError=yt;R.RateLimitError=bt;R.BadRequestError=mt;R.AuthenticationError=ft;R.InternalServerError=wt;R.PermissionDeniedError=_t;R.UnprocessableEntityError=At;R.InvalidWebhookSignatureError=ae;R.toFile=us;R.Completions=Ze;R.Chat=ke;R.Embeddings=tt;R.Files=st;R.Images=at;R.Audio=pe;R.Moderations=ut;R.Models=ct;R.FineTuning=ie;R.Graders=Ke;R.VectorStores=we;R.Webhooks=dt;R.Beta=oe;R.Batches=Xe;R.Uploads=Me;R.Admin=Ee;R.Responses=de;R.Realtime=Ae;R.Conversations=je;R.Evals=Le;R.Containers=Ne;R.Skills=be;R.Videos=ht;function qa(s){if(Wa(s))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function Wa(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var $s=Pn({module:"llm"});var Do=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=js(e);if(!r)throw new Qr("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new R({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ns(e)}async*stream(e,t,r){let n=Ha(e.getMessages()),o=[];o.push({role:"system",content:this.systemPrompt});for(let f of n)o.push(f);let c=t.map(f=>{let w=f.input_schema;return{type:"function",name:f.name,description:f.description,parameters:w,strict:null}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...c.length>0?{tools:c}:{}},m=0,p=0,I=0,h=0;try{let f=await this.client.responses.create(l,{...r?{signal:r}:{}}),w="",g="",y="";for await(let b of f)if(b.type==="response.output_text.delta")yield{type:"text_delta",text:b.delta};else if(b.type==="response.function_call_arguments.delta")y+=b.delta,yield{type:"tool_call_delta",text:b.delta};else if(b.type==="response.output_item.added")b.item.type==="function_call"&&(w=b.item.name,g=b.item.call_id,y="",yield{type:"tool_call_start",toolName:w,toolId:g});else if(b.type==="response.output_item.done"){if(b.item.type==="function_call"&&w){let P={};if(y)try{let A=JSON.parse(y);P=vs(A)?Os(A):{[kr]:y}}catch(A){$s.error({err:A},"llm operation failed"),P={[kr]:y}}yield{type:"tool_call_complete",toolId:g,toolName:w,arguments:P},w="",g="",y=""}}else if(b.type==="response.completed"){let P=b.response.usage;P&&(p=P.output_tokens,I=P.input_tokens_details.cached_tokens,m=Math.max(0,P.input_tokens-I));let A="end_turn",k=b.response;k.status==="incomplete"&&k.incomplete_details?.reason==="max_output_tokens"&&(A="max_tokens"),yield{type:"stream_end",stopReason:A,usage:{inputTokens:m,outputTokens:p,cacheReadInputTokens:I,cacheCreationInputTokens:h}}}}catch(f){throw $s.error({err:f},"llm operation failed"),qo(f)}}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Ha(s){let e=[];for(let t of s)if(t.toolUses&&t.toolUses.length>0){t.content&&e.push({role:"assistant",content:t.content});for(let r of t.toolUses)e.push({type:"function_call",name:r.toolName,call_id:r.toolUseId,arguments:JSON.stringify(r.arguments)})}else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({type:"function_call_output",call_id:r.toolUseId,output:r.content});else e.push({role:t.role,content:t.content});return e}function Ja(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}function Ay(s){let e=[];for(let t of s)if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(r=>({id:r.toolUseId,type:"function",function:{name:r.toolName,arguments:JSON.stringify(r.arguments)}}))});else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({role:"tool",tool_call_id:r.toolUseId,content:r.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content}):e.push({role:t.role==="system"?"system":"user",content:t.content});return e}var zo=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=js(e);if(!r)throw new Qr("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new R({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ns(e)}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...Xa(e.getMessages())],o=t.map(h=>({type:"function",function:{name:h.name,description:h.description,arguments:h.input_schema}})),c={model:this.model,messages:n,stream:!0,max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,m=0,p=0,I=0;try{let h=await this.client.chat.completions.create(c,{...r?{signal:r}:{}}),f=new Map,w=null;for await(let y of h){if(y.choices.length===0)continue;let b=y.choices[0].delta;if(b.content&&(yield{type:"text_delta",text:b.content}),b.tool_calls)for(let P of b.tool_calls){f.has(P.index)||(f.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let A=f.get(P.index);A&&(P.id&&(A.id=P.id),P.function?.name&&(A.name=P.function.name),P.function?.arguments&&(A.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(y.choices[0].finish_reason){w=y.choices[0].finish_reason;for(let P of f.values()){let A={},k=P.args;if(k){try{let C=JSON.parse(k);A=vs(C)?Os(C):{[kr]:k}}catch(C){$s.error({err:C},"llm operation failed"),A={[kr]:k}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:A}}}}y.usage&&(m=y.usage.completion_tokens,p=y.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,y.usage.prompt_tokens-p))}let g;w==="length"?g="max_tokens":w==="tool_calls"||f.size>0?g="tool_use":g="end_turn",yield{type:"stream_end",stopReason:g,usage:{inputTokens:l,outputTokens:m,cacheReadInputTokens:p,cacheCreationInputTokens:I}}}catch(h){throw $s.error({err:h},"llm operation failed"),qo(h)}}};function qo(s){return s instanceof R.APIError?s.status===413||s.status===400&&Ja(s.message)?new Cn(`Context Too Long: ${s.message}`):s.status===401?new Qr(`Invalid API key: ${s.message}`):s.status===429?new Rn("Rate limit error, please wait."):new xn(`OpenAI API error (${Ts(s.status)}): ${s.message}`):new Sn(`Network error: ${s instanceof Error?s.message:Ts(s)}`)}function Xa(s){let e=[];for(let t of s)if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(r=>({id:r.toolUseId,type:"function",function:{name:r.toolName,arguments:JSON.stringify(r.arguments)}}))});else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({role:"tool",tool_call_id:r.toolUseId,content:r.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content}):e.push({role:t.role==="system"?"system":"user",content:t.content});return e}export{Do as OpenAIClient,zo as OpenAICompatClient,Ay as buildChatCompletionMessage,Xa as buildChatCompletionMessages,Ha as buildOpenAIInput};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import"./chunk-X3UA5OZL.js";async function d(i,c={}){let b={env:Object.setPrototypeOf({abort(e,t,n,r){e=f(e>>>0),t=f(t>>>0),n=n>>>0,r=r>>>0,(()=>{throw Error(`${e} in ${t}:${n}:${r}`)})()}},Object.assign(Object.create(globalThis),c.env||{}))},{exports:o}=await WebAssembly.instantiate(i,b),l=o.memory||c.env.memory,m=Object.setPrototypeOf({match(e,t){e=w(u(e)||y()),t=u(t)||y();try{return o.match(e,t)!=0}finally{h(e)}}},o);function f(e){if(!e)return null;let t=e+new Uint32Array(l.buffer)[e-4>>>2]>>>1,n=new Uint16Array(l.buffer),r=e>>>1,s="";for(;t-r>1024;)s+=String.fromCharCode(...n.subarray(r,r+=1024));return s+String.fromCharCode(...n.subarray(r,t))}function u(e){if(e==null)return 0;let t=e.length,n=o.__new(t<<1,2)>>>0,r=new Uint16Array(l.buffer);for(let s=0;s<t;++s)r[(n>>>1)+s]=e.charCodeAt(s);return n}let a=new Map;function w(e){if(e){let t=a.get(e);t?a.set(e,t+1):a.set(o.__pin(e),1)}return e}function h(e){if(e){let t=a.get(e);if(t===1)o.__unpin(e),a.delete(e);else if(t)a.set(e,t-1);else throw Error(`invalid refcount '${t}' for reference '${e}'`)}}function y(){throw TypeError("value must not be null")}return m}var{memory:_,match:g}=await(async i=>d(await(async()=>typeof process<"u"&&process.versions!=null&&(process.versions.node!=null||process.versions.bun!=null)?globalThis.WebAssembly.compile(await(await import("fs/promises")).readFile(i)):await globalThis.WebAssembly.compileStreaming(globalThis.fetch(i)))(),{}))(new URL("release.wasm",import.meta.url));export{g as match,_ as memory};
Binary file
package/docs/ch1.md ADDED
@@ -0,0 +1,25 @@
1
+ # 什么是 Agent
2
+
3
+ Agent 是 LLM 在循环中根据环境反馈自主使用工具的系统
4
+
5
+ - LLM 是大脑,负责理解和思考
6
+ - 循环: 意味着不是一次性问答就结束, 做一步操作, 拿到结果,再决定下一步
7
+ - 反馈: Agent 每做一步操作, 都能拿到到结果, 这些反馈驱动下一步决策
8
+ - 执行一条命令, 拿到输出
9
+ - 读一个文件, 拿到内容
10
+ - 跑一个测试, 拿到错误信息
11
+ - 自主使用工具: Agent 自主判断使用什么工具, 是读文件还是写文件, 是 grep 搜索代码还是执行 shell 命令
12
+
13
+ ## Swifty 的 5 层架构
14
+
15
+ 1. 交互层: cli、command、skill
16
+ 2. 引擎层: 对话、循环、提示词
17
+ 3. 工具层: 工具、mcp、hook
18
+ 4. 记忆层: 上下文、会话、自动记忆
19
+ 5. 安全层: 沙箱、权限、HITL (Human-in-the-Loop)
20
+
21
+ ## AI Coding
22
+
23
+ - spec.md 需求文档
24
+ - plan.md 技术方案
25
+ - task.md、checklist.md 任务清单