@shumai-one/shumai-agent 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/chunk-115gx56y.js +12 -0
- package/bin/chunk-24s58f6x.js +11 -0
- package/bin/chunk-2mj5h53m.js +5 -0
- package/bin/chunk-3dr4h1df.js +16 -0
- package/bin/chunk-3mdhkfgq.js +3 -0
- package/bin/chunk-5axrg8rz.js +2 -0
- package/bin/chunk-5vk5pgxq.js +45 -0
- package/bin/chunk-7hkzk9pe.js +3 -0
- package/bin/chunk-7z62cgr7.js +3 -0
- package/bin/chunk-8cz84wva.js +4 -0
- package/bin/chunk-97avgejq.js +2 -0
- package/bin/chunk-avm8xsd8.js +3 -0
- package/bin/chunk-b5hbfteg.js +2 -0
- package/bin/chunk-c8vf5ezv.js +24 -0
- package/bin/chunk-caw017nc.js +3 -0
- package/bin/chunk-dak3e9js.js +2 -0
- package/bin/chunk-dpd0zpsp.js +3 -0
- package/bin/chunk-gkwywrkk.js +2 -0
- package/bin/chunk-gqvwjf6q.js +2 -0
- package/bin/chunk-hme2crct.js +2 -0
- package/bin/chunk-hyc2kn1w.js +8 -0
- package/bin/chunk-kvt13jb9.js +2 -0
- package/bin/chunk-m51y6s92.js +2 -0
- package/bin/chunk-p7sczpks.js +3 -0
- package/bin/chunk-phjnj6x5.js +3 -0
- package/bin/chunk-ptxcc9bv.js +2 -0
- package/bin/chunk-q7ypqj4c.js +2 -0
- package/bin/chunk-r8hcdypf.js +2 -0
- package/bin/chunk-rv0jkz1g.js +8 -0
- package/bin/chunk-shv0zdbp.js +4 -0
- package/bin/chunk-smv5ztx4.js +2 -0
- package/bin/chunk-spcaxtg5.js +7 -0
- package/bin/chunk-sxrz8e3j.js +3 -0
- package/bin/chunk-v8rxcp9h.js +2 -0
- package/bin/chunk-xmq8pwcp.js +13379 -0
- package/bin/chunk-y6h80xaa.js +13 -0
- package/bin/chunk-zcx3awzq.js +3 -0
- package/bin/shumai-agent-app.js +656 -449
- package/package.json +18 -18
- package/prisma/migrations/20260904022457_add_agent_id_to_assets_and_audit_logs/migration.sql +17 -0
- package/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql +15 -0
- package/prisma/schema.prisma +9 -0
- package/bin/chunk-1ep7nnzp.js +0 -5
- package/bin/chunk-1jq2vgrd.js +0 -3
- package/bin/chunk-2ntm65jn.js +0 -3
- package/bin/chunk-3nh1p64q.js +0 -12
- package/bin/chunk-41gh01qj.js +0 -3
- package/bin/chunk-4n1309xp.js +0 -2
- package/bin/chunk-616f7y5x.js +0 -8
- package/bin/chunk-6a9h5d64.js +0 -3
- package/bin/chunk-6dp3ybh2.js +0 -3
- package/bin/chunk-6nd8f70y.js +0 -4
- package/bin/chunk-6vs3gb9g.js +0 -2
- package/bin/chunk-7dyx5m0f.js +0 -6
- package/bin/chunk-7j3qbvwc.js +0 -7
- package/bin/chunk-9h5qhgqx.js +0 -13
- package/bin/chunk-b9s67nd8.js +0 -2
- package/bin/chunk-c14kvr2r.js +0 -11
- package/bin/chunk-cb5p7shk.js +0 -12240
- package/bin/chunk-ccx6803n.js +0 -44
- package/bin/chunk-cm4dpd3k.js +0 -4
- package/bin/chunk-dd2tfwzy.js +0 -45
- package/bin/chunk-dk9vz5tv.js +0 -4
- package/bin/chunk-e6691p0v.js +0 -3
- package/bin/chunk-e9d2ah8y.js +0 -3
- package/bin/chunk-fvmb8en4.js +0 -24
- package/bin/chunk-gegf6d3m.js +0 -2
- package/bin/chunk-gx9vdcbm.js +0 -2
- package/bin/chunk-j427r7a5.js +0 -2
- package/bin/chunk-jperx2a8.js +0 -6
- package/bin/chunk-k4jm2gt4.js +0 -3
- package/bin/chunk-m29dphbf.js +0 -3
- package/bin/chunk-mpgy1y53.js +0 -3
- package/bin/chunk-n1t3he2k.js +0 -3
- package/bin/chunk-pmdb6y7t.js +0 -2
- package/bin/chunk-qx9njyk7.js +0 -3
- package/bin/chunk-r5h7vczc.js +0 -3
- package/bin/chunk-spm76160.js +0 -2
- package/bin/chunk-t8k09sgb.js +0 -3
- package/bin/chunk-tvef1ck8.js +0 -2
- package/bin/chunk-v4j6yxch.js +0 -3
- package/bin/chunk-vjzrmneg.js +0 -2
- package/bin/chunk-x25enwfz.js +0 -3
- package/bin/chunk-xg9xscqz.js +0 -1
- package/bin/chunk-xqg06q7q.js +0 -2
- package/bin/chunk-xvbd9e2b.js +0 -8
- package/bin/chunk-y2z3xj0m.js +0 -12
- package/bin/chunk-ywhrsshf.js +0 -2
- package/bin/chunk-z512b49m.js +0 -3
- package/bin/chunk-z58rb52r.js +0 -3
- package/bin/chunk-zazbsz25.js +0 -3
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function w(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jr=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function pt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var mt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class _ extends Error{}class T extends _{constructor(e,t,r,s){super(`${T.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.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;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Ae({message:r,cause:mt(t)});let n=t?.error;if(e===400)return new _t(e,n,r,s);if(e===401)return new gt(e,n,r,s);if(e===403)return new yt(e,n,r,s);if(e===404)return new bt(e,n,r,s);if(e===409)return new wt(e,n,r,s);if(e===422)return new xt(e,n,r,s);if(e===429)return new At(e,n,r,s);if(e>=500)return new It(e,n,r,s);return new T(e,n,r,s)}}class N extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ae extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ie extends Ae{constructor({message:e}={}){super({message:e??"Request timed out."})}}class _t extends T{}class gt extends T{}class yt extends T{}class bt extends T{}class wt extends T{}class xt extends T{}class At extends T{}class It extends T{}class Pt extends _{constructor(){super("Could not parse response content as the length limit was reached")}}class St extends _{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ne extends Error{constructor(e){super(e)}}var Dn=/^[a-z][a-z0-9+.-]*:/i,Es=(e)=>Dn.test(e),j=(e)=>(j=Array.isArray,j(e)),Xr=j;function Vr(e){if(typeof e!=="object")return{};return e??{}}function vs(e){if(!e)return!0;for(let t in e)return!1;return!0}function $s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ue(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var ks=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new _(`${e} must be an integer`);if(t<0)throw new _(`${e} must be a positive integer`);return t};var Os=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Q=(e)=>new Promise((t)=>setTimeout(t,e));var he="6.26.0";var Ms=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Wn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var qn=()=>{let e=Wn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(Deno.build.os),"X-Stainless-Arch":Ts(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":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ts(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Hn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hn(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Ts=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Fs=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Ns,Ls=()=>Ns??(Ns=qn());function Bs(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Kr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function mr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Kr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Gr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Us(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var js=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var zr="RFC3986",Qr=(e)=>String(e),Yr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:Qr},Ds="RFC1738";var _r=(e,t)=>(_r=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),_r(e,t)),Y=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Zr=1024,Ws=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Zr){let d=o.length>=Zr?o.slice(f,f+Zr):o,g=[];for(let b=0;b<d.length;++b){let m=d.charCodeAt(b);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||n===Ds&&(m===40||m===41)){g[g.length]=d.charAt(b);continue}if(m<128){g[g.length]=Y[m];continue}if(m<2048){g[g.length]=Y[192|m>>6]+Y[128|m&63];continue}if(m<55296||m>=57344){g[g.length]=Y[224|m>>12]+Y[128|m>>6&63]+Y[128|m&63];continue}b+=1,m=65536+((m&1023)<<10|d.charCodeAt(b)&1023),g[g.length]=Y[240|m>>18]+Y[128|m>>12&63]+Y[128|m>>6&63]+Y[128|m&63]}a+=g.join("")}return a};function qs(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function es(e,t){if(j(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Js={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Xs=function(e,t){Array.prototype.push.apply(e,j(t)?t:[t])},Hs,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ws,encodeValuesOnly:!1,format:zr,formatter:Qr,indices:!1,serializeDate(e){return(Hs??(Hs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Vn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var ts={};function Vs(e,t,r,s,n,o,a,f,d,g,b,m,u,x,y,C,R,P){let I=e,O=P,v=0,q=!1;while((O=O.get(ts))!==void 0&&!q){let S=O.get(e);if(v+=1,typeof S<"u")if(S===v)throw RangeError("Cyclic object value");else q=!0;if(typeof O.get(ts)>"u")v=0}if(typeof g==="function")I=g(t,I);else if(I instanceof Date)I=u?.(I);else if(r==="comma"&&j(I))I=es(I,function(S){if(S instanceof Date)return u?.(S);return S});if(I===null){if(o)return d&&!C?d(t,M.encoder,R,"key",x):t;I=""}if(Vn(I)||qs(I)){if(d){let S=C?t:d(t,M.encoder,R,"key",x);return[y?.(S)+"="+y?.(d(I,M.encoder,R,"value",x))]}return[y?.(t)+"="+y?.(String(I))]}let F=[];if(typeof I>"u")return F;let E;if(r==="comma"&&j(I)){if(C&&d)I=es(I,d);E=[{value:I.length>0?I.join(",")||null:void 0}]}else if(j(g))E=g;else{let S=Object.keys(I);E=b?S.sort(b):S}let D=f?String(t).replace(/\./g,"%2E"):String(t),se=s&&j(I)&&I.length===1?D+"[]":D;if(n&&j(I)&&I.length===0)return se+"[]";for(let S=0;S<E.length;++S){let fe=E[S],Rs=typeof fe==="object"&&typeof fe.value<"u"?fe.value:I[fe];if(a&&Rs===null)continue;let Hr=m&&f?fe.replace(/\./g,"%2E"):fe,Un=j(I)?typeof r==="function"?r(se,Hr):se:se+(m?"."+Hr:"["+Hr+"]");P.set(e,v);let Cs=new WeakMap;Cs.set(ts,P),Xs(F,Vs(Rs,Un,r,s,n,o,a,f,r==="comma"&&C&&j(I)?null:d,g,b,m,u,x,y,C,R,Cs))}return F}function Kn(e=M){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||M.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=zr;if(typeof e.format<"u"){if(!_r(Yr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Yr[r],n=M.filter;if(typeof e.filter==="function"||j(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Js)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=M.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:M.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?M.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:M.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:M.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:M.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:M.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:M.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:M.strictNullHandling}}function Ks(e,t={}){let r=e,s=Kn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(j(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Js[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let g=new WeakMap;for(let u=0;u<n.length;++u){let x=n[u];if(s.skipNulls&&r[x]===null)continue;Xs(a,Vs(r[x],x,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,g))}let b=a.join(s.delimiter),m=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")m+="utf8=%26%2310003%3B&";else m+="utf8=%E2%9C%93&";return b.length>0?m+b:""}function Gs(e){return Ks(e,{arrayFormat:"brackets"})}function Ys(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var zs;function je(e){let t;return(zs??(t=new globalThis.TextEncoder,zs=t.encode.bind(t)))(e)}var Qs;function rs(e){let t;return(Qs??(t=new globalThis.TextDecoder,Qs=t.decode.bind(t)))(e)}var H,J;class De{constructor(){H.set(this,void 0),J.set(this,void 0),w(this,H,new Uint8Array,"f"),w(this,J,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?je(e):e;w(this,H,Ys([i(this,H,"f"),t]),"f");let r=[],s;while((s=zn(i(this,H,"f"),i(this,J,"f")))!=null){if(s.carriage&&i(this,J,"f")==null){w(this,J,s.index,"f");continue}if(i(this,J,"f")!=null&&(s.index!==i(this,J,"f")+1||s.carriage)){r.push(rs(i(this,H,"f").subarray(0,i(this,J,"f")-1))),w(this,H,i(this,H,"f").subarray(i(this,J,"f")),"f"),w(this,J,null,"f");continue}let n=i(this,J,"f")!==null?s.preceding-1:s.preceding,o=rs(i(this,H,"f").subarray(0,n));r.push(o),w(this,H,i(this,H,"f").subarray(s.index),"f"),w(this,J,null,"f")}return r}flush(){if(!i(this,H,"f").length)return[];return this.decode(`
|
|
3
|
+
`)}}H=new WeakMap,J=new WeakMap;De.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]);De.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Zs(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var yr={off:0,error:200,warn:300,info:400,debug:500},ss=(e,t,r)=>{if(!e)return;if($s(yr,e))return e;k(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(yr))}`);return};function Rt(){}function gr(e,t,r){if(!t||yr[e]>yr[r])return Rt;else return t[e].bind(t)}var Qn={error:Rt,warn:Rt,info:Rt,debug:Rt},en=new WeakMap;function k(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Qn;let s=en.get(t);if(s&&s[0]===r)return s[1];let n={error:gr("error",t,r),warn:gr("warn",t,r),info:gr("info",t,r),debug:gr("debug",t,r)};return en.set(t,[r,n]),n}var oe=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var Ct;class X{constructor(e,t,r){this.iterator=e,Ct.set(this,void 0),this.controller=t,w(this,Ct,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?k(r):console;async function*a(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Yn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let g;try{g=JSON.parse(d.data)}catch(b){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),b}if(g&&g.error)throw new T(void 0,g.error,void 0,e.headers);yield s?{event:d.event,data:g}:g}else{let g;try{g=JSON.parse(d.data)}catch(b){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),b}if(d.event=="error")throw new T(void 0,g.error,g.message,void 0);yield{event:d.event,data:g}}}f=!0}catch(d){if(pt(d))return;throw d}finally{if(!f)t.abort()}}return new X(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new De,f=Gr(e);for await(let d of f)for(let g of a.decode(d))yield g;for(let d of a.flush())yield d}async function*o(){if(s)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(pt(f))return;throw f}finally{if(!a)t.abort()}}return new X(o,t,r)}[(Ct=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new X(()=>s(e),this.controller,i(this,Ct,"f")),new X(()=>s(t),this.controller,i(this,Ct,"f"))]}toReadableStream(){let e=this,t;return Kr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=je(JSON.stringify(s)+`
|
|
5
|
+
`);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Yn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new _("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new _("Attempted to iterate over a response with no body")}let r=new tn,s=new De,n=Gr(e.body);for await(let o of Zn(n))for(let a of s.decode(o)){let f=r.decode(a);if(f)yield f}for(let o of s.flush()){let a=r.decode(o);if(a)yield a}}async function*Zn(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?je(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Zs(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class tn{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
|
|
6
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=eo(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function eo(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function br(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(k(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return X.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ns(u,r)}return await r.text()})();return k(e).debug(`[${s}] response parsed`,oe({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ns(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Et;class Pe extends Promise{constructor(e,t,r=br){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Et.set(this,void 0),w(this,Et,e,"f")}_thenUnwrap(e){return new Pe(i(this,Et,"f"),this.responsePromise,async(t,r)=>ns(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Et,"f"),e));return 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)}}Et=new WeakMap;var wr;class xr{constructor(e,t,r,s){wr.set(this,void 0),w(this,wr,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,wr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(wr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class Ar extends Pe{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await br(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class ie extends xr{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}}class A extends xr{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(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Vr(this.options.query),after:t}}}}class Z extends xr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Vr(this.options.query),after:e}}}}var as=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function We(e,t,r){return as(),new File(e,t??"unknown_file",r)}function vt(e){return(typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var Ir=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ae=async(e,t)=>{if(!os(e.body))return e;return{...e,body:await sn(e.body,t)}},K=async(e,t)=>({...e,body:await sn(e.body,t)}),rn=new WeakMap;function ro(e){let t=typeof e==="function"?e:e.fetch,r=rn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return rn.set(t,s),s}var sn=async(e,t)=>{if(!await ro(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,n])=>is(r,s,n))),r},nn=(e)=>e instanceof Blob&&("name"in e),so=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ir(e)||nn(e)),os=(e)=>{if(so(e))return!0;if(Array.isArray(e))return e.some(os);if(e&&typeof e==="object"){for(let t in e)if(os(e[t]))return!0}return!1},is=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,We([await r.blob()],vt(r)));else if(Ir(r))e.append(t,We([await new Response(mr(r)).blob()],vt(r)));else if(nn(r))e.append(t,r,vt(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>is(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>is(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var on=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",no=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&on(e),oo=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Pr(e,t,r){if(as(),e=await e,no(e)){if(e instanceof File)return e;return We([await e.arrayBuffer()],e.name)}if(oo(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),We(await ls(n),t,r)}let s=await ls(e);if(t||(t=vt(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return We(s,t,r)}async function ls(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(on(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ir(e))for await(let r of e)t.push(...await ls(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${io(e)}`)}return t}function io(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function ln(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var an=Object.freeze(Object.create(null)),lo=(e=ln)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((b,m,u)=>{if(/[?#]/.test(m))n=!0;let x=s[u],y=(n?encodeURIComponent:e)(""+x);if(u!==s.length&&(x==null||typeof x==="object"&&x.toString===Object.getPrototypeOf(Object.getPrototypeOf(x.hasOwnProperty??an)??an)?.toString))y=x+"",o.push({start:b.length+m.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(x).slice(8,-1)} is not a valid path parameter`});return b+m+(u===s.length?"":y)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,g;while((g=d.exec(f))!==null)o.push({start:g.index,length:g[0].length,error:`Value "${g[0]}" can't be safely passed as a path parameter`});if(o.sort((b,m)=>b.start-m.start),o.length>0){let b=0,m=o.reduce((u,x)=>{let y=" ".repeat(x.start-b),C="^".repeat(x.length);return b=x.start+x.length,u+y+C},"");throw new _(`Path parameters result in path with invalid segments:
|
|
7
|
+
${o.map((u)=>u.error).join(`
|
|
8
|
+
`)}
|
|
9
|
+
${a}
|
|
10
|
+
${m}`)}return a},l=lo(ln);class qe extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,A,{query:t,...r})}}function $t(e){return e!==void 0&&"function"in e&&e.function!==void 0}function kt(e){return e?.$brand==="auto-parseable-response-format"}function Se(e){return e?.$brand==="auto-parseable-tool"}function cn(e,t){if(!t||!cs(t))return{...e,choices:e.choices.map((r)=>(fn(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return Ot(e,t)}function Ot(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new Pt;if(s.finish_reason==="content_filter")throw new St;return fn(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>ho(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?fo(t,s.message.content):null}}});return{...e,choices:r}}function fo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function ho(e,t){let r=e.tools?.find((s)=>$t(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Se(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function un(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>$t(s)&&s.function?.name===t.function.name);return $t(r)&&(Se(r)||r?.function.strict||!1)}function cs(e){if(kt(e.response_format))return!0;return e.tools?.some((t)=>Se(t)||t.type==="function"&&t.function.strict===!0)??!1}function fn(e){for(let t of e||[])if(t.type!=="function")throw new _(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function hn(e){for(let t of e??[]){if(t.type!=="function")throw new _(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new _(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var He=(e)=>e?.role==="assistant",us=(e)=>e?.role==="tool";var fs,Sr,Rr,Tt,Ft,Cr,Nt,le,Mt,Er,vr,Je,dn;class Re{constructor(){fs.add(this),this.controller=new AbortController,Sr.set(this,void 0),Rr.set(this,()=>{}),Tt.set(this,()=>{}),Ft.set(this,void 0),Cr.set(this,()=>{}),Nt.set(this,()=>{}),le.set(this,{}),Mt.set(this,!1),Er.set(this,!1),vr.set(this,!1),Je.set(this,!1),w(this,Sr,new Promise((e,t)=>{w(this,Rr,e,"f"),w(this,Tt,t,"f")}),"f"),w(this,Ft,new Promise((e,t)=>{w(this,Cr,e,"f"),w(this,Nt,t,"f")}),"f"),i(this,Sr,"f").catch(()=>{}),i(this,Ft,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,fs,"m",dn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Rr,"f").call(this),this._emit("connect")}get ended(){return i(this,Mt,"f")}get errored(){return i(this,Er,"f")}get aborted(){return i(this,vr,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,le,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(w(this,Je,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){w(this,Je,!0,"f"),await i(this,Ft,"f")}_emit(e,...t){if(i(this,Mt,"f"))return;if(e==="end")w(this,Mt,!0,"f"),i(this,Cr,"f").call(this);let r=i(this,le,"f")[e];if(r)i(this,le,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Tt,"f").call(this,s),i(this,Nt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Tt,"f").call(this,s),i(this,Nt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Sr=new WeakMap,Rr=new WeakMap,Tt=new WeakMap,Ft=new WeakMap,Cr=new WeakMap,Nt=new WeakMap,le=new WeakMap,Mt=new WeakMap,Er=new WeakMap,vr=new WeakMap,Je=new WeakMap,fs=new WeakSet,dn=function(t){if(w(this,Er,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new N;if(t instanceof N)return w(this,vr,!0,"f"),this._emit("abort",t);if(t instanceof _)return this._emit("error",t);if(t instanceof Error){let r=new _(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new _(String(t)))};function pn(e){return typeof e.parse==="function"}var W,hs,$r,ds,ps,ms,mn,_n,po=10;class Lt extends Re{constructor(){super(...arguments);W.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(He(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new _("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,W,"m",hs).call(this)}async finalMessage(){return await this.done(),i(this,W,"m",$r).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,W,"m",ds).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,W,"m",ps).call(this)}async totalUsage(){return await this.done(),i(this,W,"m",ms).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,W,"m",$r).call(this);if(t)this._emit("finalMessage",t);let r=i(this,W,"m",hs).call(this);if(r)this._emit("finalContent",r);let s=i(this,W,"m",ds).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,W,"m",ps).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,W,"m",ms).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,W,"m",mn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ot(n,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{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=po}=r||{},g=t.tools.map((u)=>{if(Se(u)){if(!u.$callback)throw new _("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),b={};for(let u of g)if(u.type==="function")b[u.function.name||u.function.function.name]=u.function;let m="tools"in t?g.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let y=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:m,messages:[...this.messages]},r)).choices[0]?.message;if(!y)throw new _("missing message in ChatCompletion response");if(!y.tool_calls?.length)return;for(let C of y.tool_calls){if(C.type!=="function")continue;let R=C.id,{name:P,arguments:I}=C.function,O=b[P];if(!O){let E=`Invalid tool_call: ${JSON.stringify(P)}. Available options are: ${Object.keys(b).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:E});continue}else if(f&&f!==P){let E=`Invalid tool_call: ${JSON.stringify(P)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:E});continue}let v;try{v=pn(O)?await O.parse(I):I}catch(E){let D=E instanceof Error?E.message:String(E);this._addMessage({role:"tool",tool_call_id:R,content:D});continue}let q=await O.function(v,this),F=i(this,W,"m",_n).call(this,q);if(this._addMessage({role:"tool",tool_call_id:R,content:F}),f)return}}return}}W=new WeakSet,hs=function(){return i(this,W,"m",$r).call(this).content??null},$r=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(He(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new _("stream ended without producing a ChatCompletionMessage with role=assistant")},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(He(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ps=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(us(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ms=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},mn=function(t){if(t.n!=null&&t.n>1)throw new _("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_n=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Bt extends Lt{static runTools(e,t,r){let s=new Bt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),He(e)&&e.content)this._emit("content",e.content)}}var B={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class gn extends Error{}class yn extends Error{}function mo(e,t=B.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return _o(e.trim(),t)}var _o=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new gn(`${u} at position ${s}`)},o=(u)=>{throw new yn(`${u} at position ${s}`)},a=()=>{if(m(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return g();if(e.substring(s,s+4)==="null"||B.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||B.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||B.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||B.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||B.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||B.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return b()},f=()=>{let u=s,x=!1;s++;while(s<r&&(e[s]!=='"'||x&&e[s-1]==="\\"))x=e[s]==="\\"?!x:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(x)))}catch(y){o(String(y))}else if(B.STR&t)try{return JSON.parse(e.substring(u,s-Number(x))+'"')}catch(y){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,m();let u={};try{while(e[s]!=="}"){if(m(),s>=r&&B.OBJ&t)return u;let x=f();m(),s++;try{let y=a();Object.defineProperty(u,x,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(B.OBJ&t)return u;else throw y}if(m(),e[s]===",")s++}}catch(x){if(B.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},g=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),m(),e[s]===",")s++}catch(x){if(B.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},b=()=>{if(s===0){if(e==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(x){if(B.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(y){}o(String(x))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(B.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(x){if(e.substring(u,s)==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(y){o(String(y))}}},m=()=>{while(s<r&&`
|
|
11
|
+
\r `.includes(e[s]))s++};return a()},_s=(e)=>mo(e,B.ALL^B.NUM);var L,ce,Ve,de,gs,kr,ys,bs,ws,Or,xs,bn;class pe extends Lt{constructor(e){super();L.add(this),ce.set(this,void 0),Ve.set(this,void 0),de.set(this,void 0),w(this,ce,e,"f"),w(this,Ve,[],"f")}get currentChatCompletionSnapshot(){return i(this,de,"f")}static fromReadableStream(e){let t=new pe(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new pe(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;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,L,"m",gs).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)i(this,L,"m",ys).call(this,o);if(n.controller.signal?.aborted)throw new N;return this._addChatCompletion(i(this,L,"m",Or).call(this))}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}i(this,L,"m",gs).call(this),this._connected();let s=X.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,L,"m",Or).call(this));i(this,L,"m",ys).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new N;return this._addChatCompletion(i(this,L,"m",Or).call(this))}[(ce=new WeakMap,Ve=new WeakMap,de=new WeakMap,L=new WeakSet,gs=function(){if(this.ended)return;w(this,de,void 0,"f")},kr=function(t){let r=i(this,Ve,"f")[t.index];if(r)return r;return 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},i(this,Ve,"f")[t.index]=r,r},ys=function(t){if(this.ended)return;let r=i(this,L,"m",bn).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let n=r.choices[s.index];if(s.delta.content!=null&&n.message?.role==="assistant"&&n.message?.content)this._emit("content",s.delta.content,n.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:n.message.content,parsed:n.message.parsed});if(s.delta.refusal!=null&&n.message?.role==="assistant"&&n.message?.refusal)this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:n.message.refusal});if(s.logprobs?.content!=null&&n.message?.role==="assistant")this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:n.logprobs?.content??[]});if(s.logprobs?.refusal!=null&&n.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:n.logprobs?.refusal??[]});let o=i(this,L,"m",kr).call(this,n);if(n.finish_reason){if(i(this,L,"m",ws).call(this,n),o.current_tool_call_index!=null)i(this,L,"m",bs).call(this,n,o.current_tool_call_index)}for(let a of s.delta.tool_calls??[]){if(o.current_tool_call_index!==a.index){if(i(this,L,"m",ws).call(this,n),o.current_tool_call_index!=null)i(this,L,"m",bs).call(this,n,o.current_tool_call_index)}o.current_tool_call_index=a.index}for(let a of s.delta.tool_calls??[]){let f=n.message.tool_calls?.[a.index];if(!f?.type)continue;if(f?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:f.function?.name,index:a.index,arguments:f.function.arguments,parsed_arguments:f.function.parsed_arguments,arguments_delta:a.function?.arguments??""});else xn(f?.type)}}},bs=function(t,r){if(i(this,L,"m",kr).call(this,t).done_tool_calls.has(r))return;let n=t.message.tool_calls?.[r];if(!n)throw Error("no tool call snapshot");if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type==="function"){let o=i(this,ce,"f")?.tools?.find((a)=>$t(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:r,arguments:n.function.arguments,parsed_arguments:Se(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else xn(n.type)},ws=function(t){let r=i(this,L,"m",kr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,L,"m",xs).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}if(t.message.refusal&&!r.refusal_done)r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal});if(t.logprobs?.content&&!r.logprobs_content_done)r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!r.logprobs_refusal_done)r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},Or=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=i(this,de,"f");if(!t)throw new _("request ended without sending any chunks");return w(this,de,void 0,"f"),w(this,Ve,[],"f"),go(t,i(this,ce,"f"))},xs=function(){let t=i(this,ce,"f")?.response_format;if(kt(t))return t;return null},bn=function(t){var r,s,n,o;let a=i(this,de,"f"),{choices:f,...d}=t;if(!a)a=w(this,de,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:g,finish_reason:b,index:m,logprobs:u=null,...x}of t.choices){let y=a.choices[m];if(!y)y=a.choices[m]={finish_reason:b,index:m,message:{},logprobs:u,...x};if(u)if(!y.logprobs)y.logprobs=Object.assign({},u);else{let{content:q,refusal:F,...E}=u;if(wn(E),Object.assign(y.logprobs,E),q)(r=y.logprobs).content??(r.content=[]),y.logprobs.content.push(...q);if(F)(s=y.logprobs).refusal??(s.refusal=[]),y.logprobs.refusal.push(...F)}if(b){if(y.finish_reason=b,i(this,ce,"f")&&cs(i(this,ce,"f"))){if(b==="length")throw new Pt;if(b==="content_filter")throw new St}}if(Object.assign(y,x),!g)continue;let{content:C,refusal:R,function_call:P,role:I,tool_calls:O,...v}=g;if(wn(v),Object.assign(y.message,v),R)y.message.refusal=(y.message.refusal||"")+R;if(I)y.message.role=I;if(P)if(!y.message.function_call)y.message.function_call=P;else{if(P.name)y.message.function_call.name=P.name;if(P.arguments)(n=y.message.function_call).arguments??(n.arguments=""),y.message.function_call.arguments+=P.arguments}if(C){if(y.message.content=(y.message.content||"")+C,!y.message.refusal&&i(this,L,"m",xs).call(this))y.message.parsed=_s(y.message.content)}if(O){if(!y.message.tool_calls)y.message.tool_calls=[];for(let{index:q,id:F,type:E,function:D,...se}of O){let S=(o=y.message.tool_calls)[q]??(o[q]={});if(Object.assign(S,se),F)S.id=F;if(E)S.type=E;if(D)S.function??(S.function={name:D.name??"",arguments:""});if(D?.name)S.function.name=D.name;if(D?.arguments){if(S.function.arguments+=D.arguments,un(i(this,ce,"f"),S))S.function.parsed_arguments=_s(S.function.arguments)}}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",(s)=>{let n=t.shift();if(n)n.resolve(s);else 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 n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function go(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:g,finish_reason:b,index:m,logprobs:u,...x})=>{if(!b)throw new _(`missing finish_reason for choice ${m}`);let{content:y=null,function_call:C,tool_calls:R,...P}=g,I=g.role;if(!I)throw new _(`missing role for choice ${m}`);if(C){let{arguments:O,name:v}=C;if(O==null)throw new _(`missing function_call.arguments for choice ${m}`);if(!v)throw new _(`missing function_call.name for choice ${m}`);return{...x,message:{content:y,function_call:{arguments:O,name:v},role:I,refusal:g.refusal??null},finish_reason:b,index:m,logprobs:u}}if(R)return{...x,index:m,finish_reason:b,logprobs:u,message:{...P,role:I,content:y,refusal:g.refusal??null,tool_calls:R.map((O,v)=>{let{function:q,type:F,id:E,...D}=O,{arguments:se,name:S,...fe}=q||{};if(E==null)throw new _(`missing choices[${m}].tool_calls[${v}].id
|
|
12
|
+
${Tr(e)}`);if(F==null)throw new _(`missing choices[${m}].tool_calls[${v}].type
|
|
13
|
+
${Tr(e)}`);if(S==null)throw new _(`missing choices[${m}].tool_calls[${v}].function.name
|
|
14
|
+
${Tr(e)}`);if(se==null)throw new _(`missing choices[${m}].tool_calls[${v}].function.arguments
|
|
15
|
+
${Tr(e)}`);return{...D,id:E,type:F,function:{...fe,name:S,arguments:se}}})}};return{...x,message:{...P,content:y,role:I,refusal:g.refusal??null},finish_reason:b,index:m,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return cn(d,t)}function Tr(e){return JSON.stringify(e)}function wn(e){return}function xn(e){}class Ke extends pe{static fromReadableStream(e){let t=new Ke(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Ke(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class me extends c{constructor(){super(...arguments);this.messages=new qe(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(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return hn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>Ot(r,e))}runTools(e,t){if(e.stream)return Ke.runTools(this._client,e,t);return Bt.runTools(this._client,e,t)}stream(e,t){return pe.createChatCompletion(this._client,e,t)}}me.Messages=qe;class Ce extends c{constructor(){super(...arguments);this.completions=new me(this._client)}}Ce.Completions=me;var An=Symbol("brand.privateNullableHeaders");function*bo(e){if(!e)return;if(An in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Xr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Xr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of bo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[An]:!0,values:t,nulls:r}};class Ut extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class jt extends c{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Dt extends c{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}}class ue extends c{constructor(){super(...arguments);this.transcriptions=new jt(this._client),this.translations=new Dt(this._client),this.speech=new Ut(this._client)}}ue.Transcriptions=jt;ue.Translations=Dt;ue.Speech=Ut;class Ge extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",A,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Wt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",A,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ht extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new qt(this._client),this.transcriptionSessions=new Ht(this._client)}}Ee.Sessions=qt;Ee.TranscriptionSessions=Ht;class Jt extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Xt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Z,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Z,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class ve extends c{constructor(){super(...arguments);this.sessions=new Jt(this._client),this.threads=new Xt(this._client)}}ve.Sessions=Jt;ve.Threads=Xt;class Vt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,A,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Kt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,A,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var In=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var G=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim();return};var U,ke,As,ee,Fr,z,Oe,ze,$e,Lr,V,Nr,Mr,Qt,Gt,zt,Pn,Sn,Rn,Cn,En,vn,$n;class _e extends Re{constructor(){super(...arguments);U.add(this),As.set(this,[]),ee.set(this,{}),Fr.set(this,{}),z.set(this,void 0),Oe.set(this,void 0),ze.set(this,void 0),$e.set(this,void 0),Lr.set(this,void 0),V.set(this,void 0),Nr.set(this,void 0),Mr.set(this,void 0),Qt.set(this,void 0)}[(As=new WeakMap,ee=new WeakMap,Fr=new WeakMap,z=new WeakMap,Oe=new WeakMap,ze=new WeakMap,$e=new WeakMap,Lr=new WeakMap,V=new WeakMap,Nr=new WeakMap,Mr=new WeakMap,Qt=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else 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 n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new ke;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=X.fromReadableStream(e,this.controller);for await(let n of s)i(this,U,"m",Gt).call(this,n);if(s.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Gt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}static createThreadAssistantStream(e,t,r){let s=new ke;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Nr,"f")}currentRun(){return i(this,Mr,"f")}currentMessageSnapshot(){return i(this,z,"f")}currentRunStepSnapshot(){return i(this,Qt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,ee,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Fr,"f"))}async finalRun(){if(await this.done(),!i(this,Oe,"f"))throw Error("Final run was not received.");return i(this,Oe,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,U,"m",Gt).call(this,a);if(o.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Gt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Ue(n)&&Ue(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Ue(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}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)}}ke=_e,Gt=function(t){if(this.ended)return;switch(w(this,Nr,t,"f"),i(this,U,"m",Rn).call(this,t),t.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":i(this,U,"m",$n).call(this,t);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":i(this,U,"m",Sn).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,U,"m",Pn).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:Oo(t)}},zt=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");if(!i(this,Oe,"f"))throw Error("Final run has not been received");return i(this,Oe,"f")},Pn=function(t){let[r,s]=i(this,U,"m",En).call(this,t,i(this,z,"f"));w(this,z,r,"f"),i(this,Fr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,ze,"f")){if(i(this,$e,"f"))switch(i(this,$e,"f").type){case"text":this._emit("textDone",i(this,$e,"f").text,i(this,z,"f"));break;case"image_file":this._emit("imageFileDone",i(this,$e,"f").image_file,i(this,z,"f"));break}w(this,ze,n.index,"f")}w(this,$e,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,ze,"f")!==void 0){let n=t.data.content[i(this,ze,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,z,"f"));break;case"text":this._emit("textDone",n.text,i(this,z,"f"));break}}if(i(this,z,"f"))this._emit("messageDone",t.data);w(this,z,void 0,"f")}},Sn=function(t){let r=i(this,U,"m",Cn).call(this,t);switch(w(this,Qt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Lr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f"));if(w(this,Lr,o.index,"f"),w(this,V,r.step_details.tool_calls[o.index],"f"),i(this,V,"f"))this._emit("toolCallCreated",i(this,V,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(w(this,Qt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),w(this,V,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Rn=function(t){i(this,As,"f").push(t),this._emit("event",t)},Cn=function(t){switch(t.event){case"thread.run.step.created":return i(this,ee,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,ee,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=ke.accumulateDelta(r,s.delta);i(this,ee,"f")[t.data.id]=n}return i(this,ee,"f")[t.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":i(this,ee,"f")[t.data.id]=t.data;break}if(i(this,ee,"f")[t.data.id])return i(this,ee,"f")[t.data.id];throw Error("No snapshot available")},En=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,U,"m",vn).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},vn=function(t,r){return ke.accumulateDelta(r,t)},$n=function(t){switch(w(this,Mr,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(w(this,Oe,t.data,"f"),i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),w(this,V,void 0,"f");break;case"thread.run.cancelling":break}};function Oo(e){}class Qe extends c{constructor(){super(...arguments);this.steps=new Kt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,A,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"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 _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}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 _e.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}Qe.Steps=Kt;class Te extends c{constructor(){super(...arguments);this.runs=new Qe(this._client),this.messages=new Vt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}}Te.Runs=Qe;Te.Messages=Vt;class te extends c{constructor(){super(...arguments);this.realtime=new Ee(this._client),this.chatkit=new ve(this._client),this.assistants=new Wt(this._client),this.threads=new Te(this._client)}}te.Realtime=Ee;te.ChatKit=ve;te.Assistants=Wt;te.Threads=Te;class Ye extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Yt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Ze extends c{constructor(){super(...arguments);this.content=new Yt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,A,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Ze.Content=Yt;class Fe extends c{constructor(){super(...arguments);this.files=new Ze(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Fe.Files=Ze;class Zt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Z,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Ne extends c{constructor(){super(...arguments);this.items=new Zt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Ne.Items=Zt;class et extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)k(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return k(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=In(f)});return o})}}class er extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,A,{query:n,...r})}}class tt extends c{constructor(){super(...arguments);this.outputItems=new er(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,A,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}tt.OutputItems=er;class Me extends c{constructor(){super(...arguments);this.runs=new tt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Me.Runs=tt;class rt extends c{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await Q(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ie({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class tr extends c{}class rr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class st extends c{constructor(){super(...arguments);this.graders=new rr(this._client)}}st.Graders=rr;class sr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,ie,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Z,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class nt extends c{constructor(){super(...arguments);this.permissions=new sr(this._client)}}nt.Permissions=sr;class nr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,A,{query:t,...r})}}class ot extends c{constructor(){super(...arguments);this.checkpoints=new nr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",A,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,A,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}ot.Checkpoints=nr;class re extends c{constructor(){super(...arguments);this.methods=new tr(this._client),this.jobs=new ot(this._client),this.checkpoints=new nt(this._client),this.alpha=new st(this._client)}}re.Methods=tr;re.Jobs=ot;re.Checkpoints=nt;re.Alpha=st;class or extends c{}class Le extends c{constructor(){super(...arguments);this.graderModels=new or(this._client)}}Le.GraderModels=or;class it extends c{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})}}class at extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ie,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class lt extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class ir extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ar extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class ge extends c{constructor(){super(...arguments);this.clientSecrets=new ar(this._client),this.calls=new ir(this._client)}}ge.ClientSecrets=ar;ge.Calls=ir;function kn(e,t){if(!t||!Qo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return Is(e,t)}function Is(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:ei(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:zo(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Br(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function zo(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function Qo(e){if(kt(e.text?.format))return!0;return!1}function Yo(e){return e?.$brand==="auto-parseable-tool"}function Zo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function ei(e,t){let r=Zo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Yo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Br(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var ct,Ur,ye,jr,On,Tn,Fn,Nn;class Dr extends Re{constructor(e){super();ct.add(this),Ur.set(this,void 0),ye.set(this,void 0),jr.set(this,void 0),w(this,Ur,e,"f")}static createResponse(e,t,r){let s=new Dr(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;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,ct,"m",On).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,ct,"m",Tn).call(this,a,o);if(n.controller.signal?.aborted)throw new N;return i(this,ct,"m",Fn).call(this)}[(Ur=new WeakMap,ye=new WeakMap,jr=new WeakMap,ct=new WeakSet,On=function(){if(this.ended)return;w(this,ye,void 0,"f")},Tn=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,ct,"m",Nn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new _(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new _(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new _(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new _(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Fn=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=i(this,ye,"f");if(!t)throw new _("request ended without sending any events");w(this,ye,void 0,"f");let r=ti(t,i(this,Ur,"f"));return w(this,jr,r,"f"),r},Nn=function(t){let r=i(this,ye,"f");if(!r){if(t.type!=="response.created")throw new _(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=w(this,ye,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 _(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new _(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new _(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new _(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new _(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new _(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new _(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{w(this,ye,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else 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 n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,jr,"f");if(!e)throw new _("stream ended without producing a ChatCompletion");return e}}function ti(e,t){return kn(e,t)}class lr extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,A,{query:t,...r})}}class cr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class be extends c{constructor(){super(...arguments);this.inputItems=new lr(this._client),this.inputTokens=new cr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Br(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Br(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>Is(r,e))}stream(e,t){return Dr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}be.InputItems=lr;be.InputTokens=cr;class ur extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class fr extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class ut extends c{constructor(){super(...arguments);this.content=new fr(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,A,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ut.Content=fr;class we extends c{constructor(){super(...arguments);this.content=new ur(this._client),this.versions=new ut(this._client)}create(e={},t){return this._client.post("/skills",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}we.Content=ur;we.Versions=ut;class hr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,K({body:t,...r},this._client))}}class Be extends c{constructor(){super(...arguments);this.parts=new hr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Be.Parts=hr;var Mn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"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,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,A,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function g(m){for(let u of m){let x=await a.files.create({file:u,purpose:"assistants"},s);d.push(x.id)}}let b=Array(o).fill(f).map(g);return await Mn(b),await this.createAndPoll(e,{file_ids:d})}}class pr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,A,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"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=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"failed":case"completed":return o}}}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(l`/vector_stores/${s}/files/${e}/content`,ie,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class xe extends c{constructor(){super(...arguments);this.files=new pr(this._client),this.fileBatches=new dr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",A,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,ie,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}xe.Files=pr;xe.FileBatches=dr;class ft extends c{create(e,t){return this._client.post("/videos",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Z,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ae({body:t,...r},this._client))}}var ht,Ln,Wr;class dt extends c{constructor(){super(...arguments);ht.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 Error("Webhook signature verification is only supported when the `crypto` global is defined");i(this,ht,"m",Ln).call(this,r);let n=h([t]).values,o=i(this,ht,"m",Wr).call(this,n,"webhook-signature"),a=i(this,ht,"m",Wr).call(this,n,"webhook-timestamp"),f=i(this,ht,"m",Wr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new ne("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1000);if(g-d>s)throw new ne("Webhook timestamp is too old");if(d>g+s)throw new ne("Webhook timestamp is too new");let b=o.split(" ").map((y)=>y.startsWith("v1,")?y.substring(3):y),m=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,x=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let y of b)try{let C=Buffer.from(y,"base64");if(await crypto.subtle.verify("HMAC",x,C,new TextEncoder().encode(u)))return}catch{continue}throw new ne("The given webhook signature does not match the expected signature")}}ht=new WeakSet,Ln=function(t){if(typeof t!=="string"||t.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Wr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Ps,Ss,qr,Bn;class p{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("OPENAI_API_KEY"),organization:r=G("OPENAI_ORG_ID")??null,project:s=G("OPENAI_PROJECT_ID")??null,webhookSecret:n=G("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Ps.add(this),qr.set(this,void 0),this.completions=new Ye(this),this.chat=new Ce(this),this.embeddings=new et(this),this.files=new rt(this),this.images=new it(this),this.audio=new ue(this),this.moderations=new lt(this),this.models=new at(this),this.fineTuning=new re(this),this.graders=new Le(this),this.vectorStores=new xe(this),this.webhooks=new dt(this),this.beta=new te(this),this.batches=new Ge(this),this.uploads=new Be(this),this.responses=new be(this),this.realtime=new ge(this),this.conversations=new Ne(this),this.evals=new Me(this),this.containers=new Fe(this),this.skills=new we(this),this.videos=new ft(this),t===void 0)throw new _("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ms())throw new _(`It looks like you're running in a browser-like environment.
|
|
16
|
+
|
|
17
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
18
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
19
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
20
|
+
|
|
21
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
22
|
+
|
|
23
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
24
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Ss.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=ss(a.logLevel,"ClientOptions.logLevel",this)??ss(G("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Bs(),w(this,qr,js,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}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}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Gs(e)}getUserAgent(){return`${this.constructor.name}/JS ${he}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jr()}`}makeStatusError(e,t,r,s){return T.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof _)throw r;throw new _(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new _(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Ps,"m",Bn).call(this)&&r||this.baseURL,n=Es(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!vs(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Pe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,b=Date.now();if(k(this).debug(`[${d}] sending request`,oe({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new N;let m=new AbortController,u=await this.fetchWithTimeout(a,o,f,m).catch(mt),x=Date.now();if(u instanceof globalThis.Error){let R=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new N;let P=pt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return k(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${R}`),k(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${R})`,oe({retryOfRequestLogID:r,url:a,durationMs:x-b,message:u.message})),this.retryRequest(s,t,r??d);if(k(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),k(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,oe({retryOfRequestLogID:r,url:a,durationMs:x-b,message:u.message})),P)throw new Ie;throw new Ae({cause:u})}let y=[...u.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,P])=>", "+R+": "+JSON.stringify(P)).join(""),C=`[${d}${g}${y}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${x-b}ms`;if(!u.ok){let R=await this.shouldRetry(u);if(t&&R){let F=`retrying, ${t} attempts remaining`;return await Us(u.body),k(this).info(`${C} - ${F}`),k(this).debug(`[${d}] response error (${F})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:x-b})),this.retryRequest(s,t,r??d,u.headers)}let P=R?"error; no more retries left":"error; not retryable";k(this).info(`${C} - ${P}`);let I=await u.text().catch((F)=>mt(F).message),O=Os(I),v=O?void 0:I;throw k(this).debug(`[${d}] response error (${P})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:v,durationMs:Date.now()-b})),this.makeStatusError(u.status,O,v,u.headers)}return k(this).info(C),k(this).debug(`[${d}] response start`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:x-b})),{response:u,options:s,controller:m,requestLogID:d,retryOfRequestLogID:r,startTime:b}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Ar(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),g=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,b={signal:s.signal,...g?{duplex:"half"}:{},method:"GET",...a};if(o)b.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,b)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Q(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)ks("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:g}=this.buildBody({options:r}),b=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:b,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ls(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:mr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,qr,"f").call(this,{body:e,headers:r})}}Ss=p,qr=new WeakMap,Ps=new WeakSet,Bn=function(){return this.baseURL!=="https://api.openai.com/v1"};p.OpenAI=Ss;p.DEFAULT_TIMEOUT=600000;p.OpenAIError=_;p.APIError=T;p.APIConnectionError=Ae;p.APIConnectionTimeoutError=Ie;p.APIUserAbortError=N;p.NotFoundError=bt;p.ConflictError=wt;p.RateLimitError=At;p.BadRequestError=_t;p.AuthenticationError=gt;p.InternalServerError=It;p.PermissionDeniedError=yt;p.UnprocessableEntityError=xt;p.InvalidWebhookSignatureError=ne;p.toFile=Pr;p.Completions=Ye;p.Chat=Ce;p.Embeddings=et;p.Files=rt;p.Images=it;p.Audio=ue;p.Moderations=lt;p.Models=at;p.FineTuning=re;p.Graders=Le;p.VectorStores=xe;p.Webhooks=dt;p.Beta=te;p.Batches=Ge;p.Uploads=Be;p.Responses=be;p.Realtime=ge;p.Conversations=Ne;p.Evals=Me;p.Containers=Fe;p.Skills=we;p.Videos=ft;class Xe extends p{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("AZURE_OPENAI_API_KEY"),apiVersion:r=G("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new _("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o==="function")a=!0;if(!o&&!t)throw new _("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new _("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new _("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new _("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(fi.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Ue(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var fi=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{p,Xe};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function Z(i){let t=3735928559,h=1103547991;for(let e=0;e<i.length;e++){let l=i.charCodeAt(e);t=Math.imul(t^l,2654435761),h=Math.imul(h^l,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(h^h>>>13,3266489909),h=Math.imul(h^h>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(h>>>0).toString(36)+(t>>>0).toString(36)}
|
|
3
|
+
export{Z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Xe}from"./chunk-c8vf5ezv.js";import{f}from"./chunk-phjnj6x5.js";import"./chunk-2mj5h53m.js";import{m,b}from"./shumai-agent-app.js";import{K,q,ee}from"./chunk-115gx56y.js";import{V}from"./chunk-7z62cgr7.js";import{P}from"./chunk-avm8xsd8.js";import{U,R}from"./chunk-7hkzk9pe.js";import{v,y}from"./chunk-dpd0zpsp.js";import{x}from"./chunk-p7sczpks.js";var E="v1",h=new Set(["openai","openai-codex","opencode","azure-openai-responses"]),g=16;function _(r){let a=new Map;if(!r)return a;for(let e of r.split(",")){let n=e.trim();if(!n)continue;let[s,t]=n.split("=",2);if(!s||!t)continue;a.set(s.trim(),t.trim())}return a}function I(r,a){if(a?.azureDeploymentName)return a.azureDeploymentName;return _(f("AZURE_OPENAI_DEPLOYMENT_NAME_MAP",a?.env)).get(r.id)||r.id}function O(r){return R(U(r),"Azure OpenAI API error")}var w=(r,a,e)=>{let n=new m;return(async()=>{let s=I(r,e),t={role:"assistant",content:[],api:"azure-openai-responses",provider:r.provider,model:r.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=e?.apiKey;if(!o)throw Error(`No API key for provider: ${r.provider}`);let i=M(r,o,e),u=v(a.tools,r.compat?.supportsOpenAIGrammarTools??!1),p=T(r,a,e,s,u),c=await e?.onPayload?.(p,r);if(c!==void 0)p=c;let d={...e?.signal?{signal:e.signal}:{},...e?.timeoutMs!==void 0?{timeout:e.timeoutMs}:{},maxRetries:0},{data:A,response:l}=await P(()=>i.responses.create(p,d).withResponse(),{maxRetries:e?.maxRetries,maxRetryDelayMs:e?.maxRetryDelayMs,signal:e?.signal});if(await e?.onResponse?.({status:l.status,headers:x(l.headers)},r),n.push({type:"start",partial:t}),await ee(A,t,n,r,{grammarToolInputProperties:u}),e?.signal?.aborted)throw Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw Error("An unknown error occurred");n.push({type:"done",reason:t.stopReason,message:t}),n.end()}catch(o){for(let i of t.content)delete i.index,delete i.partialJson,delete i.customInput;t.stopReason=e?.signal?.aborted?"aborted":"error",t.errorMessage=O(o),n.push({type:"error",reason:t.stopReason,error:t}),n.end()}})(),n},J=(r,a,e)=>{let n=e?.apiKey;if(!n)throw Error(`No API key for provider: ${r.provider}`);let s=y(r,a,e,n),t=e?.reasoning?b(r,e.reasoning):void 0;return w(r,a,{...s,reasoningEffort:t==="off"?void 0:t})};function N(r){let a=r.trim().replace(/\/+$/,""),e;try{e=new URL(a)}catch{throw Error(`Invalid Azure OpenAI base URL: ${r}`)}let n=e.hostname.endsWith(".openai.azure.com")||e.hostname.endsWith(".cognitiveservices.azure.com")||e.hostname.endsWith(".ai.azure.com"),s=e.pathname.replace(/\/+$/,"");if(n&&(s===""||s==="/"||s==="/openai"||s==="/openai/v1/responses"))e.pathname="/openai/v1",e.search="";return e.toString().replace(/\/+$/,"")}function z(r){return`https://${r}.openai.azure.com/openai/v1`}function S(r,a){let e=a?.azureApiVersion||f("AZURE_OPENAI_API_VERSION",a?.env)||E,n=a?.azureBaseUrl?.trim()||f("AZURE_OPENAI_BASE_URL",a?.env)?.trim()||void 0,s=a?.azureResourceName||f("AZURE_OPENAI_RESOURCE_NAME",a?.env),t=n;if(!t&&s)t=z(s);if(!t&&r.baseUrl)t=r.baseUrl;if(!t)throw Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:N(t),apiVersion:e}}function M(r,a,e){let n={...r.headers};if(e?.headers)Object.assign(n,e.headers);let{baseUrl:s,apiVersion:t}=S(r,e);return new Xe({apiKey:a,apiVersion:t,dangerouslyAllowBrowser:!0,defaultHeaders:n,baseURL:s})}function T(r,a,e,n,s=v(a.tools,r.compat?.supportsOpenAIGrammarTools??!1)){let t=K(r,a,h,{grammarToolInputProperties:s}),o={model:n,input:t,stream:!0,prompt_cache_key:V(e?.sessionId),store:!1};if(e?.maxTokens)o.max_output_tokens=Math.max(e.maxTokens,g);if(e?.temperature!==void 0)o.temperature=e?.temperature;if(a.tools&&a.tools.length>0)o.tools=q(a.tools,{supportsStrictMode:r.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:r.compat?.supportsOpenAIGrammarTools??!1});if(r.reasoning){if(e?.reasoningEffort||e?.reasoningSummary){let i=e?.reasoningEffort?r.thinkingLevelMap?.[e.reasoningEffort]??e.reasoningEffort:"medium";o.reasoning={effort:i,summary:e?.reasoningSummary||"auto"},o.include=["reasoning.encrypted_content"]}else if(r.thinkingLevelMap?.off!==null)o.reasoning={effort:r.thinkingLevelMap?.off??"none"}}return o}export{w as stream,J as streamSimple};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function u(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}function Me(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function Oe(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let o=t.slice(e.input.length);if(!r&&o.length===0)return;let i="";if(!e.started)i+=`{${JSON.stringify(n)}:"`,e.started=!0;if(i+=JSON.stringify(o).slice(1,-1),e.input=t,r)i+='"}',e.closed=!0;return i}function P(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function w(e,n){let t=e.constrainedSampling;if(!t||t.type!=="json_schema")return;if(n)return!0;if(t.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Ie(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,o=t.variants.openai_regex,i=typeof r==="string"&&r.trim().length>0,m=typeof o==="string"&&o.trim().length>0;if(!i&&!m)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:i?"lark":"regex",definition:i?r:o,inputProperty:P(e)}}catch(c){let p=c instanceof Error?c.message:String(c);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${p}.`)}}function v(e,n){let t=new Map;for(let r of e??[]){let o=Ie(r,n);if(o)t.set(r.name,o.inputProperty)}return t}function k(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function _(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function F(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:4800;return n}function A(e){return Math.ceil(e.length/4)}function E(e){return Math.ceil(F(e)/4)}function M(e){let n=0;if(e.role==="user")return E(e.content);if(e.role==="toolResult")return E(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+_(t.arguments).length;return Math.ceil(n/4)}function G(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let o=e[r];if(o.role==="assistant"){let i=o;if(i.timestamp>=n&&i.stopReason!=="aborted"&&i.stopReason!=="error"&&k(i.usage)>0)t={usage:i.usage,index:r}}n=Math.max(n,o.timestamp)}return t}function R(e){let n=G(e);if(n){let r=k(n.usage),o=0;for(let i=n.index+1;i<e.length;i++)o+=M(e[i]);return{tokens:r+o,usageTokens:r,trailingTokens:o,lastUsageIndex:n.index}}let t=0;for(let r of e)t+=M(r);return{tokens:t,usageTokens:0,trailingTokens:t,lastUsageIndex:null}}function S(e){if(!e||e.length===0)return 0;return A(_(e))}function L(e){return Array.isArray(e)}function C(e){if(L(e))return R(e);let n=R(e.messages);if(n.lastUsageIndex!==null){let r=new Set(e.messages.slice(n.lastUsageIndex+1).filter((i)=>i.role==="toolResult").flatMap((i)=>i.addedToolNames??[])),o=S(e.tools?.filter((i)=>r.has(i.name)));return{tokens:n.tokens+o,usageTokens:n.usageTokens,trailingTokens:n.trailingTokens+o,lastUsageIndex:n.lastUsageIndex}}let t=(e.systemPrompt?A(e.systemPrompt):0)+S(e.tools);return{tokens:n.tokens+t,usageTokens:n.usageTokens,trailingTokens:n.trailingTokens+t,lastUsageIndex:n.lastUsageIndex}}var U=4096,O=1;function nt(e,n,t){if(e.contextWindow<=0)return Math.max(O,t);let r=e.contextWindow-C(n).tokens-U;return Math.min(t,Math.max(O,r))}function y(e,n,t,r){return{temperature:t?.temperature,maxTokens:nt(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,apiKey:r||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}function q(e){return e==="xhigh"||e==="max"?"high":e}function lt(e,n,t,r){let i={...{minimal:1024,low:2048,medium:8192,high:16384},...r},m=1024,c=q(t),p=i[c],d=e===void 0?n:Math.min(e+p,n);if(d<=p)p=Math.max(0,d-1024);return{maxTokens:d,thinkingBudget:p}}function D(e,n){let t=[],r=!1;for(let o of e){if(o.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(o),r=o.text===n}return t}function H(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:D(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:D(t.content,"(tool image omitted: model does not support images)")};return t})}function N(e,n,t){let r=new Map,o=e.map((a)=>a.content==null?{...a,content:[]}:a),m=H(o,n).map((a)=>{if(a.role==="user")return a;if(a.role==="toolResult"){let s=r.get(a.toolCallId);if(s&&s!==a.toolCallId)return{...a,toolCallId:s};return a}if(a.role==="assistant"){let s=a,f=s.provider===n.provider&&s.api===n.api&&s.model===n.id,T=s.content.flatMap((l)=>{if(l.type==="thinking"){if(l.redacted)return f?l:[];if(f&&l.thinkingSignature)return l;if(!l.thinking||l.thinking.trim()==="")return[];if(f)return l;return{type:"text",text:l.thinking}}if(l.type==="text"){if(f)return l;return{type:"text",text:l.text}}if(l.type==="toolCall"){let g=l,h=g;if(!f&&g.thoughtSignature)h={...g},delete h.thoughtSignature;if(!f&&t){let I=t(g.id,n,s);if(I!==g.id)r.set(g.id,I),h={...h,id:I}}return h}return l});return{...s,content:T}}return a}),c=[],p=[],d=new Set,x=()=>{if(p.length>0){for(let a of p)if(!d.has(a.id))c.push({role:"toolResult",toolCallId:a.id,toolName:a.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});p=[],d=new Set}};for(let a=0;a<m.length;a++){let s=m[a];if(s.role==="assistant"){x();let f=s;if(f.stopReason==="error"||f.stopReason==="aborted")continue;let T=f.content.filter((l)=>l.type==="toolCall");if(T.length>0)p=T,d=new Set;c.push(s)}else if(s.role==="toolResult")d.add(s.toolCallId),c.push(s);else if(s.role==="user")x(),c.push(s);else c.push(s)}return x(),c}
|
|
3
|
+
export{u,Me,Oe,w,Ie,v,nt,y,lt,N};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{c,Q,I,S,T}from"./shumai-agent-app.js";var n=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},s=class{#e;#t=new o;#r;#a;constructor(e){this.#e={...e}}async init(){if(this.#r=this.#e.database,this.#a=new i(this.#r),this.#e.onCreateConnection)await this.#e.onCreateConnection(this.#a)}async acquireConnection(){return await this.#t.lock(),this.#a}async beginTransaction(e){await e.executeQuery(I.raw("begin"))}async commitTransaction(e){await e.executeQuery(I.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(I.raw("rollback"))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#r?.close()}},i=class{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:r,parameters:a}=e,t=this.#e.prepare(r).all(...a);return Promise.resolve({rows:t})}async*streamQuery(){throw Error("Streaming query is not supported by SQLite driver.")}},o=class{#e;#t;async lock(){while(this.#e!==void 0)await this.#e;this.#e=new Promise((e)=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},l=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){let r=this.#e.selectFrom("sqlite_schema").where("type","=","table").where("name","not like","sqlite_%").select("name").$castTo();if(!e.withInternalKyselyTables)r=r.where("name","!=",S).where("name","!=",T);let a=await r.execute();return Promise.all(a.map(({name:t})=>this.#t(t)))}async getMetadata(e){return{tables:await this.getTables(e)}}async#t(e){let r=this.#e,a=(await r.selectFrom("sqlite_master").where("name","=",e).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((t)=>t.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g,"");return{name:e,columns:(await r.selectFrom(c`pragma_table_info(${e})`.as("table_info")).select(["name","type","notnull","dflt_value"]).execute()).map((t)=>({name:t.name,dataType:t.type,isNullable:!t.notnull,isAutoIncrementing:t.name===a,hasDefaultValue:t.dflt_value!=null})),isView:!0}}},u=class extends Q{getCurrentParameterPlaceholder(){return"?"}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}},h=class{#e;constructor(e){this.#e={...e}}createDriver(){return new s(this.#e)}createQueryCompiler(){return new u}createAdapter(){return new n}createIntrospector(e){return new l(e)}};export{h as NodeSqliteDialect};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{pe,we,Ae,Ne,Ge,ke,De,Le}from"./chunk-3dr4h1df.js";import{m,_,b}from"./shumai-agent-app.js";import{U,R}from"./chunk-7hkzk9pe.js";import{u,y}from"./chunk-dpd0zpsp.js";import{le}from"./chunk-p7sczpks.js";var S=0,C=(e,a,n)=>{let i=new m;return(async()=>{let t={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let g=n?.apiKey;if(!g)throw Error(`No API key for provider: ${e.provider}`);let s=L(e,g,n?.headers),c=G(e,a,n),p=await n?.onPayload?.(c,e);if(p!==void 0)c=p;let v=await s.models.generateContentStream(c);i.push({type:"start",partial:t});let o=null,w=t.content,l=()=>w.length-1;for await(let d of v){t.responseId||=d.responseId;let f=d.candidates?.[0];if(f?.content?.parts)for(let r of f.content.parts){if(r.text!==void 0){let h=we(r);if(!o||h&&o.type!=="thinking"||!h&&o.type!=="text"){if(o)if(o.type==="text")i.push({type:"text_end",contentIndex:w.length-1,content:o.text,partial:t});else i.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t});if(h)o={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(o),i.push({type:"thinking_start",contentIndex:l(),partial:t});else o={type:"text",text:""},t.content.push(o),i.push({type:"text_start",contentIndex:l(),partial:t})}if(o.type==="thinking")o.thinking+=r.text,o.thinkingSignature=Ae(o.thinkingSignature,r.thoughtSignature),i.push({type:"thinking_delta",contentIndex:l(),delta:r.text,partial:t});else o.text+=r.text,o.textSignature=Ae(o.textSignature,r.thoughtSignature),i.push({type:"text_delta",contentIndex:l(),delta:r.text,partial:t})}if(r.functionCall){if(o){if(o.type==="text")i.push({type:"text_end",contentIndex:l(),content:o.text,partial:t});else i.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t});o=null}let h=r.functionCall.id,k={type:"toolCall",id:!h||t.content.some((M)=>M.type==="toolCall"&&M.id===h)?`${r.functionCall.name}_${Date.now()}_${++S}`:h,name:r.functionCall.name||"",arguments:r.functionCall.args??{},...r.thoughtSignature&&{thoughtSignature:r.thoughtSignature}};t.content.push(k),i.push({type:"toolcall_start",contentIndex:l(),partial:t}),i.push({type:"toolcall_delta",contentIndex:l(),delta:JSON.stringify(k.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:l(),toolCall:k,partial:t})}}if(f?.finishReason){if(t.stopReason=Le(f.finishReason),t.content.some((r)=>r.type==="toolCall"))t.stopReason="toolUse"}if(d.usageMetadata)t.usage={input:(d.usageMetadata.promptTokenCount||0)-(d.usageMetadata.cachedContentTokenCount||0),output:(d.usageMetadata.candidatesTokenCount||0)+(d.usageMetadata.thoughtsTokenCount||0),cacheRead:d.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:d.usageMetadata.thoughtsTokenCount||0,totalTokens:d.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},_(e,t.usage)}if(o)if(o.type==="text")i.push({type:"text_end",contentIndex:l(),content:o.text,partial:t});else i.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t});if(n?.signal?.aborted)throw Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw Error("An unknown error occurred");i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(g){for(let s of t.content)if("index"in s)delete s.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=R(U(g)),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},F=(e,a,n)=>{let i=n?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let t=y(e,a,n,i);if(!n?.reasoning)return C(e,a,{...t,thinking:{enabled:!1}});let g=b(e,n.reasoning),s=g==="off"?"high":g,c=e;if(x(c)||T(c)||I(c))return C(e,a,{...t,thinking:{enabled:!0,level:O(s,c)}});return C(e,a,{...t,thinking:{enabled:!0,budgetTokens:A(c,s,n.thinkingBudgets)}})};function L(e,a,n){let i={};if(e.baseUrl)i.baseUrl=e.baseUrl,i.apiVersion="";let t=le({...e.headers,...n});if(t)i.headers=t;return new pe({apiKey:a,httpOptions:Object.keys(i).length>0?i:void 0})}function G(e,a,n={}){let i=Ne(e,a),t={};if(n.temperature!==void 0)t.temperature=n.temperature;if(n.maxTokens!==void 0)t.maxOutputTokens=n.maxTokens;let g=a.tools?.length?De(a.tools,n.toolChoice,ke(e.id)):void 0,s={...Object.keys(t).length>0&&t,...a.systemPrompt&&{systemInstruction:u(a.systemPrompt)},...a.tools&&a.tools.length>0&&{tools:Ge(a.tools)},...g!==void 0&&{toolConfig:{functionCallingConfig:{mode:g}}}};if(n.thinking?.enabled&&e.reasoning){let p={includeThoughts:!0};if(n.thinking.level!==void 0)p.thinkingLevel=n.thinking.level;else if(n.thinking.budgetTokens!==void 0)p.thinkingBudget=n.thinking.budgetTokens;s.thinkingConfig=p}else if(e.reasoning&&n.thinking&&!n.thinking.enabled)s.thinkingConfig=P(e);if(n.signal){if(n.signal.aborted)throw Error("Request aborted");s.abortSignal=n.signal}return{model:e.id,contents:i,config:s}}function I(e){return/gemma-?4/.test(e.id.toLowerCase())}function x(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function T(e){let a=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(a)||a==="gemini-flash-latest"||a==="gemini-flash-lite-latest"}function P(e){if(x(e))return{thinkingLevel:"LOW"};if(T(e))return{thinkingLevel:"MINIMAL"};if(I(e))return{thinkingLevel:"MINIMAL"};return{thinkingBudget:0}}function O(e,a){if(x(a))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(I(a))switch(e){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function A(e,a,n){if(n?.[a]!==void 0)return n[a];if(e.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[a];if(e.id.includes("2.5-flash-lite"))return{minimal:512,low:2048,medium:8192,high:24576}[a];if(e.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[a];return-1}export{C as stream,F as streamSimple};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{f}from"./chunk-phjnj6x5.js";import"./chunk-2mj5h53m.js";import{m,de,Ee,fe,b,Be}from"./shumai-agent-app.js";import{se}from"./chunk-3mdhkfgq.js";import{K,q,ee}from"./chunk-115gx56y.js";import{V}from"./chunk-7z62cgr7.js";import{U,R}from"./chunk-7hkzk9pe.js";import{v,y}from"./chunk-dpd0zpsp.js";import{x}from"./chunk-p7sczpks.js";var ie=new Set;function ae(e){return ie.add(e),()=>{ie.delete(e)}}function ce(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var Ae={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Q(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||f(r)||f(n)||""}function Le(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function We(e,t,r){let n=Q("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function Ne(e,t){let r=Le(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||Ae[n]||0;if(!We(s,o,t))return"";let i=Q(`${n}_proxy`,t)||Q("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var Pe="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function ue(e,t){let r=Ne(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${Pe} Got ${n.protocol}`);return n}function Me(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var z=Me(),De="https://chatgpt.com/backend-api",Ie="https://api.openai.com/auth",qe=0,le=1000,Ue=60000,$e=15000,Fe=3,we=new Set(["openai","openai-codex","opencode"]),Je=1009,He="websocket_connection_limit_reached",Ke="previous_response_not_found",Ge=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ze(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Xe(e,t){if(e===429&&ze(t))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function je(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class ne extends Error{}function Ve(e,t){let r=t?.maxRetryDelayMs??Ue;if(r>0&&e>r)throw new ne(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function pe(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function me(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Ye(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Ze(e){let t=Ye();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Fe}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var Qe=(e,t,r)=>{let n=new m;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=Ct(o),l=v(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=V(a),p=et(e,t,r,c,l),u=await r?.onPayload?.(p,e);if(u!==void 0)p=u;let k=c||Be(),d=Ot(e.headers,r?.headers,i,o,c),T=At(e.headers,r?.headers,i,o,k),w=JSON.stringify(p),h=me(r?.timeoutMs),N=me(r?.websocketConnectTimeoutMs),g=r?.transport||"auto",E=!1,S=g!=="sse"&&Te(a);if(S)ye(a);if(g!=="sse"&&!S){let _=!1,O=!1,M=!1;while(!0){_=!1;try{if(await xt(rt(e.baseUrl),p,T,s,n,e,()=>{if(_=!0,!E)E=!0,n.push({type:"start",partial:s})},h,N,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(L){let J=r?.signal?.aborted,H=!_&&st(L),I=it(L);if(!J&&I&&!M){M=!0;continue}if(!J&&H&&!O){O=!0;continue}if(J||ot(L)&&!H)throw L;if(fe(s,Ee("provider_transport_failure",L,{configuredTransport:g,fallbackTransport:_?void 0:"sse",eventsEmitted:_,phase:_?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(w).byteLength})),mt(a,L),_)throw L;ye(a);break}}}let P=Ze(w);if(P)d.set("content-encoding","zstd");let D=P??w,C,F,Z=r?.maxRetries??qe;for(let _=0;_<=Z;_++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let O=h!==void 0&&h>0?AbortSignal.timeout(h):void 0,M=ce([r?.signal,O]);try{C=await fetch(_e(e.baseUrl),{method:"POST",headers:d,body:D,signal:M.signal})}catch(I){if(O?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${h}ms`);throw I}finally{M.cleanup()}if(await r?.onResponse?.({status:C.status,headers:x(C.headers)},e),C.ok)break;let L=await C.text();if(_<Z&&Xe(C.status,L)){let I=je(C.headers),Oe=I===void 0?le*2**_:Ve(I,r);await pe(Oe,r?.signal);continue}let J=new Response(L,{status:C.status,statusText:C.statusText}),H=await vt(J);throw Error(H.friendlyMessage||H.message)}catch(O){if(O instanceof Error){if(O.name==="AbortError"||O.message==="Request was aborted")throw Error("Request was aborted")}if(F=O instanceof Error?O:Error(String(O)),_<Z&&!(F instanceof ne)&&!F.message.includes("usage limit")){let M=le*2**_;await pe(M,r?.signal);continue}throw F}}if(!C?.ok)throw F??Error("Failed after retries");if(!C.body)throw Error("No response body");if(!E)E=!0,n.push({type:"start",partial:s});if(await nt(C,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=R(U(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},jt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=y(e,t,r,n),o=r?.reasoning?b(e,r.reasoning):void 0;return Qe(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function et(e,t,r,n,s=v(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=se(t,e.compat?.supportsToolSearch??!1),a=K(e,t,we,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=q(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let p=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(p!==null)c.reasoning={effort:p,summary:r.reasoningSummary??"auto"}}return c}function tt(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function ge(e,t,r){let n=tt(r,t);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function Se(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function _e(e){let r=(e&&e.trim().length>0?e:De).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function rt(e){let t=new URL(_e(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function nt(e,t,r,n,s,o){await ee(ke(ut(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:Se,applyServiceTierPricing:(i,l)=>ge(i,l,n)})}class B extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class Y extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function ot(e){return e instanceof B||e instanceof Y}function st(e){return e instanceof B&&e.code===He}function it(e){return e instanceof B&&e.code===Ke}function at(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*ke(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=at(t);throw new B(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new B(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:ct(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function ct(e){if(typeof e!=="string")return;return Ge.has(e)?e:void 0}async function*ut(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
|
|
3
|
+
|
|
4
|
+
`);while(a!==-1){let c=s.slice(0,a);s=s.slice(a+2);let p=c.split(`
|
|
5
|
+
`).filter((u)=>u.startsWith("data:")).map((u)=>u.slice(5).trim());if(p.length>0){let u=p.join(`
|
|
6
|
+
`).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(k){throw new Y(`Invalid Codex SSE JSON: ${de(k)}`,{cause:k,payload:u})}}a=s.indexOf(`
|
|
7
|
+
|
|
8
|
+
`)}}}finally{t?.removeEventListener("abort",o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}var lt="responses_websockets=2026-02-06",ft=300000,dt=3300000,A=new Map,G=new Map,j=new Set;function oe(e){let t=G.get(e);if(!t)t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},G.set(e,t);return t}function Vt(e){let t=G.get(e);return t?{...t}:void 0}function Yt(e){if(e){G.delete(e),j.delete(e);return}G.clear(),j.clear()}function pt(e){let t=(r)=>{if(r.idleTimer)clearTimeout(r.idleTimer);W(r.socket,1000,"debug_close")};if(e){let r=A.get(e);if(r)t(r);A.delete(e);return}for(let r of A.values())t(r);A.clear()}ae(pt);function Te(e){return e?j.has(e):!1}function ye(e){if(!e)return;let t=oe(e);t.sseFallbacks++,t.websocketFallbackActive=Te(e)}function mt(e,t){if(!e)return;j.add(e);let r=oe(e);r.websocketFailures++,r.lastWebSocketError=de(t),r.websocketFallbackActive=!0}var te=null;async function yt(e){if(!e&&te)return te;if(typeof process<"u"&&process.versions?.bun){let r=class extends WebSocket{constructor(n,s){let o={};if(Array.isArray(s)||typeof s==="string")o={protocols:s};else o={...s};let i=ue(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...o,...i?{proxy:i.toString()}:{}})}};if(!e)te=r;return r}let t=globalThis.WebSocket;if(typeof t!=="function")return null;return t}class Re extends Error{code;reason;wasClean;constructor(e,t){super(e);this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function bt(e){let t=e.readyState;return typeof t==="number"?t:void 0}function X(e){let t=bt(e);return t===void 0||t===1}function ht(e){return Date.now()-e.createdAt>=dt}function W(e,t=1000,r="done"){try{e.close(t,r)}catch{}}function be(e,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;W(t.socket,1000,"idle_timeout"),A.delete(e)},ft)}async function re(e,t,r,n=$e,s){let o=await yt(s);if(!o)throw Error("WebSocket transport is not available in this runtime");let i=x(t);return delete i["OpenAI-Beta"],new Promise((l,a)=>{let c=!1,p,u;try{u=new o(e,{headers:i})}catch(g){a(g instanceof Error?g:Error(String(g)));return}let k=()=>{if(p)clearTimeout(p),p=void 0;u.removeEventListener("open",T),u.removeEventListener("error",w),u.removeEventListener("close",h),r?.removeEventListener("abort",N)},d=(g,E)=>{if(c)return;if(c=!0,k(),E)W(u,1000,E);a(g)},T=()=>{if(c)return;c=!0,k(),l(u)},w=(g)=>{d(xe(g))},h=(g)=>{d(ve(g))},N=()=>{d(Error("Request was aborted"),"aborted")};if(u.addEventListener("open",T),u.addEventListener("error",w),u.addEventListener("close",h),r?.addEventListener("abort",N),n>0)p=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(r?.aborted)N()})}async function wt(e,t,r,n,s,o){if(!r){let c=await re(e,t,n,s,o);return{socket:c,reused:!1,release:()=>W(c)}}let i=A.get(r);if(i){if(i.idleTimer)clearTimeout(i.idleTimer),i.idleTimer=void 0;if(!i.busy&&ht(i))W(i.socket,1000,"connection_age_limit"),A.delete(r);else if(!i.busy&&X(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:c}={})=>{if(!c||!X(i.socket)){W(i.socket),A.delete(r);return}i.busy=!1,be(r,i)}};if(i.busy){let c=await re(e,t,n,s,o);return{socket:c,reused:!1,release:()=>{W(c)}}}if(!X(i.socket))W(i.socket),A.delete(r)}let l=await re(e,t,n,s,o),a={socket:l,busy:!0,createdAt:Date.now()};return A.set(r,a),{socket:l,entry:a,reused:!1,release:({keep:c}={})=>{if(!c||!X(a.socket)){if(W(a.socket),a.idleTimer)clearTimeout(a.idleTimer);if(A.get(r)===a)A.delete(r);return}a.busy=!1,be(r,a)}}}function xe(e){if(e&&typeof e==="object"){let t="message"in e?e.message:void 0;if(typeof t==="string"&&t.length>0)return Error(t);let r="error"in e?e.error:void 0;if(r instanceof Error&&r.message.length>0)return r;if(r&&typeof r==="object"&&"message"in r){let n=r.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function ve(e){if(e&&typeof e==="object"){let t="code"in e?e.code:void 0,r="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,s=typeof t==="number"?` ${t}`:"",o=typeof r==="string"&&r.length>0?` ${r}`:"";if(!o&&t===Je)o=" message too big";return new Re(`WebSocket closed${s}${o}`.trim(),{code:typeof t==="number"?t:void 0,reason:typeof r==="string"&&r.length>0?r:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function gt(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==="object"&&"arrayBuffer"in e){let r=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(r))}return null}async function*St(e,t,r){let n=[],s=null,o=!1,i=null,l=!1,a=()=>{if(!s)return;let d=s;s=null,d()},c=(d)=>{(async()=>{let T=null;try{if(!d||typeof d!=="object"||!("data"in d))return;if(T=await gt(d.data),!T)return;let w=JSON.parse(T),h=typeof w.type==="string"?w.type:"";if(h==="response.completed"||h==="response.done"||h==="response.incomplete")l=!0,o=!0;n.push(w),a()}catch(w){i=new Y(`Invalid Codex WebSocket JSON: ${de(w)}`,{cause:w,payload:T}),o=!0,a()}})()},p=(d)=>{i=xe(d),o=!0,a()},u=(d)=>{if(l){o=!0,a();return}if(!i)i=ve(d);o=!0,a()},k=()=>{i=Error("Request was aborted"),o=!0,a()};e.addEventListener("message",c),e.addEventListener("error",p),e.addEventListener("close",u),t?.addEventListener("abort",k);try{while(!0){if(t?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(o)break;let d;await new Promise((T,w)=>{if(s=T,r!==void 0&&r>0)d=setTimeout(()=>{let h=Error(`WebSocket idle timeout after ${r}ms`);i=h,o=!0,s=null,W(e,1000,"idle_timeout"),w(h)},r)}).finally(()=>{if(d)clearTimeout(d)})}if(i)throw i;if(!l)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",c),e.removeEventListener("error",p),e.removeEventListener("close",u),t?.removeEventListener("abort",k)}}function he(e){let{input:t,previous_response_id:r,...n}=e;return n}function Et(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function _t(e,t){return JSON.stringify(he(e))===JSON.stringify(he(t))}function kt(e,t){if(!_t(e,t.lastRequestBody))return;let r=e.input??[],n=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(r.length<n.length)return;let s=r.slice(0,n.length);if(!Et(s,n))return;return r.slice(n.length)}function Tt(e,t){let r=e.continuation;if(!r)return t;let n=kt(t,r);if(!n||!r.lastResponseId)return e.continuation=void 0,t;return{...t,previous_response_id:r.lastResponseId,input:n}}async function*Rt(e,t){let r=!1;for await(let n of e){if(!r)r=!0,t();yield n}}async function xt(e,t,r,n,s,o,i,l,a,c,p,u){let{socket:k,entry:d,reused:T,release:w}=await wt(e,r,c,u?.signal,a,u?.env),h=!0,N=u?.transport==="websocket-cached"||u?.transport==="auto",g=t,E=N&&d?Tt(d,g):g,S=c?oe(c):void 0;if(S){if(S.requests++,T)S.connectionsReused++;else S.connectionsCreated++;if(N)S.cachedContextRequests++;if(E.store===!0)S.storeTrueRequests++;if(S.lastInputItems=E.input?.length??0,E.previous_response_id)S.deltaRequests++,S.lastDeltaInputItems=E.input?.length??0,S.lastPreviousResponseId=E.previous_response_id;else S.fullContextRequests++,S.lastDeltaInputItems=void 0,S.lastPreviousResponseId=void 0}try{if(k.send(JSON.stringify({type:"response.create",...E})),await ee(Rt(ke(St(k,u?.signal,l)),i),n,s,o,{serviceTier:u?.serviceTier,grammarToolInputProperties:p,resolveServiceTier:Se,applyServiceTierPricing:(P,D)=>ge(P,D,o)}),u?.signal?.aborted)h=!1;else if(N&&d&&n.responseId){let P=K(o,{messages:[n]},we,{includeSystemPrompt:!1,grammarToolInputProperties:p}).filter((D)=>D.type!=="function_call_output"&&D.type!=="custom_tool_call_output");d.continuation={lastRequestBody:g,lastResponseId:n.responseId,lastResponseItems:P}}}catch(P){if(d)d.continuation=void 0;throw h=!1,P}finally{w({keep:h})}}async function vt(e){let t=await e.text(),r=t||e.statusText||"Request failed",n;try{let o=JSON.parse(t)?.error;if(o){let i=o.code||o.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let l=o.plan_type?` (${o.plan_type.toLowerCase()} plan)`:"",a=o.resets_at?Math.max(0,Math.round((o.resets_at*1000-Date.now())/60000)):void 0,c=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${l}.${c}`.trim()}r=o.message||n||r}}catch{}return{message:r,friendlyMessage:n}}function Ct(e){try{let t=e.split(".");if(t.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(t[1]))?.[Ie]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function Ce(e,t,r,n){let s=new Headers(e);for(let[i,l]of Object.entries(t||{}))if(l===null)s.delete(i);else s.set(i,l);s.set("Authorization",`Bearer ${n}`),s.set("chatgpt-account-id",r),s.set("originator","pi");let o=z?`pi (${z.platform()} ${z.release()}; ${z.arch()})`:"pi (browser)";return s.set("User-Agent",o),s}function Ot(e,t,r,n,s){let o=Ce(e,t,r,n);if(o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s)o.set("session-id",s),o.set("x-client-request-id",s);return o}function At(e,t,r,n,s){let o=Ce(e,t,r,n);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",lt),o.set("x-client-request-id",s),o.set("session-id",s),o}export{pt as closeOpenAICodexWebSocketSessions,Vt as getOpenAICodexWebSocketDebugStats,Yt as resetOpenAICodexWebSocketDebugStats,Qe as stream,jt as streamSimple};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var zr=Object.create;var{getPrototypeOf:Vr,defineProperty:Et,getOwnPropertyNames:Gr}=Object;var qt=Object.prototype.hasOwnProperty;function Fr(e){return this[e]}var Xr,Yr,h=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var i=t?Xr??=new WeakMap:Yr??=new WeakMap,c=i.get(e);if(c)return c}n=e!=null?zr(Vr(e)):{};let s=t||!e||!e.__esModule||!qt.call(e,"default")?Et(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let p of Gr(e))if(!qt.call(s,p))Et(s,p,{get:Fr.bind(e,p),enumerable:!0})}if(o)i.set(e,s);return s};var r=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var qr=(e)=>e;function Zr(e,t){this[e]=qr.bind(null,t)}var O=(e,t)=>{for(var n in t)Et(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Zr.bind(t,n)})};var a=import.meta.require;var Je=new TextEncoder,ae=new TextDecoder,fe=new TextDecoder("utf-8",{fatal:!0});function v(...e){let t=e.reduce((i,{length:c})=>i+c,0),n=new Uint8Array(t),o=0;for(let i of e)n.set(i,o),o+=i.length;return n}function bt(e,t,n){if(t<0||t>=4294967296)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function St(e){let t=Math.floor(e/4294967296),n=e%4294967296,o=new Uint8Array(8);return bt(o,t,0),bt(o,n,4),o}function Le(e){let t=new Uint8Array(4);return bt(t,e),t}function K(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o>127)throw TypeError("non-ASCII string encountered in encode()");t[n]=o}return t}var je=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function At(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ze(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=="number"||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function X(e,t,n){let o=e.algorithm;if(o.name!==t.name)throw je(t.name);if(t.hash&&o.hash?.name!==t.hash)throw je(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw je(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&o.length!==t.length)throw je(t.length,"algorithm.length");At(e,n)}function Zt(e,t,...n){if(n.length>2){let o=n.pop();e+=`one of type ${n.join(", ")}, or ${o}.`}else if(n.length===2)e+=`one of type ${n[0]} or ${n[1]}.`;else e+=`of type ${n[0]}.`;if(t==null)e+=` Received ${t}`;else if(typeof t==="function"&&t.name)e+=` Received function ${t.name}`;else if(typeof t==="object"&&t!=null){if(t.constructor?.name)e+=` Received an instance of ${t.constructor.name}`}return e}var Y=(e,...t)=>Zt("Key must be ",e,...t),We=(e,t,...n)=>Zt(`Key for the ${e} algorithm must be `,t,...n);class T extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t);this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class M extends T{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,n="unspecified",o="unspecified"){super(e,{cause:{claim:n,reason:o,payload:t}});this.claim=n,this.reason=o,this.payload=t}}class he extends T{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,n="unspecified",o="unspecified"){super(e,{cause:{claim:n,reason:o,payload:t}});this.claim=n,this.reason=o,this.payload=t}}class ue extends T{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class w extends T{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Ve extends T{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class l extends T{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class S extends T{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class x extends T{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class Ge extends T{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class Xe extends T{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class Ce extends T{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class xt extends T{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class Kt extends T{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class Jt extends T{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function Ye(e){if(!q(e))throw Error("CryptoKey instance expected")}var q=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Wt=(e)=>e?.[Symbol.toStringTag]==="KeyObject",qe=(e)=>q(e)||Wt(e);var Z=(e)=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function Qt(e,t){let n=e.byteLength<<3;if(n!==t)throw new l(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var Qr=(e)=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function er(e,t){if(t.length<<3!==e.ivBits)throw new l("Invalid Initialization Vector length")}async function tr(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(Y(t,"Uint8Array"));let o=e.cekBits>>1,i=await crypto.subtle.importKey("raw",t.subarray(o>>3),"AES-CBC",!1,[n]),c=await crypto.subtle.importKey("raw",t.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[i,c,o]}async function rr(e,t,n){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,n>>3))}async function en(e,t,n,o,i){let[c,s,p]=await tr(e,n,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},c,t)),f=v(i,o,d,St(i.length*8)),u=await rr(s,f,p);return{ciphertext:d,tag:u,iv:o}}async function tn(e,t){let n={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(n,!1,["sign","verify"]),i=await crypto.subtle.sign(n,o,e);return crypto.subtle.verify(n,o,i,t)}async function rn(e,t,n,o,i,c){let[s,p,d]=await tr(e,t,"decrypt"),f=v(c,o,n,St(c.length*8)),u=await rr(p,f,d);try{if(await tn(i,u))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,n))}catch{}throw new Ve}async function nn(e,t,n,o,i){let c=n instanceof Uint8Array?await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt"]):(X(n,e.subtle,"encrypt"),n),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},c,t)),p=s.slice(-16);return{ciphertext:s.slice(0,-16),tag:p,iv:o}}async function on(e,t,n,o,i,c){let s=t instanceof Uint8Array?await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(X(t,e.subtle,"decrypt"),t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:c,iv:o,name:"AES-GCM",tagLength:128},s,v(n,i)))}catch{throw new Ve}}async function Qe(e,t,n,o,i){if(!q(n)&&!(n instanceof Uint8Array))throw TypeError(Y(n,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o)er(e,o);else o=Qr(e);if(n instanceof Uint8Array)Qt(n,e.cekBits);return e.cbc?en(e,t,n,o,i):nn(e,t,n,o,i)}async function tt(e,t,n,o,i,c){if(!q(t)&&!(t instanceof Uint8Array))throw TypeError(Y(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new l("JWE Initialization Vector missing");if(!i)throw new l("JWE Authentication Tag missing");if(!e.cbc&&i.length!==16)throw new l("Invalid Authentication Tag length");if(er(e,o),t instanceof Uint8Array)Qt(t,e.cekBits);return e.cbc?rn(e,t,n,o,i,c):on(e,t,n,o,i,c)}var et={};O(et,{decode:()=>L,encode:()=>g});function Ct(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let o=0;o<e.length;o+=t)n.push(String.fromCharCode.apply(null,e.subarray(o,o+t)));return btoa(n.join(""))}function rt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}var vt="The input to be decoded is not correctly encoded.";function L(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e==="string"?e:ae.decode(e),{alphabet:"base64url"})}catch(n){throw TypeError(vt,{cause:n})}let t=e;if(t instanceof Uint8Array)t=ae.decode(t);if(t.includes("+")||t.includes("/"))throw TypeError(vt);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return rt(t)}catch{throw TypeError(vt)}}function g(e){let t=e;if(typeof t==="string")t=Je.encode(t);if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:"base64url",omitPadding:!0});return Ct(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function se(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function J(e){if(typeof e!=="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function nt(e){return J(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(J)}function nr(...e){let t=new Set;for(let n of e){if(!n)continue;for(let o of Object.keys(n)){if(t.has(o))return!1;t.add(o)}}return!0}var or=Symbol();function ce(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function _(e,t,n){try{return L(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Tt(e,t,n){try{return K(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}async function ot(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}function ne(e,t,n){let o;try{o=JSON.parse(fe.decode(L(e)))}catch{throw new t(n)}if(!J(o))throw new t(n);return o}async function Q(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new w('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),i={...t};if(i.kty!=="AKP")delete i.alg;return delete i.use,crypto.subtle.importKey("jwk",i,n,t.ext??!o,t.key_ops??e.usages[o?1:0])}function le(e){return{__proto__:null,...e}}function it(e){let t=le(e);if(t.ext!==void 0&&typeof t.ext!=="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let n=t.key_ops,o=Array.isArray(n)?[...n]:void 0;if(!o||o.some((i)=>typeof i!=="string")||new Set(o).size!==o.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=o}return t}var Pt=(e)=>e[Symbol.toStringTag],an=(e,t,n)=>{let{alg:o}=e;if(t.use!==void 0){let i=n==="sign"||n==="verify"?"sig":"enc";if(t.use!==i)throw TypeError(`Invalid key for this operation, its "use" must be "${i}" when present`)}if(t.alg!==void 0&&t.alg!==o)throw TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let i=n==="encrypt"||n==="decrypt"?e.ops?.[n==="encrypt"?0:1]:n;if(i&&!t.key_ops.includes(i))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${i}" when present`)}};function sn(e,t,n){let{alg:o,secret:i}=e,c=n==="decrypt"||n==="sign";if(i&&t instanceof Uint8Array)return[ar,t];if(J(t)){let s=it(t);if(typeof s.kty!=="string")throw TypeError(i?We(o,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):We(o,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(i?s.kty==="oct"&&typeof s.k==="string":s.kty!=="oct"&&(c?s.kty==="AKP"&&typeof s.priv==="string"||typeof s.d==="string":s.d===void 0&&s.priv===void 0)))throw TypeError(i?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${c?"private":"public"} JWK`);return an(e,s,n),[pr,t,s]}if(!qe(t))throw TypeError(i?We(o,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):We(o,t,"CryptoKey","KeyObject","JSON Web Key"));if(i){if(t.type!=="secret")throw TypeError(`${Pt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw TypeError(`${Pt(t)} instances for asymmetric algorithms must not be of type "secret"`);let s=c?"private":"public";if((t.type==="public"||t.type==="private")&&t.type!==s){let p=n==="sign"?"signing":n==="verify"?"verifying":`${n.slice(0,-1)}tion`;throw TypeError(`${Pt(t)} instances for asymmetric algorithm ${p} must be of type "${s}"`)}}return q(t)?[sr,t]:[cr,t]}var ar=0,sr=1,cr=2,pr=3,It,cn={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function st(e,t,n){It||=new WeakMap;let o=It.get(e);if(n)if(o)o[t]=n;else It.set(e,{[t]:n});return n??o?.[t]}var ir=async(e,t,n)=>st(e,n.alg)??st(e,n.alg,await Q(n,{...t,alg:n.alg})),pn=(e,t)=>{let n=st(e,t.alg);if(n)return n;let o=e.type==="public",i=t.usages[o?0:1],{asymmetricKeyType:c}=e,s=cn[e.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:s,asymmetricKeyType:c})??t.subtle;return st(e,t.alg,e.toCryptoKey(p,o,i))};async function j(e,t,n){let o=sn(e,t,n);switch(o[0]){case ar:case sr:return o[1];case pr:{let i=o[1],c=o[2];if(c.kty==="oct")return L(c.k);if(!Object.isFrozen(i)){let{key_ops:s}=i;if(Array.isArray(s))Object.freeze(s);Object.freeze(i)}return ir(i,c,e)}case cr:{let i=o[1];if(i.type==="secret")return i.export();if("toCryptoKey"in i&&typeof i.toCryptoKey==="function")return pn(i,e);return ir(i,i.export({format:"jwk"}),e)}}}function Pe(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var dn=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],fn=[[],["deriveBits"]],ft=[[],[]];function pt(e){return{kty:["RSA"],subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:dn,ops:["wrapKey","unwrapKey"]}}function dt(){return{kty:["EC","OKP"],subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t==="X25519"||n==="x25519")return{name:"X25519"};if(e==="OKP")throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:fn,ops:[void 0,"deriveBits"]}}function me(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:ft,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function Ot(){return{kty:["oct"],secret:!0,subtle:{name:"PBKDF2"},usages:ft,ops:["deriveBits","deriveBits"]}}var _t=Pe({dir:{kty:["oct"],secret:!0,subtle:{name:"AES-GCM"},usages:ft,ops:["encrypt","decrypt"]},"RSA-OAEP":pt(1),"RSA-OAEP-256":pt(256),"RSA-OAEP-384":pt(384),"RSA-OAEP-512":pt(512),"ECDH-ES":dt(),"ECDH-ES+A128KW":dt(),"ECDH-ES+A192KW":dt(),"ECDH-ES+A256KW":dt(),A128KW:me(128),A192KW:me(192),A256KW:me(256),A128GCMKW:me(128,!0),A192GCMKW:me(192,!0),A256GCMKW:me(256,!0),"PBES2-HS256+A128KW":Ot(),"PBES2-HS384+A192KW":Ot(),"PBES2-HS512+A256KW":Ot()}),un=["encrypt","decrypt"];function ye(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:ft,ops:un,cekBits:e,ivBits:t?128:96,cbc:t}}var ln=Pe({A128GCM:ye(128),A192GCM:ye(192),A256GCM:ye(256),"A128CBC-HS256":ye(256,!0),"A192CBC-HS384":ye(384,!0),"A256CBC-HS512":ye(512,!0)});function dr(e,t){throw new w(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function z(e){return(typeof e==="string"?_t[e]:void 0)??dr("alg","Algorithm")}function pe(e){return(typeof e==="string"?ln[e]:void 0)??dr("enc","Encryption Algorithm")}function fr(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");At(e,t)}async function lr(e,t,n){let o=z(t).subtle,i=e instanceof Uint8Array?await crypto.subtle.importKey("raw",e,"AES-KW",!0,[n]):e;return X(i,o,n),i}async function Dt(e,t,n){let o=await lr(t,e,"wrapKey"),i=await crypto.subtle.importKey("raw",n,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,o,"AES-KW"))}async function Ut(e,t,n){let o=await lr(t,e,"unwrapKey"),i=await crypto.subtle.unwrapKey("raw",n,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}function mr(e,t,n){X(t,z(e).subtle,n),ze(e,t)}function mn(e,t){if(e instanceof Uint8Array)return crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);return X(e,z(t).subtle,"deriveBits"),e}async function yr(e,t,n,o){if(!(e instanceof Uint8Array)||e.length<8)throw new l("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new l("PBES2 Count Input must be a positive integer");let i=v(K(t),Uint8Array.of(0),e),c=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:"PBKDF2",salt:i},p=await mn(o,t);return new Uint8Array(await crypto.subtle.deriveBits(s,p,c))}function Rt(e){return v(Le(e.length),e)}async function yn(e,t,n){let o=t>>3,i=32,c=Math.ceil(o/32),s=new Uint8Array(c*32);for(let p=1;p<=c;p++){let d=await ot("sha256",v(Le(p),e,n));s.set(d,(p-1)*32)}return s.slice(0,o)}async function hr(e,t,n,o,i=new Uint8Array,c=new Uint8Array){fr(e),fr(t,"deriveBits");let s=v(Rt(K(n)),Rt(i),Rt(c),Le(o)),p=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return yn(p,o,s)}function wr(e){Ye(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new w("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function Ie(e){if(e===void 0)throw new l("JWE Encrypted Key missing")}function ur(e){if(e!==void 0)throw new l("Encountered unexpected JWE Encrypted Key")}async function gr(e,t,n,o,i,c){let s=z(e);if(e==="dir")return ur(o),n;switch(s.subtle.name){case"ECDH":{if(e==="ECDH-ES")ur(o);if(!J(i.epk))throw new l('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');wr(n);let p=await Q(s,i.epk),d,f;if(i.apu!==void 0){if(typeof i.apu!=="string")throw new l('JOSE Header "apu" (Agreement PartyUInfo) invalid');d=_(i.apu,"apu",l)}if(i.apv!==void 0){if(typeof i.apv!=="string")throw new l('JOSE Header "apv" (Agreement PartyVInfo) invalid');f=_(i.apv,"apv",l)}let u=await hr(p,n,e==="ECDH-ES"?t.alg:e,e==="ECDH-ES"?t.cekBits:parseInt(e.slice(-5,-2),10),d,f);if(e==="ECDH-ES")return u;return Ie(o),Ut(e.slice(-6),u,o)}case"RSA-OAEP":return Ie(o),Ye(n),mr(e,n,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",n,o));case"PBKDF2":{if(Ie(o),typeof i.p2c!=="number")throw new l('JOSE Header "p2c" (PBES2 Count) missing or invalid');let p=c||1e4;if(i.p2c>p)throw new l('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof i.p2s!=="string")throw new l('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let d=_(i.p2s,"p2s",l),f=await yr(d,e,i.p2c,n);return Ut(e.slice(-6),f,o)}case"AES-KW":return Ie(o),Ut(e,n,o);case"AES-GCM":{if(Ie(o),typeof i.iv!=="string")throw new l('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof i.tag!=="string")throw new l('JOSE Header "tag" (Authentication Tag) missing or invalid');let p;p=_(i.iv,"iv",l);let d;return d=_(i.tag,"tag",l),tt(pe(e.slice(0,-2)),n,o,p,d,new Uint8Array)}}}async function Er(e,t,n,o,i={}){let c,s,p,d=z(e);if(e==="dir")return[n,void 0,void 0];switch(d.subtle.name){case"ECDH":{wr(n);let{apu:f,apv:u}=i;if(f!==void 0)se(f,'"apu"');if(u!==void 0)se(u,'"apv"');let m;if(i.epk!==void 0)m=await j(d,i.epk,"decrypt");else m=(await crypto.subtle.generateKey(n.algorithm,!0,["deriveBits"])).privateKey;let y=crypto.subtle,P=m;if(!P.extractable){if(typeof y.getPublicKey!=="function")throw TypeError('CryptoKey for "epk" must be extractable');P=await y.getPublicKey(m,[])}let{x:R,y:A,crv:b,kty:U}=await y.exportKey("jwk",P),E=await hr(n,m,e==="ECDH-ES"?t.alg:e,e==="ECDH-ES"?t.cekBits:parseInt(e.slice(-5,-2),10),f,u);if(s={epk:{x:R,crv:b,kty:U}},U==="EC")s.epk.y=A;if(f)s.apu=g(f);if(u)s.apv=g(u);if(e==="ECDH-ES"){p=E;break}p=o||Z(t);let I=e.slice(-6);c=await Dt(I,E,p);break}case"RSA-OAEP":{p=o||Z(t),Ye(n),mr(e,n,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",n,p));break}case"PBKDF2":{p=o||Z(t);let{p2c:f=2048,p2s:u=crypto.getRandomValues(new Uint8Array(16))}=i,m=await yr(u,e,f,n);c=await Dt(e.slice(-6),m,p),s={p2c:f,p2s:g(u)};break}case"AES-KW":{p=o||Z(t),c=await Dt(e,n,p);break}case"AES-GCM":{p=o||Z(t);let{iv:f}=i,u=await Qe(pe(e.slice(0,-2)),p,n,f,new Uint8Array);c=u.ciphertext,s={iv:g(u.iv),tag:g(u.tag)};break}}return[p,c,s]}var we={__proto__:null,b64:!0},ut={__proto__:null};function Oe(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some((n)=>typeof n!=="string")))throw TypeError(`"${e}" option must be an array of strings`);if(!t)return;return new Set(t)}function lt(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function V(e,t,n,o,i){if(i.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some((s)=>typeof s!=="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let c=n===void 0?t:{__proto__:null,...n,...t};for(let s of o.crit){if(!(s in c))throw new w(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(i,s)||i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(c[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function ge(e,t){if(t.includes("b64")){let n=e.b64;if(typeof n!=="boolean")throw new S('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return n}return!0}function Ee(e,t){let n,o;try{n=JSON.stringify(t),o=JSON.parse(n)}catch(i){throw new e("JOSE Header is not valid JSON",{cause:i})}if(!J(o))throw new e("JOSE Header is not a JSON object");return[o,n]}function mt(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new w('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new l('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function br(e){if(typeof globalThis[e]>"u")throw new w(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Sr(e){br("CompressionStream");let t=new CompressionStream("deflate-raw"),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let o=[],i=t.readable.getReader();for(;;){let{value:c,done:s}=await i.read();if(s)break;o.push(c)}return v(...o)}async function Ar(e,t){br("DecompressionStream");let n=new DecompressionStream("deflate-raw"),o=n.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let i=[],c=0,s=n.readable.getReader();for(;;){let{value:p,done:d}=await s.read();if(d)break;if(i.push(p),c+=p.byteLength,t!==1/0&&c>t)throw new l("Decompressed plaintext exceeded the configured limit")}return v(...i)}function xr(e){return[e&&Oe("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&Oe("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function hn(e,t,n,o,i){let[c,s,p,d,f]=n,[u,m,y,P,R]=t,{encrypted_key:A}=e;V(l,ut,p,u,i),mt(i,u);let{alg:b,enc:U}=i;if(typeof b!=="string"||!b)throw new l("missing JWE Algorithm (alg) in JWE Header");if(typeof U!=="string"||!U)throw new l("missing JWE Encryption Algorithm (enc) in JWE Header");if(c&&!c.has(b)||!c&&b.startsWith("PBES2"))throw new ue('"alg" (Algorithm) Header Parameter value not allowed');if(s&&!s.has(U))throw new ue('"enc" (Encryption Algorithm) Header Parameter value not allowed');let E=pe(U),I;if(A!==void 0)I=_(A,"encrypted_key",l);let N=!1;if(typeof o==="function")o=await o(u,e),N=!0;let G=z(b),B=await j(b==="dir"?E:G,o,"decrypt"),H;try{if(H=await gr(b,E,B,I,i,d),A!==void 0&&H instanceof Uint8Array&&H.byteLength<<3!==E.cekBits)H=Z(E)}catch(D){if(D instanceof TypeError||D instanceof l||D instanceof w)throw D;H=Z(E)}let oe=await tt(E,H,m,y,P,R);if(i.zip==="DEF"){let D=f??250000;if(D===0)throw new w('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(D!==1/0&&(!Number.isSafeInteger(D)||D<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");oe=await Ar(oe,D).catch((ie)=>{if(ie instanceof l)throw ie;throw new l("Failed to decompress plaintext",{cause:ie})})}return[oe,u,B,N]}async function Kr(e,t,n){if(e instanceof Uint8Array)e=ae.decode(e);if(typeof e!=="string")throw new l("Compact JWE must be a string or Uint8Array");let{0:o,1:i,2:c,3:s,4:p,length:d}=e.split(".");if(d!==5)throw new l("Invalid Compact JWE");let f={ciphertext:s,iv:c||void 0,protected:o,tag:p||void 0,encrypted_key:i||void 0},u=ne(o,l,"JWE Protected Header is invalid"),m=K(o),y=[u,_(s,"ciphertext",l),c?_(c,"iv",l):void 0,p?_(p,"tag",l):void 0,m];return hn(f,y,t,n,u)}function Jr(e,t,n){if(!nr(e,t,n))throw new l("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function wn(e){let[,t,n,o,i,c,s,p,d]=e;if(i!==void 0)se(i,"JWE Additional Authenticated Data");if(c!==void 0)se(c,"JWE Content Encryption Key");if(s!==void 0)se(s,"JWE Initialization Vector");if(t!==void 0)t=Ee(l,t)[0],e[1]=t;if(n!==void 0)n=Ee(l,n)[0],e[2]=n;if(o!==void 0)o=Ee(l,o)[0],e[3]=o;if(p!==void 0&&!J(p))throw TypeError("JWE Key Management Parameters must be an object");Jr(t,n,o);let f={...t,...n,...o};lt(l,t),V(l,ut,d,t,f),mt(f,t);let{alg:u,enc:m}=f;if(typeof u!=="string"||!u)throw new l('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof m!=="string"||!m)throw new l('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[f,u,m,pe(m)]}async function gn(e,t,n){let[o,i,,c]=t,[s,p,d,f,u,m,y,P,,R]=e,A=p,b=d;if(m&&(i==="dir"||i==="ECDH-ES"))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);let U=z(i),E=await j(i==="dir"?c:U,n,"encrypt"),[I,N,G]=await Er(i,c,E,m,P);if(G){if(R)b=b?{...b,...G}:G;else A=A?{...A,...G}:G;Jr(A,b,f)}let B,H;if(A)B=g(JSON.stringify(A)),H=K(B);else B="",H=new Uint8Array;let oe,D;if(u?.byteLength)D=g(u),oe=v(H,K("."),K(D));else oe=H;let ie=s;if(o.zip==="DEF")ie=await Sr(ie).catch((jr)=>{throw new l("Failed to compress plaintext",{cause:jr})});let{ciphertext:Lr,tag:Xt,iv:Yt}=await Qe(c,ie,I,y,oe),re={ciphertext:g(Lr)};if(Yt)re.iv=g(Yt);if(Xt)re.tag=g(Xt);if(N)re.encrypted_key=g(N);if(D)re.aad=D;if(A)re.protected=B;if(f)re.unprotected=f;if(b)re.header=b;return re}async function Wr(e,t,n){if(!e[1]&&!e[2]&&!e[3])throw new l("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(n!==void 0)e[8]=n?.crit,e[9]=n?or in n:!1;return gn(e,wn(e),t)}async function Cr(e,t,n){if(t instanceof Uint8Array)return crypto.subtle.importKey("raw",t,e.subtle,!1,[n]);if(X(t,e.subtle,n),e.minRsaBits)ze(e.alg,t);return t}async function vr(e,t,n){let o=await Cr(e,t,"sign"),i=await crypto.subtle.sign(e.signing,o,n);return new Uint8Array(i)}async function Tr(e,t,n,o){let i=await Cr(e,t,"verify");try{return await crypto.subtle.verify(e.signing,i,n,o)}catch{return!1}}var _e=[["verify"],["sign"]];function Nt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:_e}}function be(e,t){let o={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:o,signing:t?{...o,saltLength:t}:o,usages:_e,minRsaBits:2048}}function Ht(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:_e}}function Pr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:_e}}function kt(e){let n={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:n,signing:n,usages:_e}}var De=Pe({HS256:Nt(256),HS384:Nt(384),HS512:Nt(512),RS256:be(256),RS384:be(384),RS512:be(512),PS256:be(256,32),PS384:be(384,48),PS512:be(512,64),ES256:Ht("P-256",256),ES384:Ht("P-384",384),ES512:Ht("P-521",512),EdDSA:Pr(),Ed25519:Pr(),"ML-DSA-44":kt(44),"ML-DSA-65":kt(65),"ML-DSA-87":kt(87)});function yt(e){let t=typeof e==="string"?De[e]:void 0;if(!t)throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Ir(e){return[e&&Oe("algorithms",e.algorithms),e?.crit]}function En(e,t=e===void 0?{}:ne(e,S,"JWS Protected Header is invalid")){return t}function bn(e,t,n){let o=ge(e,V(S,we,n[1],e,t)),i=t.alg;if(typeof i!=="string"||!i)throw new S('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(n[0]&&!n[0].has(i))throw new ue('"alg" (Algorithm) Header Parameter value not allowed');return[o,i]}function Sn(e){try{return K(e)}catch{throw new S("JWS Compact Serialization payload must use only ASCII characters")}}async function An(e,t,n,o,i,c,s){let p=!1;if(typeof n==="function")n=await n(i,e),p=!0;let d=typeof s==="string",f=yt(c),u=v(o!==void 0?K(o):new Uint8Array,K("."),d?t[2]??=Tt(s,"payload",S):s),m=_(e.signature,"signature",S),y=await j(f,n,"verify");if(!await Tr(f,y,m,u))throw new Jt;return[d?_(s,"payload",S):s,i,d,y,p]}async function Or(e,t,n){if(e instanceof Uint8Array)e=ae.decode(e);if(typeof e!=="string")throw new S("Compact JWS must be a string or Uint8Array");let{0:o,1:i,2:c,length:s}=e.split(".");if(s!==3)throw new S("Invalid Compact JWS");let p={payload:i,protected:o,signature:c},d=En(o),[f,u]=bn(d,d,t),m=f?i:Sn(i);return An(p,t,n,o,d,u,m)}var Ue=(e)=>Math.floor(e.getTime()/1000),xn={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Kn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Se="check_failed";function Bt(){throw TypeError("Invalid time period format")}function ht(e){if(typeof e!=="string")Bt();let t=Kn.exec(e);if(!t||t[4]&&t[1])Bt();let n=parseFloat(t[2]),o=Math.round(n*xn[t[3][0].toLowerCase()]);if(!Number.isFinite(o))Bt();if(t[1]==="-"||t[4]==="ago")return-o;return o}function Ae(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Mt(e,t){if(typeof t!=="string")throw TypeError(`"${e}" claim must be a string`)}function Jn(e){if(typeof e!=="string"&&(!Array.isArray(e)||Array.from(e).some((t)=>typeof t!=="string")))throw TypeError('"aud" claim must be a string or an array of strings')}function $t(e,t){if(typeof e==="number")return Ae(t,e);if(e instanceof Date)return Ae(t,Ue(e));return Ue(new Date)+ht(e)}var _r=(e)=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},Wn=(e,t)=>{if(typeof e==="string")return t.includes(e);if(Array.isArray(e))return t.some((n)=>e.includes(n));return!1};function Lt(e,t,n=!1){let o=e[t];if(o===void 0&&!n)return;if(typeof o!=="number")throw new M(`"${t}" claim must be a number`,e,t,"invalid");return o}function jt(e,t){throw new M(`unexpected "${t}" claim value`,e,t,Se)}function xe(e,t,n={}){let o;try{o=JSON.parse(fe.decode(t))}catch{}if(!J(o))throw new x("JWT Claims Set must be a top-level JSON object");let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=="string"||_r(e.typ)!==_r(i)))throw new M('unexpected "typ" JWT header value',o,"typ",Se);let{requiredClaims:c=[],issuer:s,subject:p,audience:d,maxTokenAge:f}=n,u=[...c];if(f!==void 0)u.push("iat");if(d!==void 0)u.push("aud");if(p!==void 0)u.push("sub");if(s!==void 0)u.push("iss");for(let E of new Set(u.reverse()))if(!Object.hasOwn(o,E))throw new M(`missing required "${E}" claim`,o,E,"missing");if(s!==void 0&&!(Array.isArray(s)?s:[s]).includes(o.iss))jt(o,"iss");if(p!==void 0&&o.sub!==p)jt(o,"sub");if(d!==void 0&&!Wn(o.aud,typeof d==="string"?[d]:d))jt(o,"aud");let{clockTolerance:m}=n,y=0;if(typeof m==="string")y=ht(m);else if(m!==void 0){if(typeof m!=="number")throw TypeError("Invalid clockTolerance option type");y=m}Ae("clockTolerance option",y);let{currentDate:P}=n,R=Ae("currentDate option",Ue(P===void 0?new Date:P)),A=Lt(o,"iat",f!==void 0),b=Lt(o,"nbf");if(b!==void 0){if(b>R+y)throw new M('"nbf" claim timestamp check failed',o,"nbf",Se)}let U=Lt(o,"exp");if(U!==void 0){if(U<=R-y)throw new he('"exp" claim timestamp check failed',o,"exp",Se)}if(f!==void 0){let E=R-A,I=Ae("maxTokenAge option",typeof f==="number"?f:ht(f));if(E-y>I)throw new he('"iat" claim timestamp check failed (too far in the past)',o,"iat",Se);if(E<-y)throw new M('"iat" claim timestamp check failed (it should be in the past)',o,"iat",Se)}return o}var Dr;function ee(e){return Dr.get(e)}function Ke(e){let t=ee(e);for(let n of["iat","nbf","exp"]){let o=t[n];if(typeof o==="number"&&!Number.isFinite(o))throw TypeError(`"${n}" claim must be a finite number`)}return Je.encode(JSON.stringify(t))}function wt(e,t){return ee(e)[t]}class de{constructor(e={}){if(!J(e))throw TypeError("JWT Claims Set MUST be an object");(Dr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Mt("iss",e),ee(this).iss=e,this}setSubject(e){return Mt("sub",e),ee(this).sub=e,this}setAudience(e){return Jn(e),ee(this).aud=e,this}setJti(e){return Mt("jti",e),ee(this).jti=e,this}setNotBefore(e){return ee(this).nbf=$t(e,"setNotBefore"),this}setExpirationTime(e){return ee(this).exp=$t(e,"setExpirationTime"),this}setIssuedAt(e){let t=ee(this);if(e===void 0)t.iat=Ue(new Date);else if(typeof e==="string")t.iat=Ae("setIssuedAt",Ue(new Date)+ht(e));else t.iat=$t(e,"setIssuedAt");return this}}async function F(e,t,n){let o=await Or(e,Ir(n),t);if(!o[2])throw new x("JWTs MUST NOT use unencoded payload");let c={payload:xe(o[1],o[0],n),protectedHeader:o[1]};if(typeof t==="function")return{...c,key:o[3]};return c}async function Re(e,t,n){let o=await Kr(e,xr(n),t),i=o[1],c=xe(i,o[0],n);for(let p of["iss","sub","aud"])if(i[p]!==void 0&&(p==="aud"?JSON.stringify(i.aud)!==JSON.stringify(c.aud):i[p]!==c[p]))throw new M(`replicated "${p}" claim header parameter mismatch`,c,p,"mismatch");let s={payload:c,protectedHeader:i};if(typeof t==="function")return{...s,key:o[2]};return s}function Cn(e){if(e===void 0)return[void 0,""];let t=Ee(S,e);return[t[0],g(t[1])]}function vn(e,t,n){return lt(S,e),ge(e,V(S,we,n,e,t))}function Tn(e){let t=e.alg;if(typeof t!=="string"||!t)throw new S('JWS "alg" (Algorithm) Header Parameter missing or invalid');return yt(t)}async function Pn(e,t,n,o){let i=v(K(e),K("."),t),c=await j(n,o,"sign");return g(await vr(n,c,i))}async function Ur(e,t,n,o,i){let[c,s]=Cn(t);if(!c)throw new S("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!vn(c,c,n))i();let d=Tn(c),f=g(e),u=await Pn(s,K(f),d,o);return`${s}.${f}.${u}`}var In=de;class Te extends In{#e;setProtectedHeader(e){return ce(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return Ur(Ke(this),this.#e,t?.crit,e,()=>{throw new x("JWTs MUST NOT use unencoded payload")})}}var On=de;class Fe extends On{#e;#r;#n;#t;#o;#i;#a;setProtectedHeader(e){return ce(this.#t,"setProtectedHeader"),this.#t=e,this}setKeyManagementParameters(e){return ce(this.#n,"setKeyManagementParameters"),this.#n=e,this}setContentEncryptionKey(e){return ce(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return ce(this.#r,"setInitializationVector"),this.#r=e,this}replicateIssuerAsHeader(){return this.#o=!0,this}replicateSubjectAsHeader(){return this.#i=!0,this}replicateAudienceAsHeader(){return this.#a=!0,this}async encrypt(e,t){let n=Ke(this);if(this.#t&&(this.#o||this.#i||this.#a))this.#t={...this.#t,iss:this.#o?wt(this,"iss"):void 0,sub:this.#i?wt(this,"sub"):void 0,aud:this.#a?wt(this,"aud"):void 0};let o=await Wr([n,this.#t,void 0,void 0,void 0,this.#e,this.#r,this.#n,void 0,!1],e,t);return[o.protected,o.encrypted_key,o.iv,o.ciphertext,o.tag].join(".")}}var zt='"alg" (Algorithm)';function Vt(e='JWK "alg" (Algorithm) Parameter'){throw new w(`Invalid or unsupported ${e} value`)}function Ne(e,t){return(typeof e==="string"?De[e]??_t[e]:void 0)??Vt(t)}function gt(e){if(e!==void 0&&typeof e!=="boolean")throw TypeError('"extractable" option must be a boolean');return e}var ke=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},_n=(e)=>({data:e,pos:0}),Gt=(e)=>{let t=e.data[e.pos++];if(t===void 0)throw Error("Unexpected end of ASN.1 input");return t},Be=(e)=>{let t=Gt(e);if(t&128){let n=t&127,o=0;for(let i=0;i<n;i++)o=o<<8|Gt(e);return o}return t};var Me=(e,t,n)=>{if(Gt(e)!==t)throw Error(n)},Rr=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},Dn=(e)=>{Me(e,6,"Expected algorithm OID");let t=Be(e);return Rr(e,t)};function Un(e,t){if(Me(e,48,`Invalid ${t==="spki"?"SPKI":"PKCS#8"} structure`),Be(e),t==="pkcs8"){Me(e,2,"Expected version field");let n=Be(e);e.pos+=n}Me(e,48,"Expected algorithm identifier"),Be(e)}var Rn=(e)=>{let t=Dn(e);if(ke(t,[43,101,110]))return"X25519";if(!ke(t,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");Me(e,6,"Expected curve OID");let n=Be(e),o=Rr(e,n);if(ke(o,[42,134,72,206,61,3,1,7]))return"P-256";if(ke(o,[43,129,4,0,34]))return"P-384";if(ke(o,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")},Nn=async(e,t,n,o)=>{let i=gt(o?.extractable),c=Ne(n,zt);if(c.secret)Vt(zt);let s=e==="spki",p;if(c.resolve)try{let d=_n(t);Un(d,e),p=c.resolve({crv:Rn(d)})}catch{throw new w("Invalid or unsupported key format")}else p=c.subtle;return crypto.subtle.importKey(e,t,p,i??s,c.usages[s?0:1])},Hn=(e,t)=>rt(e.replace(t,"")),Nr=(e,t,n)=>{let o=Hn(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return Nn("pkcs8",o,t,n)};function kn(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Bn(e){if(Wt(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:g(e)};if(!q(e))throw TypeError(Y(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:n,alg:o,use:i,...c}=kn(await crypto.subtle.exportKey("jwk",e));if(c.kty==="AKP")c.alg=o;return c}function Hr(e){return Bn(e)}var te=(e,t)=>{if(typeof e!=="string"||!e)throw new Ge(`${t} missing or invalid`)};async function ve(e,t){let n;if(J(e)){if(n=le(e),typeof n.kty!=="string")throw TypeError(Y(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(qe(e))n=le(await Hr(e));else throw TypeError(Y(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(n.kty){case"AKP":te(n.alg,'"alg" (Algorithm) Parameter'),te(n.pub,'"pub" (Public key) Parameter'),o={alg:n.alg,kty:n.kty,pub:n.pub};break;case"EC":te(n.crv,'"crv" (Curve) Parameter'),te(n.x,'"x" (X Coordinate) Parameter'),te(n.y,'"y" (Y Coordinate) Parameter'),o={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case"OKP":te(n.crv,'"crv" (Subtype of Key Pair) Parameter'),te(n.x,'"x" (Public Key) Parameter'),o={crv:n.crv,kty:n.kty,x:n.x};break;case"RSA":te(n.e,'"e" (Exponent) Parameter'),te(n.n,'"n" (Modulus) Parameter'),o={e:n.e,kty:n.kty,n:n.n};break;case"oct":if(typeof n.k!=="string")throw new Ge('"k" (Key Value) Parameter missing or invalid');o={k:n.k,kty:n.kty};break;default:throw new w('"kty" (Key Type) Parameter missing or unsupported')}let i=K(JSON.stringify(o));return g(await ot(t,i))}function Mn(e,t,n,o){let{kty:i,key_ops:c,ext:s,kid:p,alg:d,use:f,crv:u}=le(e),m=Array.isArray(c)?[...c]:c;return(s===void 0||typeof s==="boolean")&&(m===void 0||Array.isArray(m)&&m.every((y,P)=>typeof y==="string"&&m.indexOf(y)===P)&&m.includes("verify"))&&t.kty.includes(i)&&(o===void 0||typeof o==="string"&&o===p)&&(d===void 0?i!=="AKP":n===d)&&(f===void 0||f==="sig")&&(!t.crv||u===t.crv)}async function kr(e,t,n){let o=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(o[i]===void 0){let c=await Q(n,{...t,alg:i,ext:!0});if(c.type!=="public")throw new Xe("JSON Web Key Set members must be public keys");o[i]=c}return o[i]}function Ze(e){let t;try{t=structuredClone(e)}catch{}if(!nt(t))throw new Xe("JSON Web Key Set malformed");let n=new WeakMap;return Object.defineProperty(async(i,c)=>{let{alg:s,kid:p}={...i,...c?.header},d=typeof s==="string"?De[s]:void 0;if(!d||d.secret)throw new w('Unsupported "alg" value for a JSON Web Key Set');let f=t.keys.filter((y)=>Mn(y,d,s,p)),{0:u,length:m}=f;if(!m)throw new Ce;if(m!==1){let y=new xt;throw y[Symbol.asyncIterator]=async function*(){for(let P of f)try{yield await kr(n,P,d)}catch{}},y}return kr(n,u,d)},"jwks",{value:()=>structuredClone(t)})}function $n(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var Ft;if(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))Ft="jose/v6.2.10";var Mr=Symbol();async function Ln(e,t,n,o=fetch){let i=await o(e,{method:"GET",signal:n,redirect:"manual",headers:t}).catch((c)=>{if(c.name==="TimeoutError")throw new Kt;throw c});if(i.status!==200)throw new T("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new T("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var $r=Symbol();function $e(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Br(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==="number"?e:t}function He(e,t){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");let n=new URL(e.href).href,o=t??{},i=o.timeoutDuration;if(typeof i==="number"&&(!Number.isInteger(i)||i<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let c=typeof i==="number"?i:5000,s=Br(o.cooldownDuration,30000,"cooldownDuration"),p=Br(o.cacheMaxAge,600000,"cacheMaxAge"),d=new Headers(o.headers);if(Ft&&!d.has("User-Agent"))d.set("User-Agent",Ft);if(!d.has("accept"))d.set("accept","application/json, application/jwk-set+json");let f=o[Mr],u=o[$r],m,y,P=0,R=0,A;if(u&&typeof u==="object"){let{uat:E,jwks:I}=u;if($e(E,p)&&nt(I))m=E,A=Ze(I)}let b=async()=>{if(y&&$n())y=void 0;if(!y){let E=++P,I=y=Ln(n,d,AbortSignal.timeout(c),f).then((N)=>{let G=Ze(N);if(E<=R)return;A=G;let B=Date.now();if(u)u.uat=B,u.jwks=N;m=B,R=E}).finally(()=>{if(y===I)y=void 0})}await y};return Object.defineProperties(async(E,I)=>{if(!A||!$e(m,p))await b();try{return await A(E,I)}catch(N){if(N instanceof Ce&&!$e(m,s))return await b(),A(E,I);throw N}},{coolingDown:{get:()=>$e(m,s),enumerable:!0},fresh:{get:()=>$e(m,p),enumerable:!0},reload:{value:b,enumerable:!0},reloading:{get:()=>!!y,enumerable:!0},jwks:{value:()=>A?.jwks(),enumerable:!0}})}var jn=de;class at extends jn{encode(){let e=g(JSON.stringify({alg:"none"})),t=g(Ke(this));return`${e}.${t}.`}static decode(e,t){if(typeof e!=="string")throw new x("Unsecured JWT must be a string");let{0:n,1:o,2:i,length:c}=e.split(".");if(c!==3||i!=="")throw new x("Invalid Unsecured JWT");let s,p;try{s=ne(n,S,"JWS Protected Header is invalid");let f=V(S,we,void 0,s,s);p=ge(s,f)}catch(f){if(!(f instanceof S))throw f;throw new x("Invalid Unsecured JWT",{cause:f})}if(s.alg!=="none")throw new x("Invalid Unsecured JWT");if(!p)throw new x("JWTs MUST NOT use unencoded payload");return{payload:xe(s,_(o,"payload",x),t),header:s}}}async function ct(e,t,n){if(typeof e!=="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw TypeError('"pkcs8" must be PKCS#8 formatted string');return Nr(e,t,n)}async function W(e,t,n){if(!J(e))throw TypeError("JWK must be an object");let o=it(e),i=gt(n?.extractable),{alg:c}=o;t??=c;let s=i??o.ext;if(o.kty!=="oct"&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!=="string")throw TypeError('missing "k" (Key Value) Parameter value');return L(o.k);case"AKP":{if(typeof c!=="string"||!c)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==c)throw TypeError("JWK alg and alg option value mismatch");return Q(Ne(t),{...o,ext:s})}case"RSA":case"EC":case"OKP":return Q(Ne(t),{...o,alg:t,ext:s});default:throw new w('Unsupported "kty" (Key Type) Parameter value')}}function k(e){let t;if(typeof e==="string"){let o=e.split(".");if(o.length===3||o.length===5)[t]=o}else if(typeof e==="object"&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");let n="Invalid Token or Protected Header formatting";if(typeof t!=="string"||!t)throw TypeError(n);return ne(t,TypeError,n)}function C(e){if(typeof e!=="string")throw new x("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:n}=e.split(".");if(n===5)throw new x("Only JWTs using Compact JWS serialization can be decoded");if(n!==3)throw new x("Invalid JWT");if(!t)throw new x("JWTs must contain a payload");let o;try{o=L(t)}catch{throw new x("Failed to base64url decode the payload")}let i;try{i=JSON.parse(fe.decode(o))}catch{throw new x("Failed to parse the decoded payload as JSON")}if(!J(i))throw new x("Invalid JWT Claims Set");return i}export{h,r,O,a,he,g,et,F,Re,Te,Fe,ve,Ze,He,at,ct,W,k,C};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{a}from"./chunk-kvt13jb9.js";var n=null;function c(e){if(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)return;if(n===null){n=new Map;try{let{readFileSync:t}=a("fs"),s=t("/proc/self/environ","utf-8");for(let r of s.split("\x00")){let o=r.indexOf("=");if(o>0)n.set(r.slice(0,o),r.slice(o+1))}}catch{}}return n.get(e)}function f(e,t){return t?.[e]||(typeof process<"u"?process.env[e]:void 0)||c(e)||void 0}
|
|
3
|
+
export{f};
|