@maincode-ai/matilda-code 0.19.4 → 0.19.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/agent-NN3YCAQH.js +3 -0
- package/chunks/agent-headless-GCUE63J5.js +3 -0
- package/chunks/{anthropicContentGenerator-BRG6WZK3.js → anthropicContentGenerator-CZLOMDXF.js} +11 -11
- package/chunks/chunk-3KCDX6MY.js +8 -0
- package/chunks/chunk-7VGUNT5L.js +8 -0
- package/chunks/chunk-CLUEFPSU.js +8 -0
- package/chunks/{chunk-LDSV6752.js → chunk-ETVBCNID.js} +1 -1
- package/chunks/chunk-FSRNEJQB.js +8 -0
- package/chunks/chunk-KP6BLFQS.js +12 -0
- package/chunks/{chunk-TVWOSSXE.js → chunk-NRPYZBZX.js} +2 -2
- package/chunks/chunk-OGLMWPGR.js +56 -0
- package/chunks/{chunk-GV5WGCQ4.js → chunk-OREAJC5D.js} +472 -471
- package/chunks/chunk-RAHHGBHX.js +101 -0
- package/chunks/{chunk-NAH2MNUA.js → chunk-TZIIADJW.js} +3 -3
- package/chunks/chunk-XXZH7C44.js +34 -0
- package/chunks/{chunk-LN2DRVOB.js → chunk-XYA3SFGC.js} +1 -1
- package/chunks/{computer-use-GUYVQIGN.js → computer-use-AM62LD63.js} +1 -1
- package/chunks/contextCommand-CWNMYXES.js +3 -0
- package/chunks/{edit-ZULTS2VM.js → edit-PJD2ABCG.js} +1 -1
- package/chunks/{en-77LGBBG5.js → en-ZU6RPTEW.js} +1 -1
- package/chunks/{enter-worktree-CCLNWZ5Q.js → enter-worktree-MTT3VNXA.js} +1 -1
- package/chunks/{enterPlanMode-GXBX6ZNF.js → enterPlanMode-KJSXKSQX.js} +1 -1
- package/chunks/{exit-worktree-6Q45J7P4.js → exit-worktree-CX2HMIRN.js} +1 -1
- package/chunks/{exitPlanMode-SKDXBN5H.js → exitPlanMode-QQ7DSRYT.js} +1 -1
- package/chunks/geminiContentGenerator-HZHMNMGX.js +8 -0
- package/chunks/glob-L6LCKWIV.js +22 -0
- package/chunks/{grep-SEHIGGHQ.js → grep-PIJYRFHS.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-O54RMUHJ.js → matildaAgentContentGenerator-Y2ECTUZO.js} +9 -9
- package/chunks/matildaContentGenerator-HATVJLJF.js +8 -0
- package/chunks/monitor-A3RDX2JT.js +32 -0
- package/chunks/notebook-edit-5KEG5MTP.js +17 -0
- package/chunks/openaiContentGenerator-XI6SCJ2G.js +3 -0
- package/chunks/ripGrep-PXECRMR2.js +3 -0
- package/chunks/scheduler-XG6XEE2W.js +8 -0
- package/chunks/{serve-JLX6G5W2.js → serve-RZQK4PGY.js} +1 -1
- package/chunks/shell-CGATWESB.js +3 -0
- package/chunks/src-D4A3YMBH.js +3 -0
- package/chunks/{team-create-WNT5JVQS.js → team-create-WADAQUBF.js} +1 -1
- package/chunks/{update-goal-6YHKDFDL.js → update-goal-DH2TEYYU.js} +1 -1
- package/chunks/{web-fetch-KIAE27JH.js → web-fetch-5F7C7MXU.js} +1 -1
- package/chunks/{web-search-T6JQYRFL.js → web-search-XR5V4QRH.js} +1 -1
- package/chunks/{workflow-S2XCUMV3.js → workflow-NTYIHQG2.js} +2 -2
- package/chunks/write-file-THZKUU47.js +11 -0
- package/chunks/{zh-LDF5IJ3D.js → zh-I4FV25MS.js} +1 -1
- package/chunks/{zh-TW-NAHJGTBA.js → zh-TW-7HNBEDIB.js} +1 -1
- package/cli.js +461 -461
- package/locales/en.js +2 -2
- package/locales/zh-TW.js +2 -2
- package/locales/zh.js +2 -2
- package/package.json +2 -2
- package/chunks/agent-THT56PAJ.js +0 -3
- package/chunks/agent-headless-MJXXZAJ5.js +0 -3
- package/chunks/chunk-33FV6XMQ.js +0 -38
- package/chunks/chunk-OQ73WWR4.js +0 -8
- package/chunks/chunk-QE7JDD3Q.js +0 -101
- package/chunks/chunk-R6YTDM76.js +0 -8
- package/chunks/chunk-T3ERIC7X.js +0 -12
- package/chunks/chunk-YNR4LJMU.js +0 -34
- package/chunks/contextCommand-4CKQVKP7.js +0 -3
- package/chunks/geminiContentGenerator-AHPUJXRJ.js +0 -8
- package/chunks/glob-YQYYXRD6.js +0 -22
- package/chunks/matildaContentGenerator-UXLQXYIJ.js +0 -8
- package/chunks/monitor-H5RCPLSV.js +0 -32
- package/chunks/notebook-edit-ZBKC73OA.js +0 -17
- package/chunks/openaiContentGenerator-4D5JS26Z.js +0 -3
- package/chunks/ripGrep-SIK37YV5.js +0 -3
- package/chunks/scheduler-OM5HPBCW.js +0 -8
- package/chunks/shell-YYHEBIMO.js +0 -3
- package/chunks/src-5RWLWMNE.js +0 -3
- package/chunks/write-file-GM4PPNIQ.js +0 -11
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{b as n}from"./chunk-GZPNIYVZ.js";n();var m="MATILDA_API_KEY";var g="matilda-code-1.0",_="Matilda",u="https://matilda.maincode.com/api/v1/code";var f={id:"matilda",label:"Matilda",description:"Connect to the Matilda Core code API endpoint",protocol:"openai",baseUrl:u,envKey:m,models:[{id:g,displayName:_,contextWindowSize:1048576,description:"Matilda Code model",generationConfig:{openAIRequestProfile:"matilda-code",samplingParams:{max_tokens:65536,chat_template_kwargs:{enable_thinking:!0}},schemaCompliance:"openapi_30",splitToolMedia:!0,customHeaders:{"User-Agent":"MatildaCode/0.1"}}}],modelNamePrefix:"",documentationUrl:"https://matilda.maincode.help/welcome/external-api",uiGroup:"third-party"};function h(a){return a.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}async function E(a){let{baseUrl:r,email:s,password:d,signal:l}=a,i=h(r),p=`${i}/api/auth/login`,t;try{t=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:s,password:d}),signal:l})}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`Could not reach Matilda at ${i}: ${c}`)}if(t.status===401)throw new Error("Invalid email or password.");if(!t.ok)throw new Error(`Matilda sign-in failed (HTTP ${t.status}). Please try again.`);let e;try{e=await t.json()}catch{throw new Error("Matilda sign-in returned an unreadable response.")}if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("Matilda sign-in did not return a token.");return{token:e.token,refreshToken:typeof e.refreshToken=="string"?e.refreshToken:void 0,userId:typeof e.userId=="string"?e.userId:void 0,email:typeof e.email=="string"?e.email:void 0,displayName:typeof e.displayName=="string"?e.displayName:void 0}}export{m as a,u as b,f as c,h as d,E as e};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2026 Matilda Team
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{a as c}from"./chunk-4F4DA5UI.js";import{j as i}from"./chunk-CLUEFPSU.js";import{e as l}from"./chunk-5U3A6KMU.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function C(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
|
|
4
|
+
|
|
5
|
+
`):void 0}catch{return}}function h(t,e){return e?t===void 0?e:typeof t=="string"?`${t}
|
|
6
|
+
|
|
7
|
+
${e}`:Array.isArray(t)?[...t,{text:e}]:typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)?{...t,parts:[...t.parts,{text:e}]}:[t,{text:e}]:t}function R(t){return t.schema!==void 0&&t.schema!==null}async function b(t,e){let n=T(t,e.model),o=e.promptId??S(e.purpose),s=x(e.config),a=h(e.systemInstruction,await C(t)),u=e.purpose==="chat-compression"?"compaction":"unknown";if(R(e)){let r=await i(u,()=>t.getBaseLlmClient().generateJson({contents:e.contents,schema:e.schema,abortSignal:e.abortSignal,model:n,systemInstruction:a,promptId:o,config:s,...e.maxAttempts!==void 0&&{maxAttempts:e.maxAttempts}})),f=l.validate(e.schema,r);if(f)throw new Error(`Invalid side query response: ${f}`);let g=e.validate?.(r);if(g)throw new Error(g);return r}let p=await i(u,()=>t.getBaseLlmClient().generateText({contents:e.contents,model:n,systemInstruction:a,abortSignal:e.abortSignal,promptId:o,config:s,...e.maxAttempts!==void 0&&{maxAttempts:e.maxAttempts}})),d=e.validate?.(p.text);if(d)throw new Error(d);return p}export{b as a};
|
|
8
|
+
/**
|
|
9
|
+
* @license
|
|
10
|
+
* Copyright 2025 Google LLC
|
|
11
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
12
|
+
*/
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{bh as T}from"./chunk-OREAJC5D.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var W=e=>{process.stdout.write(e.endsWith(`
|
|
4
4
|
`)?e:`${e}
|
|
5
5
|
`)},m=e=>{process.stderr.write(e.endsWith(`
|
|
6
6
|
`)?e:`${e}
|
|
7
|
-
`)},G=()=>{console.clear()};o();import*as c from"node:fs";import*as f from"node:path";import{pathToFileURL as E}from"node:url";o();var l=[{code:"en",id:"en-US",fullName:"English",nativeName:"English"},{code:"zh-TW",id:"zh-TW",fullName:"Traditional Chinese",nativeName:"\u7E41\u9AD4\u4E2D\u6587",strictParity:!0},{code:"zh",id:"zh-CN",fullName:"Chinese",nativeName:"\u4E2D\u6587",strictParity:!0},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function R(e){return e.trim().replace(/_/g,"-").toLowerCase()}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function U(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function u(e){let t=R(e);if(!t)return;let n;for(let r of l){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=U(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function M(e){let t=u(e);return(t?l.find(r=>r.code===t):void 0)?.fullName||"English"}function J(){return[{value:"auto",label:"Auto (detect from system)"},...l.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}function V(e="|"){return l.map(t=>t.id).join(e)}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var C=w({"./locales/ca.js":()=>import("./ca-UW3G7H5I.js"),"./locales/de.js":()=>import("./de-QSFN3SRK.js"),"./locales/en.js":()=>import("./en-
|
|
7
|
+
`)},G=()=>{console.clear()};o();import*as c from"node:fs";import*as f from"node:path";import{pathToFileURL as E}from"node:url";o();var l=[{code:"en",id:"en-US",fullName:"English",nativeName:"English"},{code:"zh-TW",id:"zh-TW",fullName:"Traditional Chinese",nativeName:"\u7E41\u9AD4\u4E2D\u6587",strictParity:!0},{code:"zh",id:"zh-CN",fullName:"Chinese",nativeName:"\u4E2D\u6587",strictParity:!0},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function R(e){return e.trim().replace(/_/g,"-").toLowerCase()}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function U(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function u(e){let t=R(e);if(!t)return;let n;for(let r of l){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=U(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function M(e){let t=u(e);return(t?l.find(r=>r.code===t):void 0)?.fullName||"English"}function J(){return[{value:"auto",label:"Auto (detect from system)"},...l.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}function V(e="|"){return l.map(t=>t.id).join(e)}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var C=w({"./locales/ca.js":()=>import("./ca-UW3G7H5I.js"),"./locales/de.js":()=>import("./de-QSFN3SRK.js"),"./locales/en.js":()=>import("./en-ZU6RPTEW.js"),"./locales/fr.js":()=>import("./fr-FKTJ4COX.js"),"./locales/ja.js":()=>import("./ja-GKS4GLZP.js"),"./locales/pt.js":()=>import("./pt-VIW62ZAE.js"),"./locales/ru.js":()=>import("./ru-FSSACF4A.js"),"./locales/zh-TW.js":()=>import("./zh-TW-7HNBEDIB.js"),"./locales/zh.js":()=>import("./zh-I4FV25MS.js")});var y="en",v={},s={},S={},P=()=>f.join(T(import.meta.url),"locales"),D=()=>f.join(b.getGlobalMatildaDir(),"locales");var N=(e,t=!1)=>{let n=t?D():P();return f.join(n,`${e}.js`)};function I(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=u(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=u(t);if(n)return n}catch{}return"en"}async function A(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function O(e){try{let t=await C(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){if(s[e])return s[e];let t=S[e];if(t)return t;let n=(async()=>{let r=N(e,!0);if(c.existsSync(D())&&c.existsSync(r)){let i=await A(E(r).href);if(i.translations)return s[e]=i.translations,i.translations;m(`Failed to load translations from user directory for ${e}: ${i.error.message}`)}let a=N(e,!1),x=[];c.existsSync(P())&&c.existsSync(a)&&x.push(E(a).href);let d;for(let i of x){let p=await A(i);if(p.translations)return s[e]=p.translations,p.translations;d=p.error}let g=await O(e);return g.translations?(s[e]=g.translations,g.translations):(d=g.error,d&&m(`Failed to load JS translations for ${e}: ${d.message}`),s[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function j(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function z(e){return e==="auto"?I():u(e)??e}async function F(e){y=z(e),v=await $(y)}function se(){return y}function le(e,t){let n=v[e]??e;return Array.isArray(n)?e:j(n,t)}function ue(e){let t=v[e];return Array.isArray(t)?t:[]}async function ce(e){await F(e??"auto")}export{W as a,m as b,G as c,l as d,u as e,M as f,J as g,V as h,I as i,F as j,se as k,le as l,ue as m,ce as n};
|
|
8
8
|
/**
|
|
9
9
|
* @license
|
|
10
10
|
* Copyright 2025 Matilda Team
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{a as rs}from"./chunk-QCIDUZV6.js";import{a as es,b as ts,c as qt}from"./chunk-3KCDX6MY.js";import{a as ns}from"./chunk-FSRNEJQB.js";import{c as yr,f as ve}from"./chunk-S4K76QPI.js";import{a as qn,b as ot,c as Xn,x as Qn}from"./chunk-RAHHGBHX.js";import{a as Zr,e as Jn,j as Vn,o as Kn,q as zn,s as Yn,t as hr}from"./chunk-XYA3SFGC.js";import{e as Hn}from"./chunk-4J6DC24J.js";import{a as gr,b as _r,e as Zn,m as br}from"./chunk-CLUEFPSU.js";import{b as en}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Wn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var tn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return tn=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Xt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Jt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var y=class extends Error{},$=class n extends y{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.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 s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new he({message:r,cause:Jt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},he=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends he{constructor({message:e}={}){super({message:e??"Request timed out."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},mt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ht=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var fo=/^[a-z][a-z0-9+.-]*:/i,ss=n=>fo.test(n),W=n=>(W=Array.isArray,W(n)),rn=W;function os(n){return typeof n!="object"?{}:n??{}}function is(n){if(!n)return!0;for(let e in n)return!1;return!0}function as(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ls=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var cs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var ds=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function po(){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 mo=()=>{let n=po();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(Deno.build.os),"X-Stainless-Arch":us(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":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":us(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ho();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"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":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ho(){if(typeof navigator>"u"||!navigator)return null;let n=[{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 n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var us=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",fs=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),ps,ms=()=>ps??(ps=mo());a();function hs(){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 nn(...n){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(...n)}function Cr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nn({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sn(n){if(n[Symbol.asyncIterator])return n;let e=n.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 gs(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var _s=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var wr="RFC3986",on=n=>String(n),Ar={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:on},an="RFC1738";a();a();var xr=(n,e)=>(xr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xr(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var ln=1024,bs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),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 i="";for(let l=0;l<o.length;l+=ln){let u=o.length>=ln?o.slice(l,l+ln):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===an&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function ys(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function cn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ws={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},As=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Cs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bs,encodeValuesOnly:!1,format:wr,formatter:on,indices:!1,serializeDate(n){return(Cs??(Cs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function bo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var un={};function xs(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,X=!1;for(;(U=U.get(un))!==void 0&&!X;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");X=!0}typeof U.get(un)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=cn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(bo(w)||ys(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=cn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return j+"[]";for(let T=0;T<E.length;++T){let M=E[T],Gn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Gn===null)continue;let Qr=p&&l?M.replace(/\./g,"%2E"):M,co=W(w)?typeof t=="function"?t(j,Qr):j:j+(p?"."+Qr:"["+Qr+"]");O.set(n,S);let Bn=new WeakMap;Bn.set(un,O),As(H,xs(Gn,co,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Bn))}return H}function yo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=wr;if(typeof n.format<"u"){if(!xr(Ar,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=Ar[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ws?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function fn(n,e={}){let t=n,r=yo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=ws[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||As(i,xs(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function Rs(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var Is;function gt(n){let e;return(Is??(e=new globalThis.TextEncoder,Is=e.encode.bind(e)))(n)}var Ps;function pn(n){let e;return(Ps??(e=new globalThis.TextDecoder,Ps=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),A(this,J,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,J,Rs([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=wo(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(pn(c(this,J,"f").subarray(0,c(this,V,"f")-1))),A(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=pn(c(this,J,"f").subarray(0,o));r.push(i),A(this,J,c(this,J,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
|
|
4
|
+
`):[]}};J=new WeakMap,V=new WeakMap;Te.NEWLINE_CHARS=new Set([`
|
|
5
|
+
`,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function wo(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Os(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}a();var Pr={off:0,error:200,warn:300,info:400,debug:500},dn=(n,e,t)=>{if(n){if(as(Pr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Pr))}`)}};function Kt(){}function Ir(n,e,t){return!e||Pr[n]>Pr[t]?Kt:e[n].bind(e)}var Ao={error:Kt,warn:Kt,info:Kt,debug:Kt},Ss=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return Ao;let r=Ss.get(e);if(r&&r[0]===t)return r[1];let s={error:Ir("error",e,t),warn:Ir("warn",e,t),info:Ir("info",e,t),debug:Ir("debug",e,t)};return Ss.set(e,[t,s]),s}var le=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var zt,re=class n{constructor(e,t,r){this.iterator=e,zt.set(this,void 0),this.controller=t,A(this,zt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of xo(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let d;try{d=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(d&&d.error)throw new $(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new $(void 0,d.error,d.message,void 0);yield{event:u.event,data:d}}}l=!0}catch(u){if(Xt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*o(){let l=new Te,u=sn(e);for await(let d of u)for(let g of l.decode(d))yield g;for(let d of l.flush())yield d}async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Xt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(zt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new n(()=>s(e),this.controller,c(this,zt,"f")),new n(()=>s(t),this.controller,c(this,zt,"f"))]}toReadableStream(){let e=this,t;return nn({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:o}=await t.next();if(o)return r.close();let i=gt(JSON.stringify(s)+`
|
|
6
|
+
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*xo(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new mn,r=new Te,s=sn(n.body);for await(let o of Io(s))for(let i of r.decode(o)){let l=t.decode(i);l&&(yield l)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*Io(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?gt(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=Os(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var mn=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(`
|
|
7
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Po(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Po(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function Rr(n,e){let{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return v(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):re.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return hn(p,t)}return await t.text()})();return v(n).debug(`[${r}] response parsed`,le({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function hn(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}a();var Yt,ke=class n extends Promise{constructor(e,t,r=Rr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Yt.set(this,void 0),A(this,Yt,e,"f")}_thenUnwrap(e){return new n(c(this,Yt,"f"),this.responsePromise,async(t,r)=>hn(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(c(this,Yt,"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)}};Yt=new WeakMap;var Or,Sr=class{constructor(e,t,r,s){Or.set(this,void 0),A(this,Or,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Or,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Or=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Qt=class extends ke{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await Rr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends Sr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Sr{constructor(e,t,r,s){super(e,t,r,s),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:{...os(this.options.query),after:t}}:null}};a();a();a();var _n=()=>{if(typeof File>"u"){let{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.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 _t(n,e,t){return _n(),new File(n,e??"unknown_file",t)}function Zt(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}var bn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function";var K=async(n,e)=>({...n,body:await So(n.body,e)}),Es=new WeakMap;function Oo(n){let e=typeof n=="function"?n:n.fetch,t=Es.get(e);if(t)return t;let r=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Es.set(e,r),r}var So=async(n,e)=>{if(!await Oo(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(n||{}).map(([r,s])=>gn(t,r,s))),t},Eo=n=>n instanceof Blob&&"name"in n;var gn=async(n,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")n.append(e,String(t));else if(t instanceof Response)n.append(e,_t([await t.blob()],Zt(t)));else if(bn(t))n.append(e,_t([await new Response(Cr(t)).blob()],Zt(t)));else if(Eo(t))n.append(e,t,Zt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>gn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>gn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var vs=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",vo=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&vs(n),To=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Er(n,e,t){if(_n(),n=await n,vo(n))return n instanceof File?n:_t([await n.arrayBuffer()],n.name);if(To(n)){let s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),_t(await yn(s),e,t)}let r=await yn(n);if(e||(e=Zt(n)),!t?.type){let s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return _t(r,e,t)}async function yn(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(vs(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(bn(n))for await(let t of n)e.push(...await yn(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${ko(n)}`)}return e}function ko(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}a();a();a();a();var h=class{constructor(e){this._client=e}};a();a();a();function ks(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ts=Object.freeze(Object.create(null)),$o=(n=ks)=>function(t,...r){if(t.length===1)return t[0];let s=!1,o=[],i=t.reduce((g,p,b)=>{/[?#]/.test(p)&&(s=!0);let f=r[b],x=(s?encodeURIComponent:n)(""+f);return b!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Ts)??Ts)?.toString)&&(x=f+"",o.push({start:g.length+p.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+p+(b===r.length?"":x)},""),l=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(l))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((g,p)=>g.start-p.start),o.length>0){let g=0,p=o.reduce((b,f)=>{let x=" ".repeat(f.start-g),C="^".repeat(f.length);return g=f.start+f.length,b+x+C},"");throw new y(`Path parameters result in path with invalid segments:
|
|
8
|
+
${o.map(b=>b.error).join(`
|
|
9
|
+
`)}
|
|
10
|
+
${i}
|
|
11
|
+
${p}`)}return i},m=$o(ks);var Me=class extends h{list(e,t={},r){return this._client.getAPIList(m`/chat/completions/${e}/messages`,R,{query:t,...r})}};a();a();a();a();function Ms(n){return typeof n.parse=="function"}a();var bt=n=>n?.role==="assistant",Cn=n=>n?.role==="tool";a();var wn,vr,Tr,er,tr,kr,rr,ce,nr,Mr,$r,yt,$s,be=class{constructor(){wn.add(this),this.controller=new AbortController,vr.set(this,void 0),Tr.set(this,()=>{}),er.set(this,()=>{}),tr.set(this,void 0),kr.set(this,()=>{}),rr.set(this,()=>{}),ce.set(this,{}),nr.set(this,!1),Mr.set(this,!1),$r.set(this,!1),yt.set(this,!1),A(this,vr,new Promise((e,t)=>{A(this,Tr,e,"f"),A(this,er,t,"f")}),"f"),A(this,tr,new Promise((e,t)=>{A(this,kr,e,"f"),A(this,rr,t,"f")}),"f"),c(this,vr,"f").catch(()=>{}),c(this,tr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,wn,"m",$s).bind(this))},0)}_connected(){this.ended||(c(this,Tr,"f").call(this),this._emit("connect"))}get ended(){return c(this,nr,"f")}get errored(){return c(this,Mr,"f")}get aborted(){return c(this,$r,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,ce,"f")[e];if(!r)return this;let s=r.findIndex(o=>o.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(c(this,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{A(this,yt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){A(this,yt,!0,"f"),await c(this,tr,"f")}_emit(e,...t){if(c(this,nr,"f"))return;e==="end"&&(A(this,nr,!0,"f"),c(this,kr,"f").call(this));let r=c(this,ce,"f")[e];if(r&&(c(this,ce,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,yt,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,yt,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end")}}_emitFinal(){}};vr=new WeakMap,Tr=new WeakMap,er=new WeakMap,tr=new WeakMap,kr=new WeakMap,rr=new WeakMap,ce=new WeakMap,nr=new WeakMap,Mr=new WeakMap,$r=new WeakMap,yt=new WeakMap,wn=new WeakSet,$s=function(e){if(A(this,Mr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new k),e instanceof k)return A(this,$r,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};a();function sr(n){return n?.$brand==="auto-parseable-response-format"}function $e(n){return n?.$brand==="auto-parseable-tool"}function Ns(n,e){return!e||!An(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:or(n,e)}function or(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new mt;if(r.finish_reason==="content_filter")throw new ht;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>Uo(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Fo(e,r.message.content):null}}});return{...n,choices:t}}function Fo(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function Uo(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$e(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Ls(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return $e(t)||t?.function.strict||!1}function An(n){return sr(n.response_format)?!0:n.tools?.some(e=>$e(e)||e.type==="function"&&e.function.strict===!0)??!1}function Fs(n){for(let e of n??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,xn,Nr,In,Pn,Rn,Us,Ds,Do=10,Ct=class extends be{constructor(){super(...arguments),q.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),Cn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(bt(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",xn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",Nr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",In).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",Pn).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",Rn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,q,"m",Nr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",xn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",In).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",Pn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",Rn).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,q,"m",Us).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(or(o,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let s="tool",{tool_choice:o="auto",stream:i,...l}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:d=Do}=r||{},g=t.tools.map(f=>{if($e(f)){if(!f.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of g)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let b="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){let C=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:b,messages:[...this.messages]},r)).choices[0]?.message;if(!C)throw new y("missing message in ChatCompletion response");if(!C.tool_calls?.length)return;for(let P of C.tool_calls){if(P.type!=="function")continue;let O=P.id,{name:w,arguments:U}=P.function,S=p[w];if(S){if(u&&u!==w){let D=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(p).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}let X;try{X=Ms(S)?await S.parse(U):U}catch(D){let j=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:O,content:j});continue}let H=await S.function(X,this),E=c(this,q,"m",Ds).call(this,H);if(this._addMessage({role:s,tool_call_id:O,content:E}),u)return}}}};q=new WeakSet,xn=function(){return c(this,q,"m",Nr).call(this).content??null},Nr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(bt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},In=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(bt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Pn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Cn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Rn=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},Us=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ds=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ir=class n extends Ct{static runTools(e,t,r){let s=new n,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),bt(e)&&e.content&&this._emit("content",e.content)}};a();a();a();a();var G={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},On=class extends Error{},Sn=class extends Error{};function jo(n,e=G.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Go(n.trim(),e)}var Go=(n,e)=>{let t=n.length,r=0,s=b=>{throw new On(`${b} at position ${r}`)},o=b=>{throw new Sn(`${b} at position ${r}`)},i=()=>(p(),r>=t&&s("Unexpected end of input"),n[r]==='"'?l():n[r]==="{"?u():n[r]==="["?d():n.substring(r,r+4)==="null"||G.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||G.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||G.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||G.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||G.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||G.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):g()),l=()=>{let b=r,f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(b,++r-Number(f)))}catch(x){o(String(x))}else if(G.STR&e)try{return JSON.parse(n.substring(b,r-Number(f))+'"')}catch{return JSON.parse(n.substring(b,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,p();let b={};try{for(;n[r]!=="}";){if(p(),r>=t&&G.OBJ&e)return b;let f=l();p(),r++;try{let x=i();Object.defineProperty(b,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(G.OBJ&e)return b;throw x}p(),n[r]===","&&r++}}catch{if(G.OBJ&e)return b;s("Expected '}' at end of object")}return r++,b},d=()=>{r++;let b=[];try{for(;n[r]!=="]";)b.push(i()),p(),n[r]===","&&r++}catch{if(G.ARR&e)return b;s("Expected ']' at end of array")}return r++,b},g=()=>{if(r===0){n==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(G.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}o(String(f))}}let b=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(G.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(b,r))}catch{n.substring(b,r)==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(b,n.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<t&&`
|
|
12
|
+
\r `.includes(n[r]);)r++};return i()},En=n=>jo(n,G.ALL^G.NUM);var L,ue,wt,ye,vn,Lr,Tn,kn,Mn,Fr,$n,js,Ne=class n extends Ct{constructor(e){super(),L.add(this),ue.set(this,void 0),wt.set(this,void 0),ye.set(this,void 0),A(this,ue,e,"f"),A(this,wt,[],"f")}get currentChatCompletionSnapshot(){return c(this,ye,"f")}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new n(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,L,"m",vn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)c(this,L,"m",Tn).call(this,i);if(o.controller.signal?.aborted)throw new k;return this._addChatCompletion(c(this,L,"m",Fr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,L,"m",vn).call(this),this._connected();let s=re.fromReadableStream(e,this.controller),o;for await(let i of s)o&&o!==i.id&&this._addChatCompletion(c(this,L,"m",Fr).call(this)),c(this,L,"m",Tn).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new k;return this._addChatCompletion(c(this,L,"m",Fr).call(this))}[(ue=new WeakMap,wt=new WeakMap,ye=new WeakMap,L=new WeakSet,vn=function(){this.ended||A(this,ye,void 0,"f")},Lr=function(t){let r=c(this,wt,"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},c(this,wt,"f")[t.index]=r,r)},Tn=function(t){if(this.ended)return;let r=c(this,L,"m",js).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let o=r.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=c(this,L,"m",Lr).call(this,o);o.finish_reason&&(c(this,L,"m",Mn).call(this,o),i.current_tool_call_index!=null&&c(this,L,"m",kn).call(this,o,i.current_tool_call_index));for(let l of s.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(c(this,L,"m",Mn).call(this,o),i.current_tool_call_index!=null&&c(this,L,"m",kn).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[l.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:l.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(u?.type,void 0))}}},kn=function(t,r){if(c(this,L,"m",Lr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=c(this,ue,"f")?.tools?.find(l=>l.type==="function"&&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:$e(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Mn=function(t){let r=c(this,L,"m",Lr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=c(this,L,"m",$n).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$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}))},Fr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,ye,"f");if(!t)throw new y("request ended without sending any chunks");return A(this,ye,void 0,"f"),A(this,wt,[],"f"),Bo(t,c(this,ue,"f"))},$n=function(){let t=c(this,ue,"f")?.response_format;return sr(t)?t:null},js=function(t){var r,s,o,i;let l=c(this,ye,"f"),{choices:u,...d}=t;l?Object.assign(l,d):l=A(this,ye,{...d,choices:[]},"f");for(let{delta:g,finish_reason:p,index:b,logprobs:f=null,...x}of t.choices){let C=l.choices[b];if(C||(C=l.choices[b]={finish_reason:p,index:b,message:{},logprobs:f,...x}),f)if(!C.logprobs)C.logprobs=Object.assign({},f);else{let{content:H,refusal:E,...D}=f;Object.assign(C.logprobs,D),H&&((r=C.logprobs).content??(r.content=[]),C.logprobs.content.push(...H)),E&&((s=C.logprobs).refusal??(s.refusal=[]),C.logprobs.refusal.push(...E))}if(p&&(C.finish_reason=p,c(this,ue,"f")&&An(c(this,ue,"f")))){if(p==="length")throw new mt;if(p==="content_filter")throw new ht}if(Object.assign(C,x),!g)continue;let{content:P,refusal:O,function_call:w,role:U,tool_calls:S,...X}=g;if(Object.assign(C.message,X),O&&(C.message.refusal=(C.message.refusal||"")+O),U&&(C.message.role=U),w&&(C.message.function_call?(w.name&&(C.message.function_call.name=w.name),w.arguments&&((o=C.message.function_call).arguments??(o.arguments=""),C.message.function_call.arguments+=w.arguments)):C.message.function_call=w),P&&(C.message.content=(C.message.content||"")+P,!C.message.refusal&&c(this,L,"m",$n).call(this)&&(C.message.parsed=En(C.message.content))),S){C.message.tool_calls||(C.message.tool_calls=[]);for(let{index:H,id:E,type:D,function:j,...T}of S){let M=(i=C.message.tool_calls)[H]??(i[H]={});Object.assign(M,T),E&&(M.id=E),D&&(M.type=D),j&&(M.function??(M.function={name:j.name??"",arguments:""})),j?.name&&(M.function.name=j.name),j?.arguments&&(M.function.arguments+=j.arguments,Ls(c(this,ue,"f"),M)&&(M.function.parsed_arguments=En(M.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Bo(n,e){let{id:t,choices:r,created:s,model:o,system_fingerprint:i,...l}=n,u={...l,id:t,choices:r.map(({message:d,finish_reason:g,index:p,logprobs:b,...f})=>{if(!g)throw new y(`missing finish_reason for choice ${p}`);let{content:x=null,function_call:C,tool_calls:P,...O}=d,w=d.role;if(!w)throw new y(`missing role for choice ${p}`);if(C){let{arguments:U,name:S}=C;if(U==null)throw new y(`missing function_call.arguments for choice ${p}`);if(!S)throw new y(`missing function_call.name for choice ${p}`);return{...f,message:{content:x,function_call:{arguments:U,name:S},role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}return P?{...f,index:p,finish_reason:g,logprobs:b,message:{...O,role:w,content:x,refusal:d.refusal??null,tool_calls:P.map((U,S)=>{let{function:X,type:H,id:E,...D}=U,{arguments:j,name:T,...M}=X||{};if(E==null)throw new y(`missing choices[${p}].tool_calls[${S}].id
|
|
13
|
+
${Ur(n)}`);if(H==null)throw new y(`missing choices[${p}].tool_calls[${S}].type
|
|
14
|
+
${Ur(n)}`);if(T==null)throw new y(`missing choices[${p}].tool_calls[${S}].function.name
|
|
15
|
+
${Ur(n)}`);if(j==null)throw new y(`missing choices[${p}].tool_calls[${S}].function.arguments
|
|
16
|
+
${Ur(n)}`);return{...D,id:E,type:H,function:{...M,name:T,arguments:j}}})}}:{...f,message:{...O,content:x,role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Ns(u,e)}function Ur(n){return JSON.stringify(n)}var ar=class n extends Ne{static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new n(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var fe=class extends h{constructor(){super(...arguments),this.messages=new Me(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(m`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(m`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/chat/completions/${e}`,t)}parse(e,t){return Fs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>or(r,e))}runTools(e,t){return e.stream?ar.runTools(this._client,e,t):ir.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};fe.Messages=Me;var Ce=class extends h{constructor(){super(...arguments),this.completions=new fe(this._client)}};Ce.Completions=fe;a();a();a();a();a();var Gs=Symbol("brand.privateNullableHeaders");function*Ho(n){if(!n)return;if(Gs in n){let{values:r,nulls:s}=n;yield*r.entries();for(let o of s)yield[o,null];return}let e=!1,t;n instanceof Headers?t=n.entries():rn(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){let s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=rn(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,l])}}var _=n=>{let e=new Headers,t=new Set;for(let r of n){let s=new Set;for(let[o,i]of Ho(r)){let l=o.toLowerCase();s.has(l)||(e.delete(o),s.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[Gs]:!0,values:e,nulls:t}};var At=class extends h{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};a();var xt=class extends h{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var It=class extends h{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends h{constructor(){super(...arguments),this.transcriptions=new xt(this._client),this.translations=new It(this._client),this.speech=new At(this._client)}};se.Transcriptions=xt;se.Translations=It;se.Speech=At;a();var Le=class extends h{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(m`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",R,{query:e,...t})}cancel(e,t){return this._client.post(m`/batches/${e}/cancel`,t)}};a();a();var Pt=class extends h{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/assistants/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(m`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();a();var Rt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Ot=class extends h{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends h{constructor(){super(...arguments),this.sessions=new Rt(this._client),this.transcriptionSessions=new Ot(this._client)}};we.Sessions=Rt;we.TranscriptionSessions=Ot;a();a();var St=class extends h{create(e,t,r){return this._client.post(m`/threads/${e}/messages`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(m`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/messages/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/threads/${e}/messages`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(m`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();var Et=class extends h{retrieve(e,t,r){let{thread_id:s,run_id:o,...i}=t;return this._client.get(m`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...o}=t;return this._client.getAPIList(m`/threads/${s}/runs/${e}/steps`,R,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var Bs=n=>{if(typeof Buffer<"u"){let e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};a();var Ae=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var B,Ue,Nn,oe,Dr,Y,De,vt,Fe,Br,z,jr,Gr,ur,lr,cr,Ws,Hs,qs,Xs,Js,Vs,Ks,pe=class extends be{constructor(){super(...arguments),B.add(this),Nn.set(this,[]),oe.set(this,{}),Dr.set(this,{}),Y.set(this,void 0),De.set(this,void 0),vt.set(this,void 0),Fe.set(this,void 0),Br.set(this,void 0),z.set(this,void 0),jr.set(this,void 0),Gr.set(this,void 0),ur.set(this,void 0)}[(Nn=new WeakMap,oe=new WeakMap,Dr=new WeakMap,Y=new WeakMap,De=new WeakMap,vt=new WeakMap,Fe=new WeakMap,Br=new WeakMap,z=new WeakMap,jr=new WeakMap,Gr=new WeakMap,ur=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ue;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=re.fromReadableStream(e,this.controller);for await(let o of s)c(this,B,"m",lr).call(this,o);if(s.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}static createThreadAssistantStream(e,t,r){let s=new Ue;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,jr,"f")}currentRun(){return c(this,Gr,"f")}currentMessageSnapshot(){return c(this,Y,"f")}currentRunStepSnapshot(){return c(this,ur,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Dr,"f"))}async finalRun(){if(await this.done(),!c(this,De,"f"))throw Error("Final run was not received.");return c(this,De,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let l of i)c(this,B,"m",lr).call(this,l);if(i.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}async _createAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Vt(o)&&Vt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!Vt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),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 u=o[l];u==null?o.push(i):o[l]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, 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,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}};Ue=pe,lr=function(e){if(!this.ended)switch(A(this,jr,e,"f"),c(this,B,"m",qs).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":c(this,B,"m",Ks).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":c(this,B,"m",Hs).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":c(this,B,"m",Ws).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},cr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!c(this,De,"f"))throw Error("Final run has not been received");return c(this,De,"f")},Ws=function(e){let[t,r]=c(this,B,"m",Js).call(this,e,c(this,Y,"f"));A(this,Y,t,"f"),c(this,Dr,"f")[t.id]=t;for(let s of r){let o=t.content[s.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=c(this,vt,"f")){if(c(this,Fe,"f"))switch(c(this,Fe,"f").type){case"text":this._emit("textDone",c(this,Fe,"f").text,c(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Fe,"f").image_file,c(this,Y,"f"));break}A(this,vt,s.index,"f")}A(this,Fe,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,vt,"f")!==void 0){let s=e.data.content[c(this,vt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Y,"f"));break;case"text":this._emit("textDone",s.text,c(this,Y,"f"));break}}c(this,Y,"f")&&this._emit("messageDone",e.data),A(this,Y,void 0,"f")}},Hs=function(e){let t=c(this,B,"m",Xs).call(this,e);switch(A(this,ur,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==c(this,Br,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,z,"f")&&this._emit("toolCallDone",c(this,z,"f")),A(this,Br,o.index,"f"),A(this,z,t.step_details.tool_calls[o.index],"f"),c(this,z,"f")&&this._emit("toolCallCreated",c(this,z,"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":A(this,ur,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},qs=function(e){c(this,Nn,"f").push(e),this._emit("event",e)},Xs=function(e){switch(e.event){case"thread.run.step.created":return c(this,oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,oe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let s=Ue.accumulateDelta(t,r.delta);c(this,oe,"f")[e.data.id]=s}return c(this,oe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,oe,"f")[e.data.id]=e.data;break}if(c(this,oe,"f")[e.data.id])return c(this,oe,"f")[e.data.id];throw new Error("No snapshot available")},Js=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 s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=c(this,B,"m",Vs).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Vs=function(e,t){return Ue.accumulateDelta(t,e)},Ks=function(e){switch(A(this,Gr,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":A(this,De,e.data,"f"),c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f"));break;case"thread.run.cancelling":break}};var je=class extends h{constructor(){super(...arguments),this.steps=new Et(this._client)}create(e,t,r){let{include:s,...o}=t;return this._client.post(m`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(m`/threads/${s}/runs/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/runs/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/threads/${e}/runs`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(m`/threads/${s}/runs/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};je.Steps=Et;var xe=class extends h{constructor(){super(...arguments),this.runs=new je(this._client),this.messages=new St(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/threads/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(m`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}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 pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=je;xe.Messages=St;var ie=class extends h{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new Pt(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=Pt;ie.Threads=xe;a();var Ge=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var Tt=class extends h{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(m`/containers/${s}/files/${e}/content`,{...r,headers:_([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var Be=class extends h{constructor(){super(...arguments),this.content=new Tt(this._client)}create(e,t,r){return this._client.post(m`/containers/${e}/files`,K({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(m`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(m`/containers/${e}/files`,R,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(m`/containers/${s}/files/${e}`,{...r,headers:_([{Accept:"*/*"},r?.headers])})}};Be.Content=Tt;var Ie=class extends h{constructor(){super(...arguments),this.files=new Be(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(m`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=Be;a();var We=class extends h{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";r&&v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?o:(v(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let u=l.embedding;l.embedding=Bs(u)}),i)))}};a();a();a();var kt=class extends h{retrieve(e,t,r){let{eval_id:s,run_id:o}=t;return this._client.get(m`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...o}=t;return this._client.getAPIList(m`/evals/${s}/runs/${e}/output_items`,R,{query:o,...r})}};var He=class extends h{constructor(){super(...arguments),this.outputItems=new kt(this._client)}create(e,t,r){return this._client.post(m`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(m`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(m`/evals/${e}/runs`,R,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(m`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(m`/evals/${s}/runs/${e}`,r)}};He.OutputItems=kt;var Pe=class extends h{constructor(){super(...arguments),this.runs=new He(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(m`/evals/${e}`,t)}update(e,t,r){return this._client.post(m`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/evals/${e}`,t)}};Pe.Runs=He;a();var qe=class extends h{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(m`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/files/${e}`,t)}content(e,t){return this._client.get(m`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await ee(t),i=await this.retrieve(e),Date.now()-o>r)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};a();a();var Mt=class extends h{};a();a();var $t=class extends h{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Xe=class extends h{constructor(){super(...arguments),this.graders=new $t(this._client)}};Xe.Graders=$t;a();a();var Nt=class extends h{create(e,t,r){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(m`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}};var Je=class extends h{constructor(){super(...arguments),this.permissions=new Nt(this._client)}};Je.Permissions=Nt;a();a();var Lt=class extends h{list(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...r})}};var Ve=class extends h{constructor(){super(...arguments),this.checkpoints=new Lt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(m`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...t})}cancel(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,R,{query:t,...r})}pause(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=Lt;var Q=class extends h{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Je(this._client),this.alpha=new Xe(this._client)}};Q.Methods=Mt;Q.Jobs=Ve;Q.Checkpoints=Je;Q.Alpha=Xe;a();a();var Ft=class extends h{};var Re=class extends h{constructor(){super(...arguments),this.graderModels=new Ft(this._client)}};Re.GraderModels=Ft;a();var Ke=class extends h{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};a();var ze=class extends h{retrieve(e,t){return this._client.get(m`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(m`/models/${e}`,t)}};a();var Ye=class extends h{create(e,t){return this._client.post("/moderations",{body:e,...t})}};a();a();function zs(n,e){return!e||!hi(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Ln(n,e)}function Ln(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:bi(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:mi(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Wr(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let s of r.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function mi(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function hi(n){return!!sr(n.text?.format)}function gi(n){return n?.$brand==="auto-parseable-tool"}function _i(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function bi(n,e){let t=_i(n.tools??[],e.name);return{...e,...e,parsed_arguments:gi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Wr(n){let e=[];for(let t of n.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}a();var Ut,Hr,Oe,qr,Ys,Qs,Zs,eo,Xr=class n extends be{constructor(e){super(),Ut.add(this),Hr.set(this,void 0),Oe.set(this,void 0),qr.set(this,void 0),A(this,Hr,e,"f")}static createResponse(e,t,r){let s=new n(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,Ut,"m",Ys).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let l of o)c(this,Ut,"m",Qs).call(this,l,i);if(o.controller.signal?.aborted)throw new k;return c(this,Ut,"m",Zs).call(this)}[(Hr=new WeakMap,Oe=new WeakMap,qr=new WeakMap,Ut=new WeakSet,Ys=function(){this.ended||A(this,Oe,void 0,"f")},Qs=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Ut,"m",eo).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new y(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Zs=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,Oe,"f");if(!t)throw new y("request ended without sending any events");A(this,Oe,void 0,"f");let r=yi(t,c(this,Hr,"f"));return A(this,qr,r,"f"),r},eo=function(t){let r=c(this,Oe,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=A(this,Oe,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{A(this,Oe,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,qr,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function yi(n,e){return zs(n,e)}a();var Dt=class extends h{list(e,t={},r){return this._client.getAPIList(m`/responses/${e}/input_items`,R,{query:t,...r})}};var Se=class extends h{constructor(){super(...arguments),this.inputItems=new Dt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Wr(r),r))}retrieve(e,t={},r){return this._client.get(m`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Wr(s),s))}delete(e,t){return this._client.delete(m`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Ln(r,e))}stream(e,t){return Xr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(m`/responses/${e}/cancel`,t)}};Se.InputItems=Dt;a();a();var jt=class extends h{create(e,t,r){return this._client.post(m`/uploads/${e}/parts`,K({body:t,...r},this._client))}};var Ee=class extends h{constructor(){super(...arguments),this.parts=new jt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(m`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(m`/uploads/${e}/complete`,{body:t,...r})}};Ee.Parts=jt;a();a();a();var to=async n=>{let e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let s of e)s.status==="fulfilled"&&r.push(s.value);return r};var Gt=class extends h{create(e,t,r){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(m`/vector_stores/${s}/file_batches/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(m`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...o}=t;return this._client.getAPIList(m`/vector_stores/${s}/file_batches/${e}/files`,R,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){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=s?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,u=t.values(),d=[...r];async function g(b){for(let f of b){let x=await l.files.create({file:f,purpose:"assistants"},s);d.push(x.id)}}let p=Array(i).fill(u).map(g);return await to(p),await this.createAndPoll(e,{file_ids:d})}};a();var Bt=class extends h{create(e,t,r){return this._client.post(m`/vector_stores/${e}/files`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(m`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...o}=t;return this._client.post(m`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/vector_stores/${e}/files`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(m`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=_([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:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(m`/vector_stores/${s}/files/${e}/content`,ne,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var de=class extends h{constructor(){super(...arguments),this.files=new Bt(this._client),this.fileBatches=new Gt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/vector_stores/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(m`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(m`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};de.Files=Bt;de.FileBatches=Gt;a();var Wt,ro,Jr,Qe=class extends h{constructor(){super(...arguments),Wt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Wt,"m",ro).call(this,r);let o=_([t]).values,i=c(this,Wt,"m",Jr).call(this,o,"webhook-signature"),l=c(this,Wt,"m",Jr).call(this,o,"webhook-timestamp"),u=c(this,Wt,"m",Jr).call(this,o,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Z("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-d>s)throw new Z("Webhook timestamp is too old");if(d>g+s)throw new Z("Webhook timestamp is too new");let p=i.split(" ").map(C=>C.startsWith("v1,")?C.substring(3):C),b=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${l}.${e}`:`${l}.${e}`,x=await crypto.subtle.importKey("raw",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let C of p)try{let P=Buffer.from(C,"base64");if(await crypto.subtle.verify("HMAC",x,P,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Wt=new WeakSet,ro=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")},Jr=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 Fn,Un,Vr,no,I=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:r=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Fn.add(this),Vr.set(this,void 0),this.completions=new Ge(this),this.chat=new Ce(this),this.embeddings=new We(this),this.files=new qe(this),this.images=new Ke(this),this.audio=new se(this),this.moderations=new Ye(this),this.models=new ze(this),this.fineTuning=new Q(this),this.graders=new Re(this),this.vectorStores=new de(this),this.webhooks=new Qe(this),this.beta=new ie(this),this.batches=new Le(this),this.uploads=new Ee(this),this.responses=new Se(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let l={apiKey:t,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&ds())throw new y(`It looks like you're running in a browser-like environment.
|
|
17
|
+
|
|
18
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
19
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
20
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
21
|
+
|
|
22
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
23
|
+
|
|
24
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
25
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Un.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=dn(l.logLevel,"ClientOptions.logLevel",this)??dn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??hs(),A(this,Vr,_s,"f"),this._options=l,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return fn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${tn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Fn,"m",no).call(this)&&r||this.baseURL,o=ss(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return is(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}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(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(v(this).debug(`[${d}] sending request`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Jt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Xt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new he({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await gs(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Jt(E).message),S=cs(U),X=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,X,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Qt(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,g={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(g.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}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,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let l=s?.get("retry-after");if(l&&!o){let u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ee(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&ls("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:g}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Cr(e)}:c(this,Vr,"f").call(this,{body:e,headers:r})}};Un=I,Vr=new WeakMap,Fn=new WeakSet,no=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Un;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=Er;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=Ke;I.Audio=se;I.Moderations=Ye;I.Models=ze;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Qe;I.Beta=ie;I.Batches=Le;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Pi(n){return n.toLowerCase().includes("matilda3")}function Ri(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?n:{...e,reasoning:e.reasoning_content}}var F=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))Zn(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=this.contentGeneratorConfig.extra_body,s=this.applyOutputTokenLimit(e),o=Pi(e.model)?s.messages.map(Ri):s.messages;return{...s,messages:o,...r||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,r=zn(e.model,"output"),s=Kn(e.model),o;if(t!=null)s?o=Math.min(t,r):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,l=i?parseInt(i,10):NaN;!isNaN(l)&&l>0?o=s?Math.min(l,r):l:o=Math.min(r,8e3)}return{...e,max_tokens:o}}};var Ht=class extends F{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let r=super.buildRequest(e,t);return r.stream||delete r.stream_options,r}};a();var Oi=me("MatildaOpenAICompatibleProvider"),ae=class n extends F{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:r}=e;if(t==="matilda-oauth"||!r)return!0;let s=r.endsWith("/")?r.slice(0,-1):r,o=null;try{o=new URL(s).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),l=hr?.endsWith("/")?hr.slice(0,-1):hr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&Oi.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||u}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))!ts(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,es(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Yn,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br();if(!b&&Object.keys(f).length===0)return l(d,g);p.delete(gr),p.delete(_r);for(let[C,P]of Object.entries(f))p.set(C,P);let x=p.get("x-stainless-retry-count");return p.has(gr)&&x!==null&&/^[1-9][0-9]*$/.test(x)&&p.set(_r,"retry"),l(d,{...g,headers:p})}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}buildRequest(e,t){let r=e.messages,s=e.tools;if(this.shouldEnableCacheControl()){let{messages:l,tools:u}=this.addCacheControl(e,e.stream?"all":"system_only");r=l,s=u}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let r=e.messages,s=r.findIndex(u=>u.role==="system"),o=r.length-1,i=r.length===0?r:r.map((u,d)=>!(d===s&&s!==-1||d===o&&t==="all")||!("content"in u)||u.content===null||u.content===void 0?u:{...u,content:this.addCacheControlToContent(u.content)}),l=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:l}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],r=e.length-1;return t[r]={...t[r],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(n.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let r of n.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(r))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};a();a();function Kr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Si(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Si;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?vi(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=Ei(i);return Kr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function Ei(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
|
|
26
|
+
|
|
27
|
+
`);return{...n,content:t}}function vi(n){let e=n,t=e.reasoning,r=t?.effort;if(typeof r!="string"||!r)return n;let s={...e};if(typeof s.reasoning_effort!="string"||!s.reasoning_effort){let o=r;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),s.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete s.reasoning;else if(t){let{effort:o,...i}=t;s.reasoning=i}return s}a();var et=class extends F{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};a();var Ti=["api.minimaxi.com","api.minimax.io"],ki=[".minimaxi.com",".minimax.io"],tt=class extends F{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return Ti.includes(t)?!0:ki.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var so="api.mistral.ai",Mi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function $i(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===so||t.endsWith(`.${so}`)}catch{return!1}}function Ni(n){if($i(n))return!0;let e=n.model?.toLowerCase()??"";return Mi.some(t=>e.includes(t))}var rt=class extends F{static isMistralProvider=Ni;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Li)}}};function Li(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Fi(n){let e=n.baseUrl??"";if(e)try{let r=new URL(e).hostname.toLowerCase();if(r==="xiaomimimo.com"||r.endsWith(".xiaomimimo.com"))return!0}catch{}return(n.model??"").toLowerCase().startsWith("mimo-")}var nt=class extends F{constructor(e,t){super(e,t)}static isMiMoProvider=Fi;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(Kr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var Ui=me("STREAMING_TOOL_CALL_PARSER"),zr=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,r,s){let o=e,i=!!(r&&this.idToIndexMap.has(r));if(r)if(this.idToIndexMap.has(r))o=this.idToIndexMap.get(r);else{if(this.buffers.has(e)){let P=this.buffers.get(e),O=this.depths.get(e),w=this.toolCallMeta.get(e);if(P.trim()&&O===0&&w?.id&&w.id!==r)try{JSON.parse(P),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let P=this.buffers.get(e);if(this.depths.get(e)>0||!P.trim())o=e;else try{JSON.parse(P),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let l=this.buffers.get(o),u=this.depths.get(o);if(i&&l.trim()&&u===0)try{return JSON.parse(l),Ui.debug(`Ignoring replay chunk for completed toolCall id=${r}`),{complete:!1}}catch{}let d=this.toolCallMeta.get(o);r&&(d.id=r),s&&(d.name=s);let g=this.inStrings.get(o),p=this.escapes.get(o),b=l+t;this.buffers.set(o,b);let f=u,x=g,C=p;for(let P of t)x||(P==="{"||P==="["?f++:(P==="}"||P==="]")&&f--),P==='"'&&!C&&(x=!x),C=P==="\\"&&!C;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,C),f===0&&b.trim().length>0)try{return{complete:!0,value:JSON.parse(b)}}catch(P){if(x)try{return{complete:!0,value:JSON.parse(b+'"'),repaired:!0}}catch{}return{complete:!1,error:P instanceof Error?P:new Error(String(P))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){let e=[],t=new Set;for(let[r,s]of this.buffers.entries()){let o=this.toolCallMeta.get(r);if(o?.name&&s.trim()){if(o.id){if(t.has(o.id))continue;t.add(o.id)}let i={};try{i=JSON.parse(s)}catch{if(this.inStrings.get(r))try{i=JSON.parse(s+'"')}catch{i=Zr(s,{})}else i=Zr(s,{})}e.push({id:o.id,name:o.name,args:i,index:r})}}return e}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),r=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!r?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,r]of this.buffers.entries()){let s=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(s>0||!r.trim()))e=Math.max(e,t);else if(r.trim())try{JSON.parse(r)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e]of this.buffers.entries()){if(!this.toolCallMeta.get(e)?.name)continue;let r=this.depths.get(e)||0,s=this.inStrings.get(e)||!1;if(r>0||s)return!0}return!1}};var oo=16e3,io=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
28
|
+
`,Yr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ot.convertOpenAIResponseToGemini(u,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders(),u;try{u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}})}catch(b){throw i?.abort(),b}if(!i)return this.processStreamWithLogging(u,s,e);let d=i,g=this.processStreamWithLogging(u,s,e);async function*p(){try{yield*g}finally{d.abort()}}return p()})}reportedOperationHeaders(){if(!qt(this.contentGeneratorConfig))return;let e=br();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,r){let s=[],o=null,i=!1;try{for await(let l of e){if(l.choices?.[0]?.finish_reason==="error_finish"){let g=l.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new Yr(g)}let u=ot.convertOpenAIChunkToGemini(l,t);if(u.candidates?.[0]?.content?.parts?.length===0&&!u.candidates?.[0]?.finishReason&&!u.usageMetadata)continue;if(i){if(u.usageMetadata){let g=o;g&&(g.usageMetadata=u.usageMetadata)}s.push(u);continue}this.handleChunkMerging(u,s,g=>{o=g})&&(o?(yield o,i=!0):yield u)}o&&!i&&(yield o)}catch(l){if(l instanceof Yr)throw ve(l);await this.handleError(l,t,r)}}handleChunkMerging(e,t,r){let s=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(s){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),r(i)}else t.push(e),r(e);return!1}else if(o){let i=t[t.length-1],l=new Hn;return l.candidates=i.candidates,e.usageMetadata?l.usageMetadata=e.usageMetadata:l.usageMetadata=i.usageMetadata,l.responseId=e.responseId,l.createTime=e.createTime,l.modelVersion=e.modelVersion,l.promptFeedback=e.promptFeedback,t[t.length-1]=l,r(l),!0}return t.push(e),!0}async buildRequest(e,t,r,s){let o=ot.convertGeminiRequestToOpenAI(e,r),i=this.shouldUseMatildaCoreRequestProfile(),l=i?this.toMatildaCoreUserMessages(o):o,u={model:r.model,messages:l,...this.buildGenerateContentConfig(e)};s?(u.stream=!0,u.stream_options={include_usage:!0}):u.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(u.tools=await ot.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let d=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let p=d,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="coder-model")){p.enable_thinking=!1;let f=p.chat_template_kwargs;typeof f=="object"&&f!==null&&"enable_thinking"in f&&(p.chat_template_kwargs={...f,enable_thinking:!1})}"reasoning"in p&&delete p.reasoning,"reasoning_effort"in p&&delete p.reasoning_effort,fr(this.contentGeneratorConfig)&&(p.thinking={type:"disabled"})}return d}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile;if(e==="matilda-core")return!0;if(e==="matilda-code")return!1;let t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(t.endsWith("/api/v1/code"))return!1;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
|
|
29
|
+
`):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=oo)return r;let s=oo-io.length;return`${io}${r.slice(-s)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),r=this.contentGeneratorConfig.samplingParams,s=(l,u)=>{let d=r?.[l],g=u?e.config?.[u]:void 0,p=u?t[u]:void 0;return d!==void 0?d:g!==void 0?g:p},o=(l,u,d)=>{let g=s(u,d);return g!==void 0?{[l]:g}:{}};if(r!==void 0){let l=e.config?.maxOutputTokens;return{...r,...l!==void 0&&r.max_tokens!==void 0?{max_tokens:l}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,r,s){let o=this.createRequestContext(e,r);try{let i=await this.buildRequest(e,t,o,r);return Xn.getStore()?.(i),Jn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(ve(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new zr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new qn:void 0;return{model:r,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:s.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...l?{taggedThinkingParser:l}:{}}}};a();var Di=me("OPENAI_ERROR"),dr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=ve(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Di.error("OpenAI API Error:",i),o?new Error(`${i}
|
|
30
|
+
|
|
31
|
+
${this.getTimeoutTroubleshootingTips()}`):s}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e?.code,s=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||r==="ETIMEDOUT"||r==="ESOCKETTIMEDOUT"||s==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,r){let s=Math.round((Date.now()-t.startTime)/1e3);return r?`Request timeout after ${s}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
|
|
32
|
+
${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
|
|
33
|
+
`)}`}};var ao=me("OPENAI"),st=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(Wn(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new rs().calculateTokens(e)).totalTokens}}catch(t){ao.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let r=JSON.stringify(e.contents);return{totalTokens:Math.ceil(r.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(r=>typeof r=="string"?r:"parts"in r&&r.parts?r.parts.map(s=>typeof s=="string"?s:"text"in s&&s.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(r){let s=ve(r);throw ao.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var mr=class extends st{contentGeneratorConfig;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e}shouldSuppressErrorLogging(e,t){return lo(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.withTokenRefresh(()=>super.generateContentStream(e,t))}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t=await Qn({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh});t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[ns]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!lo(t))throw t;return await this.applyValidToken({forceRefresh:!0}),await e()}}};function lo(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=t?.status||t?.code||t?.statusCode;return r===401||r===403||r==="401"||r==="403"||e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function l_(n,e){let t=ji(n,e);return ae.isMatildaCompatibleProvider(n)?new mr(n,e,t):new st(n,e,t)}function ji(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):Ze.isDeepSeekProvider(t)?new Ze(n,e):nt.isMiMoProvider(t)?new nt(n,e):et.isOpenRouterProvider(t)?new et(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):tt.isMiniMaxProvider(t)?new tt(n,e):rt.isMistralProvider(t)?new rt(n,e):new F(n,e)}export{ae as a,Ze as b,et as c,tt as d,rt as e,nt as f,pr as g,dr as h,st as i,mr as j,l_ as k,ji as l};
|
|
34
|
+
/**
|
|
35
|
+
* @license
|
|
36
|
+
* Copyright 2025 Matilda
|
|
37
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* @license
|
|
41
|
+
* Copyright 2026 Maincode
|
|
42
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
43
|
+
*
|
|
44
|
+
* OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
|
|
45
|
+
*
|
|
46
|
+
* Emulates Grok Build's automatic credential refresh
|
|
47
|
+
* (docs: "Automatic Credential Refresh"):
|
|
48
|
+
* 1. Before each request: ensure a fresh access token (re-read disk; refresh
|
|
49
|
+
* when within the early-invalidation window / already expired).
|
|
50
|
+
* 2. On 401 Unauthorized: force-refresh and retry the request once.
|
|
51
|
+
* 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
|
|
52
|
+
*
|
|
53
|
+
* Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
|
|
54
|
+
* createContentGenerator time, so idle sessions past access-token expiry
|
|
55
|
+
* failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
|
|
56
|
+
*/
|