@shumai-one/shumai 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-adekdctx.css → chunk-0ccg9ddn.css} +1 -1
- package/bin/chunk-0e4wawpq.js +2 -0
- package/bin/chunk-185qefn1.js +2 -0
- package/bin/chunk-1kw2mbqb.js +1 -0
- package/bin/chunk-1wm6ptdx.js +1 -0
- package/bin/chunk-1yacmegc.js +2 -0
- package/bin/chunk-2291ehh5.js +3 -0
- package/bin/chunk-2520aq8j.js +2 -0
- package/bin/chunk-29zdp63z.js +3 -0
- package/bin/chunk-2yxj593j.js +2 -0
- package/bin/chunk-32pcmaqm.js +3 -0
- package/bin/chunk-3a13dcs1.js +1 -0
- package/bin/chunk-3cyrcgm5.js +13 -0
- package/bin/chunk-3swpwb9v.js +1 -0
- package/bin/chunk-3wmcx2bv.js +2 -0
- package/bin/chunk-4r81ghg8.js +2 -0
- package/bin/chunk-4v5n0ayb.js +2 -0
- package/bin/chunk-5a8nt4me.js +1 -0
- package/bin/chunk-66hsjnw6.js +2 -0
- package/bin/chunk-6bhn1p8v.js +211 -0
- package/bin/chunk-6gg1ymer.js +2 -0
- package/bin/chunk-70c3xrgd.js +2 -0
- package/bin/chunk-7esm0hqb.js +2 -0
- package/bin/chunk-7fst8kdw.js +12 -0
- package/bin/chunk-83e12sjg.js +3 -0
- package/bin/chunk-87zxtf66.js +3 -0
- package/bin/chunk-8fmy5jtp.js +2 -0
- package/bin/chunk-8zqgaxvv.js +1 -0
- package/bin/chunk-9t1ne8xr.js +2 -0
- package/bin/chunk-a32vreya.js +2 -0
- package/bin/chunk-a3dmtt2j.js +1 -0
- package/bin/chunk-abt0azmv.js +2 -0
- package/bin/chunk-ag6p3mbf.js +2 -0
- package/bin/chunk-aqbrzx9z.js +1 -0
- package/bin/chunk-av1a8fqp.js +3 -0
- package/bin/chunk-awfwk64v.js +2 -0
- package/bin/chunk-b235azv4.js +45 -0
- package/bin/chunk-b9yrw9et.js +10 -0
- package/bin/chunk-bay038pj.js +2 -0
- package/bin/chunk-c007p0t8.js +299 -0
- package/bin/chunk-cak32x57.js +2 -0
- package/bin/chunk-ce8m4zeg.js +3 -0
- package/bin/chunk-ck8azecb.js +12 -0
- package/bin/chunk-cnxwmycy.js +6 -0
- package/bin/chunk-cqb415s6.js +5 -0
- package/bin/chunk-e2mvmq2m.js +1 -0
- package/bin/chunk-e7mqtkzn.js +2 -0
- package/bin/chunk-e99dv20z.js +3 -0
- package/bin/chunk-ea79xnn3.js +2 -0
- package/bin/chunk-ehc9adfz.js +2 -0
- package/bin/chunk-ejbvfj4r.js +1 -0
- package/bin/chunk-ekfem7kf.js +1 -0
- package/bin/chunk-etwkk0xh.js +1 -0
- package/bin/chunk-evrdd32b.js +2 -0
- package/bin/chunk-f15qyp41.js +1 -0
- package/bin/chunk-f3ehv01n.js +54 -0
- package/bin/chunk-fm6p03ad.js +2 -0
- package/bin/chunk-fxswt9hc.js +3 -0
- package/bin/chunk-fyha3r13.js +2 -0
- package/bin/chunk-g0vs7k2x.js +1 -0
- package/bin/chunk-g84z2w7v.js +16 -0
- package/bin/chunk-gk3eqd50.js +2 -0
- package/bin/chunk-h3tbf521.js +2 -0
- package/bin/chunk-h837fyed.js +2 -0
- package/bin/chunk-hfh0c082.js +2 -0
- package/bin/chunk-j20e0qsw.js +7 -0
- package/bin/chunk-j8fxp8ej.js +2 -0
- package/bin/chunk-jje8nj8h.js +3 -0
- package/bin/chunk-jy006gcv.js +7 -0
- package/bin/chunk-k7hss0bd.js +4 -0
- package/bin/chunk-m7m9d4fb.js +2 -0
- package/bin/chunk-n1jwdb0a.js +1 -0
- package/bin/chunk-p5gf1zdm.js +4 -0
- package/bin/chunk-pb1zf0vb.js +2 -0
- package/bin/chunk-pfgxggaj.js +11 -0
- package/bin/chunk-q16490pv.js +2 -0
- package/bin/chunk-q2bvyv39.js +8 -0
- package/bin/chunk-qf24e71w.js +2 -0
- package/bin/chunk-qh81zhg1.js +1 -0
- package/bin/chunk-qwp3kwbz.js +2 -0
- package/bin/chunk-qwqvt9v6.js +2 -0
- package/bin/chunk-qydeqgyj.js +5 -0
- package/bin/chunk-r7dty1tg.js +2 -0
- package/bin/chunk-rbj4fad9.js +32 -0
- package/bin/chunk-rhdxwebf.js +2 -0
- package/bin/chunk-rhh716z0.js +42 -0
- package/bin/chunk-rpywcvg1.js +3 -0
- package/bin/chunk-rza4ae5z.js +3 -0
- package/bin/chunk-sfx2588q.js +3 -0
- package/bin/chunk-sk4e6rb1.js +1 -0
- package/bin/chunk-t2n1dbgx.js +4 -0
- package/bin/chunk-tf28796q.js +2 -0
- package/bin/chunk-twdxayky.js +3 -0
- package/bin/chunk-v9b3w8q5.js +3 -0
- package/bin/chunk-v9w25rp2.js +2 -0
- package/bin/chunk-vgn5zcpv.js +3 -0
- package/bin/chunk-wfzqnpc1.js +3 -0
- package/bin/chunk-wry2hvrq.js +24 -0
- package/bin/chunk-x8f4defx.js +3 -0
- package/bin/chunk-xp59apdb.js +2 -0
- package/bin/chunk-xtf3c29c.css +1 -0
- package/bin/chunk-z3gkt8w1.js +3 -0
- package/bin/chunk-zehyn6vd.js +2 -0
- package/bin/chunk-zh6fqq44.js +1 -0
- package/bin/chunk-zmv8cg4s.js +8 -0
- package/bin/chunk-zqv0zhfb.js +3 -0
- package/bin/{pdf.worker.min-szxdj13d.mjs → pdf.worker.min-vf48er29.mjs} +14423 -13889
- package/bin/shumai-app.html +1 -1
- package/bin/shumai-app.js +626 -460
- 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-07h4b77v.js +0 -2
- package/bin/chunk-0t4n4d5w.js +0 -4
- package/bin/chunk-1611z9jg.js +0 -2
- package/bin/chunk-1phqxp6z.js +0 -3
- package/bin/chunk-23hckrrz.js +0 -2
- package/bin/chunk-30z44j1g.js +0 -2
- package/bin/chunk-3j463k1g.js +0 -1
- package/bin/chunk-4181tdds.js +0 -14
- package/bin/chunk-480jtqng.js +0 -4
- package/bin/chunk-4c3g146q.js +0 -2
- package/bin/chunk-4ca0zt5e.js +0 -1
- package/bin/chunk-4d9bgmf2.js +0 -2
- package/bin/chunk-4ev56fss.js +0 -9
- package/bin/chunk-4gk52tjq.js +0 -45
- package/bin/chunk-4mdqkj4d.js +0 -1
- package/bin/chunk-4r91fggc.js +0 -2
- package/bin/chunk-50fb1x3w.js +0 -1
- package/bin/chunk-59gj1njz.js +0 -1
- package/bin/chunk-5pr0t7fb.js +0 -2
- package/bin/chunk-5vewxmz7.js +0 -3
- package/bin/chunk-62zx96pe.js +0 -2
- package/bin/chunk-63y0eb07.js +0 -2
- package/bin/chunk-6d5xrgfx.js +0 -2
- package/bin/chunk-6gbtz5bf.js +0 -67
- package/bin/chunk-6gjg5egq.js +0 -3
- package/bin/chunk-6m4jz9s1.js +0 -44
- package/bin/chunk-6s4x525w.js +0 -2
- package/bin/chunk-6w2wmvqs.js +0 -3
- package/bin/chunk-77d23vcn.js +0 -2
- package/bin/chunk-77m5p188.js +0 -2
- package/bin/chunk-7bvx087f.js +0 -1
- package/bin/chunk-7pfjfrjg.js +0 -5
- package/bin/chunk-7q10s127.js +0 -4
- package/bin/chunk-7thx8ctx.js +0 -3
- package/bin/chunk-8t4s91gh.js +0 -2
- package/bin/chunk-98ey5p2e.js +0 -3
- package/bin/chunk-9amndcyh.js +0 -6
- package/bin/chunk-9bk23g9x.js +0 -1
- package/bin/chunk-9mkcfy43.js +0 -1
- package/bin/chunk-9t3nsq5n.js +0 -2
- package/bin/chunk-9tjq99ds.js +0 -2
- package/bin/chunk-9wm9rwh1.js +0 -2
- package/bin/chunk-ab16fyg4.js +0 -4
- package/bin/chunk-arv0g2av.js +0 -1
- package/bin/chunk-aytj4zxg.js +0 -3
- package/bin/chunk-b1ypjqgp.js +0 -2
- package/bin/chunk-bdjv0ykq.js +0 -2
- package/bin/chunk-c1k86mfa.js +0 -10
- package/bin/chunk-caa96dgd.js +0 -2
- package/bin/chunk-ce4v2yjy.js +0 -1
- package/bin/chunk-cqh60y54.js +0 -3
- package/bin/chunk-cvq7zgw7.js +0 -1
- package/bin/chunk-d9mjbtp2.js +0 -2
- package/bin/chunk-dn7sbjws.js +0 -3
- package/bin/chunk-dxyq9h8n.js +0 -3
- package/bin/chunk-e3cabksx.js +0 -3
- package/bin/chunk-egcrbj94.js +0 -2
- package/bin/chunk-ev17v1mv.js +0 -2
- package/bin/chunk-evtpwg71.js +0 -2
- package/bin/chunk-f3e0nsv2.js +0 -2
- package/bin/chunk-f40gjqpq.js +0 -2
- package/bin/chunk-fe7822ak.js +0 -299
- package/bin/chunk-g8tkhw9j.js +0 -2
- package/bin/chunk-g9r0p4t8.js +0 -2
- package/bin/chunk-gbjyh9ms.js +0 -1
- package/bin/chunk-gtbsb39v.js +0 -3
- package/bin/chunk-gytz1q13.js +0 -13
- package/bin/chunk-h0fxysxs.js +0 -7
- package/bin/chunk-h8bdvsqt.js +0 -2
- package/bin/chunk-hag024w8.js +0 -2
- package/bin/chunk-hc6w5nw4.js +0 -7
- package/bin/chunk-j69dqc48.js +0 -2
- package/bin/chunk-jbtw1zym.js +0 -8
- package/bin/chunk-jc1vb7rj.js +0 -5
- package/bin/chunk-jdv78w9r.js +0 -2
- package/bin/chunk-jjs70y9v.js +0 -3
- package/bin/chunk-jmdar2gz.js +0 -2
- package/bin/chunk-jvwz10n4.js +0 -2
- package/bin/chunk-k47md1g4.js +0 -2
- package/bin/chunk-k4v0brcb.js +0 -2
- package/bin/chunk-k6n7c07e.js +0 -1
- package/bin/chunk-kk2cstsg.js +0 -2
- package/bin/chunk-knz4h56q.js +0 -12
- package/bin/chunk-kqqtt6bd.js +0 -3
- package/bin/chunk-kvyp1t4j.js +0 -7
- package/bin/chunk-kxskpgsq.js +0 -5
- package/bin/chunk-m6srbjcs.js +0 -2
- package/bin/chunk-mcc1scxs.js +0 -12
- package/bin/chunk-mq83a0kk.js +0 -2
- package/bin/chunk-mxm8g4q0.js +0 -1
- package/bin/chunk-nhpgdqq5.js +0 -2
- package/bin/chunk-nne496aa.js +0 -2
- package/bin/chunk-nqpb0r9h.js +0 -11
- package/bin/chunk-ns0zww9g.js +0 -2
- package/bin/chunk-ps4xfp23.js +0 -2
- package/bin/chunk-pz2ec6xt.js +0 -2
- package/bin/chunk-q163k309.js +0 -2
- package/bin/chunk-q1da61ps.js +0 -1
- package/bin/chunk-qrf0ady6.js +0 -68
- package/bin/chunk-qy28f25e.js +0 -2
- package/bin/chunk-r7s4ypw1.js +0 -2
- package/bin/chunk-ran23vm9.js +0 -1
- package/bin/chunk-rfvdc4n0.js +0 -2
- package/bin/chunk-rgthkvgx.js +0 -3
- package/bin/chunk-s39n3yw3.js +0 -2
- package/bin/chunk-s7wdd0g7.js +0 -8
- package/bin/chunk-s88ha5kx.js +0 -3
- package/bin/chunk-sf91bt9m.js +0 -2
- package/bin/chunk-sjwbjf9j.js +0 -2
- package/bin/chunk-t62076pv.js +0 -1
- package/bin/chunk-tbbwss3v.js +0 -3
- package/bin/chunk-tjcc7a6y.js +0 -24
- package/bin/chunk-tp6ab26e.js +0 -2
- package/bin/chunk-v2wxk9p5.js +0 -4
- package/bin/chunk-vbk6y4hk.js +0 -2
- package/bin/chunk-vfgfg5fk.js +0 -2
- package/bin/chunk-vm6c3xx9.js +0 -2
- package/bin/chunk-vsx96mt6.js +0 -3
- package/bin/chunk-wbyw1shz.js +0 -6
- package/bin/chunk-whh2vh50.css +0 -1
- package/bin/chunk-wjkcq65s.js +0 -2
- package/bin/chunk-wkefwkfp.js +0 -41
- package/bin/chunk-x7bsnk1e.js +0 -2
- package/bin/chunk-xbhw6bpz.js +0 -3
- package/bin/chunk-xg5yrcj5.js +0 -2
- package/bin/chunk-xg9xscqz.js +0 -1
- package/bin/chunk-xw2gpcsh.js +0 -3
- package/bin/chunk-ycq8ank7.js +0 -2
- package/bin/chunk-yp9hvkc5.js +0 -73
- package/bin/chunk-ytypyfkc.js +0 -65
- package/bin/chunk-z1kjmf60.js +0 -2
- package/bin/chunk-z36bx86r.js +0 -2
- package/bin/chunk-z7hdnecp.js +0 -3
- package/bin/chunk-zeby1cq7.js +0 -2
- package/bin/chunk-zs5e8z1w.js +0 -1
- package/bin/chunk-zxnyefg5.js +0 -2
- /package/bin/{chunk-24ke0th1.css → chunk-kegybs91.css} +0 -0
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Tn}from"./chunk-v9b3w8q5.js";var r=/"/g,n=/[\\'"]/g;class Oi extends Tn{visitOrAction(e){this.append("or "),this.append(e.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(e){return e.replace(r,'""')}sanitizeJSONPathMemberValue(e){return e.replace(n,(t)=>t==="\\"?"\\\\":t==="'"?"''":"\\\"")}visitDefaultInsertValue(e){this.append("null")}}class Pa{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class Di extends Pa{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}}
|
|
3
|
+
export{Pa,Oi,Di};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var k=Object.create;var{getPrototypeOf:l,defineProperty:f,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,Ke=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?k(l(a)):{};let e=b||!a||!a.__esModule||!j.call(a,"default")?f(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of m(a))if(!j.call(e,g))f(e,g,{get:n.bind(a,g),enumerable:!0})}if(d)h.set(a,e);return e};var w=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var Ne=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var zp=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var Fp=(a)=>JSON.parse(a);var jp=(a,b,c)=>{for(var d in b)f(a,d,{get:b[d],set:c[d],enumerable:!0,configurable:!0})},W=import.meta.require;
|
|
3
|
+
export{Ke,w,Ne,zp,Fp,jp,W};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{W}from"./chunk-rza4ae5z.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}=W("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 nr(e,t){return t?.[e]||(typeof process<"u"?process.env[e]:void 0)||c(e)||void 0}
|
|
3
|
+
export{nr};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h,C,t,L,Ue,A,st,yt,Ap}from"./chunk-6bhn1p8v.js";import"./chunk-3wmcx2bv.js";import"./chunk-j20e0qsw.js";import"./chunk-ehc9adfz.js";import"./chunk-b9yrw9et.js";import"./chunk-6gg1ymer.js";import"./chunk-bay038pj.js";import"./chunk-7esm0hqb.js";import"./chunk-q16490pv.js";import"./chunk-k7hss0bd.js";import"./chunk-c007p0t8.js";import"./chunk-cqb415s6.js";import{Zn}from"./chunk-185qefn1.js";import{Wt}from"./chunk-rhdxwebf.js";import"./chunk-4r81ghg8.js";import"./chunk-gk3eqd50.js";import"./chunk-ag6p3mbf.js";import"./chunk-9t1ne8xr.js";import"./chunk-m7m9d4fb.js";import"./chunk-1yacmegc.js";import"./chunk-r7dty1tg.js";import"./chunk-2yxj593j.js";import"./chunk-ea79xnn3.js";C();function l(){let{projectId:o}=c.useParams(),{teamId:r,ensureTeamIdForProject:a}=st();h(()=>{a(o)},[o,a]);let{data:s}=Wt(Ap(o)),e=s?.rootFolder,{data:i}=L({queryKey:["folders",e],queryFn:async()=>{let n=await A.api.folders[":folderId"].$get({param:{folderId:e}});if(!n.ok)throw Error("failed to fetch folder");return await n.json()},enabled:!!e});if(!r||!e||!i)return t(yt,{});return t(Zn,{teamId:r,projectId:o,projectName:s.name??"",assetId:e,rootFolderId:e})}var c=Ue("/projects/$projectId/")({component:l});export{c as Route};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Nr,Da,Zd,e,m,d,x,z,s,r,I,y,l,a}from"./chunk-f3ehv01n.js";function c(t,n){let o={};if(!Object.keys(n).length)return o=t,o;for(let[u,i]of Object.entries(t)){let p=n[u];if(p===null)continue;o[p??u]=i}return o}function _(t){let n={};for(let[o,u]of Object.entries(t))if(typeof u<"u")n[o]=u;return n}class j extends Error{rawValue;rawMessage;static[Symbol.hasInstance](t){if(!(t instanceof Error))return!1;if(!("rawValue"in t))return!1;if(!("rawMessage"in t))return!1;if(!("pretty"in t))return!1;if(typeof t.pretty!=="function")return!1;return!0}constructor(t,n,o){super(`${t}: ${n}`);this.name="SDKValidationError",this.cause=n,this.rawValue=o,this.rawMessage=t}pretty(){if(this.cause instanceof Da)return`${this.rawMessage}
|
|
3
|
+
${Id(this.cause)}`;else return this.toString()}}function Id(t){return Zd(t)}function Ys(t){return{ok:!0,value:t}}function Bo(t){return{ok:!1,error:t}}async function k(t){let n=await t;if(!n.ok)throw n.error;return n.value}function b(t,n,o){try{return Ys(n(t))}catch(u){return Bo(new j(o,u,t))}}var Ro=r({prompt_tokens:m().default(0),completion_tokens:m().default(0),total_tokens:m().default(0),prompt_audio_seconds:a(m()).optional()}).catchall(x()).transform((t)=>c(t,{prompt_tokens:"promptTokens",completion_tokens:"completionTokens",total_tokens:"totalTokens",prompt_audio_seconds:"promptAudioSeconds"})),kl=r({promptTokens:m().default(0),completionTokens:m().default(0),totalTokens:m().default(0),promptAudioSeconds:a(m()).optional()}).catchall(x()).transform((t)=>({...c(t,{promptTokens:"prompt_tokens",completionTokens:"completion_tokens",totalTokens:"total_tokens",promptAudioSeconds:"prompt_audio_seconds"})}));function w(t){return N++,t}var N=0,A=0;function J(){A++;let t=N;return{end:(n)=>{let o=N-t;if(N=t+(n??o),--A===0)N=0;return o}}}function Y(t){let n=Object.values(t);return I([...n.map((o)=>l(o)),e().transform((o)=>w(o))])}function Ei(t){let n=Object.values(t).filter((o)=>typeof o==="number");return I([...n.map((o)=>l(o)),m().transform((o)=>w(o))])}function lt(t){return e()}function Tp(t){return m()}var v=Symbol("UNKNOWN");function P(t){return typeof t==="object"&&t!==null&&v in t}function $e(t,n,o={}){let{unknownValue:u="UNKNOWN",outputPropertyName:i}=o;return z().transform((p)=>{let h=Object.defineProperties({raw:p,[i??t]:u,isUnknown:!0},{[v]:{value:!0,enumerable:!1,configurable:!1}});if(!(typeof p==="object"&&p!==null))return h;let g=p[t];if(typeof g!=="string")return h;if(!(g in n))return h;let U=n[g];if(!U)return h;let C=J(),O=U.safeParse(p);if(!O.success)return C.end(0),h;if(C.end(),i)O.data[i]=g;return O.data})}var K=/^\d{4}-\d{2}-\d{2}$/;class T{serialized;static today(){return new T(new Date)}constructor(t){if(typeof t==="string"&&!K.test(t))throw RangeError("RFCDate: date strings must be in the format YYYY-MM-DD: "+t);let n=new Date(t);if(isNaN(+n))throw RangeError("RFCDate: invalid date provided: "+t);if(this.serialized=n.toISOString().slice(0,10),!K.test(this.serialized))throw TypeError(`RFCDate: failed to build valid date with given value: ${t} serialized to ${this.serialized}`)}toJSON(){return this.toString()}toString(){return this.serialized}}function M(t){return z().transform((n,o)=>{let u=[],i=t.map(()=>[]),p=J();for(let[S,g]of t.entries()){let U=J(),C=g.safeParse(n),O=U.end(),ie=0;if(C.success){u.push({data:C.data,inexactCount:O,zeroDefaultCount:0,fieldCount:-1});continue}i[S].push(...C.error.issues)}if(u.length===0)return p.end(0),o.addIssue({input:n,code:"invalid_union",errors:i}),Nr;let h=u[0];for(let S of u){if(u.length>1)S.fieldCount=ne(S.data);h=te(S,h)}return p.end(h.inexactCount),h.data})}function te(t,n){let o=t.inexactCount===0,u=n.inexactCount===0;if(o!==u)return o?t:n;let i=t.fieldCount-t.zeroDefaultCount,p=n.fieldCount-n.zeroDefaultCount;if(i!==p)return i>p?t:n;return t.inexactCount<n.inexactCount?t:n}function ne(t){let n=0,o=[t],u=0;while(u<o.length){let i=o[u++];if(i===void 0||P(i))continue;let p=typeof i;if(i===null||p==="number"||p==="string"||p==="boolean"||p==="bigint"||i instanceof Date||i instanceof T){n++;continue}if(Array.isArray(i)){o.push(...i);continue}if(p==="object")o.push(...Object.values(i))}return n}var B=r({type:l("input_audio"),input_audio:e()}).transform((t)=>c(t,{input_audio:"inputAudio"})),V=r({type:l("input_audio"),inputAudio:e()}).transform((t)=>c(t,{inputAudio:"input_audio"}));var fs=r({type:l("document_url").default("document_url"),document_url:e(),document_name:a(e()).optional()}).transform((t)=>c(t,{document_url:"documentUrl",document_name:"documentName"})),Ia=r({type:l("document_url").default("document_url"),documentUrl:e(),documentName:a(e()).optional()}).transform((t)=>c(t,{documentUrl:"document_url",documentName:"document_name"}));var W=r({type:l("file").default("file"),file_id:e()}).transform((t)=>c(t,{file_id:"fileId"})),Ml=r({type:l("file").default("file"),fileId:e()}).transform((t)=>c(t,{fileId:"file_id"}));var Z={Low:"low",Auto:"auto",High:"high"},q=Y(Z),G=lt(Z);var E=r({url:e(),detail:a(q).optional()}),L=r({url:e(),detail:a(G).optional()});var Ee=M([E,e()]),Le=M([L,e()]);var ps=r({type:l("image_url").default("image_url"),image_url:M([E,e()])}).transform((t)=>c(t,{image_url:"imageUrl"})),Ta=r({type:l("image_url").default("image_url"),imageUrl:M([L,e()])}).transform((t)=>c(t,{imageUrl:"image_url"}));var Me=M([m(),e()]),Ke=M([m(),e()]);var R=r({type:l("reference").default("reference"),reference_ids:s(M([m(),e()]))}).transform((t)=>c(t,{reference_ids:"referenceIds"})),F=r({type:l("reference").default("reference"),referenceIds:s(M([m(),e()]))}).transform((t)=>c(t,{referenceIds:"reference_ids"}));var Uo=r({type:l("text").default("text"),text:e()}),zo=r({type:l("text").default("text"),text:e()});var H={WebSearch:"web_search",WebSearchPremium:"web_search_premium",CodeInterpreter:"code_interpreter",ImageGeneration:"image_generation",DocumentLibrary:"document_library"},Jr=Y(H),Ma=lt(H);var qe=M([Jr,e()]),Ge=M([Ma,e()]);var Js=r({type:l("tool_reference").default("tool_reference"),tool:M([Jr,e()]),title:e(),url:a(e()).optional(),favicon:a(e()).optional(),description:a(e()).optional()}),Rl=r({type:l("tool_reference").default("tool_reference"),tool:M([Ma,e()]),title:e(),url:a(e()).optional(),favicon:a(e()).optional(),description:a(e()).optional()});var nt=M([Js,Uo,R]),ot=M([Rl,zo,F]);var ms=r({type:l("thinking").default("thinking"),thinking:s(M([Js,Uo,R])),signature:a(e()).optional(),closed:d().optional()}),hs=r({type:l("thinking").default("thinking"),thinking:s(M([Rl,zo,F])),signature:a(e()).optional(),closed:d().optional()});var Ii=$e("type",{image_url:ps.and(r({type:l("image_url")})),document_url:fs.and(r({type:l("document_url")})),text:Uo.and(r({type:l("text")})),reference:R.and(r({type:l("reference")})),file:W.and(r({type:l("file")})),thinking:ms.and(r({type:l("thinking")})),input_audio:B}),Ra=I([Ta.and(r({type:l("image_url")})),Ia.and(r({type:l("document_url")})),zo.and(r({type:l("text")})),F.and(r({type:l("reference")})),Ml.and(r({type:l("file")})),hs.and(r({type:l("thinking")})),V]);var zt=M([y(e(),x()),e()]),St=M([y(e(),x()),e()]);var Q=r({name:e(),arguments:M([y(e(),x()),e()])}),X=r({name:e(),arguments:M([y(e(),x()),e()])});var Gc=r({id:e().default("null"),type:e().optional(),function:Q,index:m().default(0)}),Mp=r({id:e().default("null"),type:e().optional(),function:X,index:m().default(0)});var Jt=M([e(),s(Ii)]);var $c=r({role:a(e()).optional(),content:a(M([e(),s(Ii)])).optional(),tool_calls:a(s(Gc)).optional(),tool_call_id:a(e()).optional(),index:a(m()).optional(),metadata:a(y(e(),x())).optional()}).transform((t)=>c(t,{tool_calls:"toolCalls",tool_call_id:"toolCallId"}));var oe={Stop:"stop",Length:"length",Error:"error",ToolCalls:"tool_calls"},re=Y(oe),ee=r({index:m(),delta:$c,finish_reason:a(re)}).transform((t)=>c(t,{finish_reason:"finishReason"}));var Td=r({id:e(),object:e().optional(),created:m().optional(),model:e(),usage:Ro.optional(),choices:s(ee)});function Rp(t){return b(t,(n)=>Td.parse(JSON.parse(n)),"Failed to parse 'CompletionChunk' from JSON")}
|
|
4
|
+
export{Id,Ys,Bo,k,b,c,_,Y,Ei,lt,Tp,$e,M,fs,Ia,Ml,ps,Ta,Uo,zo,Jr,Ma,Js,Rl,ms,hs,Ii,Ra,Gc,Mp,$c,Ro,kl,Td,Rp};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Se,oa}from"./chunk-7fst8kdw.js";function R(e,c){if(typeof e==="string"&&typeof c==="string")return e.toLowerCase()===c.toLowerCase();return e===c}function S(e,c){if(typeof e!=="string")return c.includes(e);return c.some((v)=>typeof v==="string"&&e.toLowerCase()===v.toLowerCase())}function W(e,c){return!S(e,c)}function T(e,c){if(typeof e!=="string"||typeof c!=="string")return!1;return e.toLowerCase().includes(c.toLowerCase())}function D(e,c){if(typeof e!=="string"||typeof c!=="string")return!1;return e.toLowerCase().startsWith(c.toLowerCase())}function k(e,c){if(typeof e!=="string"||typeof c!=="string")return!1;return e.toLowerCase().endsWith(c.toLowerCase())}var J=(e,c)=>{let v=null,E=oa({config:{adapterId:"memory",adapterName:"Memory Adapter",usePlural:!1,debugLogs:c?.debugLogs||!1,supportsArrays:!0,customTransformInput(h){if(h.options.advanced?.database?.generateId==="serial"&&h.field==="id"&&h.action==="create")return e[h.model].length+1;return h.data},transaction:async(h)=>{let L=structuredClone(e);try{return await h(E(v))}catch(M){throw Object.keys(e).forEach((C)=>{e[C]=L[C]}),M}}},adapter:({getFieldName:h,getDefaultFieldName:L,options:M,getModelName:C})=>{let I=(t,i,l)=>{if(!i)return t;return t.sort((o,f)=>{let y=h({model:l,field:i.field}),g=o[y],u=f[y],a=0;if(g==null&&u==null)a=0;else if(g==null)a=-1;else if(u==null)a=1;else if(typeof g==="string"&&typeof u==="string")a=g.localeCompare(u);else if(g instanceof Date&&u instanceof Date)a=g.getTime()-u.getTime();else if(typeof g==="number"&&typeof u==="number")a=g-u;else if(typeof g==="boolean"&&typeof u==="boolean")a=g===u?0:g?1:-1;else a=String(g).localeCompare(String(u));return i.direction==="asc"?a:-a})};function m(t,i,l,o){let f=(()=>{let u=e[i];if(!u)throw Se.error(`[MemoryAdapter] Model ${i} not found in the DB`,Object.keys(e)),Error(`Model ${i} not found`);let a=(n,p)=>{let{field:s,value:r,operator:O,mode:A="sensitive"}=p,w=A==="insensitive"&&(typeof r==="string"||Array.isArray(r)&&r.every((j)=>typeof j==="string"));switch(O){case"in":if(!Array.isArray(r))throw Error("Value must be an array");if(w)return S(n[s],r);return r.includes(n[s]);case"not_in":if(!Array.isArray(r))throw Error("Value must be an array");if(w)return W(n[s],r);return!r.includes(n[s]);case"contains":if(w)return T(n[s],r);return n[s]?.includes(r);case"starts_with":if(w)return D(n[s],r);return n[s].startsWith(r);case"ends_with":if(w)return k(n[s],r);return n[s].endsWith(r);case"ne":return w?!R(n[s],r):n[s]!==r;case"gt":return r!=null&&Boolean(n[s]>r);case"gte":return r!=null&&Boolean(n[s]>=r);case"lt":return r!=null&&Boolean(n[s]<r);case"lte":return r!=null&&Boolean(n[s]<=r);default:if(w)return R(n[s],r);if(r===null)return n[s]==null;return n[s]===r}},d=u.filter((n)=>{if(!t.length||t.length===0)return!0;let p=a(n,t[0]);for(let s of t){let r=a(n,s);if(s.connector==="OR")p=p||r;else p=p&&r}return p});if(o?.length&&o.length>0)d=d.map((n)=>Object.fromEntries(Object.entries(n).filter(([p])=>o.includes(L({model:i,field:p})))));return d})();if(!l)return f;let y=new Map,g=new Map;for(let u of f){let a=String(u.id);if(!y.has(a)){let n={...u};for(let[p,s]of Object.entries(l)){let r=C(p);if(s.relation==="one-to-one")n[r]=null;else n[r]=[],g.set(`${a}-${p}`,new Set)}y.set(a,n)}let d=y.get(a);for(let[n,p]of Object.entries(l)){let s=C(n),r=e[s];if(!r)throw Se.error(`[MemoryAdapter] JoinOption model ${s} not found in the DB`,Object.keys(e)),Error(`JoinOption model ${s} not found`);let O=r.filter((A)=>A[p.on.to]===u[p.on.from]);if(p.relation==="one-to-one")d[s]=O[0]||null;else{let A=g.get(`${a}-${n}`),w=p.limit??100,j=0;for(let b of O){if(j>=w)break;if(!A.has(b.id))d[s].push(b),A.add(b.id),j++}}}}return Array.from(y.values())}return{create:async({model:t,data:i})=>{if(M.advanced?.database?.generateId==="serial")i.id=e[C(t)].length+1;if(!e[t])e[t]=[];return e[t].push(i),i},findOne:async({model:t,where:i,select:l,join:o})=>{let f=m(i,t,o,l);if(o){let y=f;if(!y.length)return null;return y[0]}return f[0]||null},findMany:async({model:t,where:i,sortBy:l,limit:o,select:f,offset:y,join:g})=>{let u=m(i||[],t,g,f);if(g){let d=u;if(!d.length)return[];I(d,l,t);let n=d;if(y!==void 0)n=n.slice(y);if(o!==void 0)n=n.slice(0,o);return n}let a=I(u,l,t);if(y!==void 0)a=a.slice(y);if(o!==void 0)a=a.slice(0,o);return a||[]},count:async({model:t,where:i})=>{if(i)return m(i,t).length;return e[t].length},update:async({model:t,where:i,update:l})=>{let o=m(i,t);return o.forEach((f)=>{Object.assign(f,l)}),o[0]||null},delete:async({model:t,where:i})=>{let l=e[t],o=m(i,t);e[t]=l.filter((f)=>!o.includes(f))},deleteMany:async({model:t,where:i})=>{let l=e[t],o=m(i,t),f=0;return e[t]=l.filter((y)=>{if(o.includes(y))return f++,!1;return!o.includes(y)}),f},consumeOne:async({model:t,where:i})=>{let l=e[t],o=m(i,t)[0];if(!o)return null;return e[t]=l.filter((f)=>f!==o),o},updateMany({model:t,where:i,update:l}){let o=m(i,t);return o.forEach((f)=>{Object.assign(f,l)}),o[0]||null}}}});return(h)=>(v=h,E(h))};export{J as memoryAdapter};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function r(e){let t=e[e.length-1];return t&&t.role!=="user"?"agent":"user"}function ws(e){return e.some((t)=>{if(t.role==="user"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");if(t.role==="toolResult"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");return!1})}function xs(e){let t={"X-Initiator":r(e.messages),"Openai-Intent":"conversation-edits"};if(e.hasImages)t["Copilot-Vision-Request"]="true";return t}
|
|
3
|
+
export{ws,xs};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function Cn(i){return typeof i>"u"||i===void 0}function $t(i){return typeof i==="string"}function No(i){return typeof i==="number"}function sa(i){return typeof i==="boolean"}function Na(i){return i===null}function ru(i){return i instanceof Date}function Oa(i){return typeof i==="bigint"}function Np(i){return typeof Buffer<"u"&&Buffer.isBuffer(i)}function Qt(i){return typeof i==="function"}function vr(i){return typeof i==="object"&&i!==null}function f(i){return Object.freeze(i)}function Fl(i){if(En(i))return i;else return[i]}function En(i){return Array.isArray(i)}function Un(i){return i}var Op=["preserve rows","delete rows","drop"],In=f({is(i){return i.kind==="CreateTableNode"},create(i){return f({kind:"CreateTableNode",table:i,columns:f([])})},cloneWithColumn(i,t){return f({...i,columns:f([...i.columns,t])})},cloneWithConstraint(i,t){return f({...i,constraints:i.constraints?f([...i.constraints,t]):f([t])})},cloneWithFrontModifier(i,t){return f({...i,frontModifiers:i.frontModifiers?f([...i.frontModifiers,t]):f([t])})},cloneWithEndModifier(i,t){return f({...i,endModifiers:i.endModifiers?f([...i.endModifiers,t]):f([t])})},cloneWith(i,t){return f({...i,...t})}});var wr=f({is(i){return i.kind==="InsertQueryNode"},create(i,t,e){return f({kind:"InsertQueryNode",into:i,...t&&{with:t},replace:e})},createWithoutInto(){return f({kind:"InsertQueryNode"})},cloneWith(i,t){return f({...i,...t})}});class r{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#i=f({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=(i)=>{this.nodeStack.push(i),this.#i[i.kind](i),this.nodeStack.pop()}}var h=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],d=["+","-","*","/","%","^","&","|","#","<<",">>"],a=["->","->>"],l=[...h,...d,"&&","||"],c=["exists","not exists"],u=["not","-",...c],Dp=[...l,...a,...u,"between","between symmetric"],_o=f({is(i){return i.kind==="OperatorNode"},create(i){return f({kind:"OperatorNode",operator:i})}});function Dd(i){return $t(i)&&a.includes(i)}var bo=f({is(i){return i.kind==="ParensNode"},create(i){return f({kind:"ParensNode",node:i})}});var Zt=f({is(i){return i.kind==="RawNode"},create(i,t){return f({kind:"RawNode",sqlFragments:f(i),parameters:f(t)})},createWithSql(i){return Zt.create([i],[])},createWithChild(i){return Zt.create(["",""],[i])},createWithChildren(i){return Zt.create(Array(i.length+1).fill(""),i)}});var ze=f({is(i){return i.kind==="IdentifierNode"},create(i){return f({kind:"IdentifierNode",name:i})}});var sn=f({is(i){return i.kind==="SchemableIdentifierNode"},create(i){return f({kind:"SchemableIdentifierNode",identifier:ze.create(i)})},createWithSchema(i,t){return f({kind:"SchemableIdentifierNode",schema:ze.create(i),identifier:ze.create(t)})}});var Ho=f({is(i){return i.kind==="CreateViewNode"},create(i){return f({kind:"CreateViewNode",name:sn.create(i)})},cloneWith(i,t){return f({...i,...t})}});var nu=f({is(i){return i.kind==="SetOperationNode"},create(i,t,e){return f({kind:"SetOperationNode",operator:i,expression:t,all:e})}});var Oo=f({is(i){return i.kind==="WhenNode"},create(i){return f({kind:"WhenNode",condition:i})},cloneWithResult(i,t){return f({...i,result:t})}});var p=new Set;function qo(i){if(p.has(i))return;p.add(i),console.log(i)}var m=/'/g,N=/['"]/g;class Tn extends r{#i="";#t=[];get numParameters(){return this.#t.length}compileQuery(i,t){return this.#i="",this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(i),f({query:i,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#i}visitSelectQuery(i){let t=this.parentNode!==void 0&&!bo.is(this.parentNode)&&!wr.is(this.parentNode)&&!In.is(this.parentNode)&&!Ho.is(this.parentNode)&&!nu.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("select"),i.distinctOn)this.append(" "),this.compileDistinctOn(i.distinctOn);if(i.frontModifiers?.length)this.append(" "),this.compileList(i.frontModifiers," ");if(i.top)this.append(" "),this.visitNode(i.top);if(i.selections)this.append(" "),this.compileList(i.selections);if(i.from)this.append(" "),this.visitNode(i.from);if(i.joins)this.append(" "),this.compileList(i.joins," ");if(i.where)this.append(" "),this.visitNode(i.where);if(i.groupBy)this.append(" "),this.visitNode(i.groupBy);if(i.having)this.append(" "),this.visitNode(i.having);if(i.setOperations)this.append(" "),this.compileList(i.setOperations," ");if(i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(i.limit)this.append(" "),this.visitNode(i.limit);if(i.offset)this.append(" "),this.visitNode(i.offset);if(i.fetch)this.append(" "),this.visitNode(i.fetch);if(i.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...i.endModifiers])," ");if(t)this.append(")")}visitFrom(i){this.append("from "),this.compileList(i.froms)}visitSelection(i){this.visitNode(i.selection)}visitColumn(i){this.visitNode(i.column)}compileDistinctOn(i){this.append("distinct on ("),this.compileList(i),this.append(")")}compileList(i,t=", "){let e=i.length-1;for(let s=0;s<=e;s++)if(this.visitNode(i[s]),s<e)this.append(t)}visitWhere(i){this.append("where "),this.visitNode(i.where)}visitHaving(i){this.append("having "),this.visitNode(i.having)}visitInsertQuery(i){let t=this.parentNode!==void 0&&!bo.is(this.parentNode)&&!Zt.is(this.parentNode)&&!Oo.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append(i.replace?"replace":"insert"),i.ignore)qo("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(i.orAction)this.append(" "),this.visitNode(i.orAction);if(i.top)this.append(" "),this.visitNode(i.top);if(i.into)this.append(" into "),this.visitNode(i.into);if(i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");if(i.output)this.append(" "),this.visitNode(i.output);if(i.values)this.append(" "),this.visitNode(i.values);if(i.defaultValues)this.append(" "),this.append("default values");if(i.onConflict)this.append(" "),this.visitNode(i.onConflict);if(i.onDuplicateKey)this.append(" "),this.visitNode(i.onDuplicateKey);if(i.returning)this.append(" "),this.visitNode(i.returning);if(t)this.append(")");if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitValues(i){this.append("values "),this.compileList(i.values)}visitDeleteQuery(i){let t=this.parentNode!==void 0&&!bo.is(this.parentNode)&&!Zt.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("delete "),i.top)this.visitNode(i.top),this.append(" ");if(this.visitNode(i.from),i.output)this.append(" "),this.visitNode(i.output);if(i.using)this.append(" "),this.visitNode(i.using);if(i.joins)this.append(" "),this.compileList(i.joins," ");if(i.where)this.append(" "),this.visitNode(i.where);if(i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(i.limit)this.append(" "),this.visitNode(i.limit);if(i.returning)this.append(" "),this.visitNode(i.returning);if(t)this.append(")");if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitReturning(i){this.append("returning "),this.compileList(i.selections)}visitAlias(i){this.visitNode(i.node),this.append(" as "),this.visitNode(i.alias)}visitReference(i){if(i.table)this.visitNode(i.table),this.append(".");this.visitNode(i.column)}visitSelectAll(i){this.append("*")}visitIdentifier(i){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(i),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(i){if(!$t(i.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(i.name))}visitAnd(i){this.visitNode(i.left),this.append(" and "),this.visitNode(i.right)}visitOr(i){this.visitNode(i.left),this.append(" or "),this.visitNode(i.right)}visitValue(i){if(i.immediate)this.appendImmediateValue(i.value);else this.appendValue(i.value)}visitValueList(i){this.append("("),this.compileList(i.values),this.append(")")}visitTuple(i){this.append("("),this.compileList(i.values),this.append(")")}visitPrimitiveValueList(i){this.append("(");let{values:t}=i;for(let e=0;e<t.length;++e)if(this.appendValue(t[e]),e!==t.length-1)this.append(", ");this.append(")")}visitParens(i){this.append("("),this.visitNode(i.node),this.append(")")}visitJoin(i){if(this.append(g[i.joinType]),this.append(" "),this.visitNode(i.table),i.on)this.append(" "),this.visitNode(i.on)}visitOn(i){this.append("on "),this.visitNode(i.on)}visitRaw(i){let{sqlFragments:t,parameters:e}=i;for(let s=0;s<t.length;++s)if(this.append(t[s]),e.length>s)this.visitNode(e[s])}visitOperator(i){this.append(i.operator)}visitTable(i){this.visitNode(i.table)}visitSchemableIdentifier(i){if(i.schema)this.visitNode(i.schema),this.append(".");this.visitNode(i.identifier)}visitCreateTable(i){if(this.append("create "),i.frontModifiers?.length)this.compileList(i.frontModifiers," "),this.append(" ");if(i.temporary)this.append("temporary ");if(this.append("table "),i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.table),!i.selectQuery)this.append(" ("),this.compileList([...i.columns,...i.constraints??[]]),this.append(")");if(i.onCommit)this.append(" on commit "),this.append(i.onCommit);if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ");if(i.selectQuery)this.append(" as "),this.visitNode(i.selectQuery)}visitColumnDefinition(i){if(i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.column),this.append(" "),this.visitNode(i.dataType),i.unsigned)this.append(" unsigned");if(i.frontModifiers&&i.frontModifiers.length>0)this.append(" "),this.compileList(i.frontModifiers," ");if(i.generated)this.append(" "),this.visitNode(i.generated);if(i.identity)this.append(" identity");if(i.defaultTo)this.append(" "),this.visitNode(i.defaultTo);if(i.notNull)this.append(" not null");if(i.unique)this.append(" unique");if(i.nullsNotDistinct)this.append(" nulls not distinct");if(i.primaryKey)this.append(" primary key");if(i.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(i.references)this.append(" "),this.visitNode(i.references);if(i.check)this.append(" "),this.visitNode(i.check);if(i.endModifiers&&i.endModifiers.length>0)this.append(" "),this.compileList(i.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(i){if(this.append("references "),this.visitNode(i.table),this.append(" ("),this.compileList(i.columns),this.append(")"),i.onDelete)this.append(" on delete "),this.append(i.onDelete);if(i.onUpdate)this.append(" on update "),this.append(i.onUpdate)}visitDropTable(i){if(this.append("drop table "),i.ifExists)this.append("if exists ");if(this.visitNode(i.table),i.cascade)this.append(" cascade")}visitDataType(i){this.append(i.dataType)}visitOrderBy(i){this.append("order by "),this.compileList(i.items)}visitOrderByItem(i){if(this.visitNode(i.orderBy),i.collation)this.append(" "),this.visitNode(i.collation);if(i.direction)this.append(" "),this.visitNode(i.direction);if(i.nulls)this.append(" nulls "),this.append(i.nulls)}visitGroupBy(i){this.append("group by "),this.compileList(i.items)}visitGroupByItem(i){this.visitNode(i.groupBy)}visitUpdateQuery(i){let t=this.parentNode!==void 0&&!bo.is(this.parentNode)&&!Zt.is(this.parentNode)&&!Oo.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("update "),i.top)this.visitNode(i.top),this.append(" ");if(i.table)this.visitNode(i.table),this.append(" ");if(this.append("set "),i.updates)this.compileList(i.updates);if(i.output)this.append(" "),this.visitNode(i.output);if(i.from)this.append(" "),this.visitNode(i.from);if(i.joins){if(!i.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(i.joins," ")}if(i.where)this.append(" "),this.visitNode(i.where);if(i.returning)this.append(" "),this.visitNode(i.returning);if(i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(i.limit)this.append(" "),this.visitNode(i.limit);if(t)this.append(")");if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitColumnUpdate(i){this.visitNode(i.column),this.append(" = "),this.visitNode(i.value)}visitLimit(i){this.append("limit "),this.visitNode(i.limit)}visitOffset(i){this.append("offset "),this.visitNode(i.offset)}visitOnConflict(i){if(this.append("on conflict"),i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");else if(i.constraint)this.append(" on constraint "),this.visitNode(i.constraint);else if(i.indexExpression)this.append(" ("),this.visitNode(i.indexExpression),this.append(")");if(i.indexWhere)this.append(" "),this.visitNode(i.indexWhere);if(i.doNothing===!0)this.append(" do nothing");else if(i.updates){if(this.append(" do update set "),this.compileList(i.updates),i.updateWhere)this.append(" "),this.visitNode(i.updateWhere)}}visitOnDuplicateKey(i){this.append("on duplicate key update "),this.compileList(i.updates)}visitCreateIndex(i){if(this.append("create "),i.unique)this.append("unique ");if(this.append("index "),i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.name),i.table)this.append(" on "),this.visitNode(i.table);if(i.using)this.append(" using "),this.visitNode(i.using);if(i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");if(i.nullsNotDistinct)this.append(" nulls not distinct");if(i.where)this.append(" "),this.visitNode(i.where)}visitDropIndex(i){if(this.append("drop index "),i.ifExists)this.append("if exists ");if(this.visitNode(i.name),i.table)this.append(" on "),this.visitNode(i.table);if(i.cascade)this.append(" cascade")}visitCreateSchema(i){if(this.append("create schema "),i.ifNotExists)this.append("if not exists ");this.visitNode(i.schema)}visitDropSchema(i){if(this.append("drop schema "),i.ifExists)this.append("if exists ");if(this.visitNode(i.schema),i.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");this.append("primary key ("),this.compileList(i.columns),this.append(")"),this.buildDeferrable(i)}buildDeferrable(i){if(i.deferrable!==void 0)if(i.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(i.initiallyDeferred!==void 0)if(i.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");if(this.append("unique"),i.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(i.columns),this.append(")"),this.buildDeferrable(i)}visitCheckConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");this.append("check ("),this.visitNode(i.expression),this.append(")")}visitForeignKeyConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");if(this.append("foreign key ("),this.compileList(i.columns),this.append(") "),this.visitNode(i.references),i.onDelete)this.append(" on delete "),this.append(i.onDelete);if(i.onUpdate)this.append(" on update "),this.append(i.onUpdate);this.buildDeferrable(i)}visitList(i){this.compileList(i.items)}visitWith(i){if(this.append("with "),i.recursive)this.append("recursive ");this.compileList(i.expressions)}visitCommonTableExpression(i){if(this.visitNode(i.name),this.append(" as "),sa(i.materialized)){if(!i.materialized)this.append("not ");this.append("materialized ")}this.visitNode(i.expression)}visitCommonTableExpressionName(i){if(this.visitNode(i.table),i.columns)this.append("("),this.compileList(i.columns),this.append(")")}visitAlterTable(i){if(this.append("alter table "),this.visitNode(i.table),this.append(" "),i.renameTo)this.append("rename to "),this.visitNode(i.renameTo);if(i.setSchema)this.append("set schema "),this.visitNode(i.setSchema);if(i.addConstraint)this.visitNode(i.addConstraint);if(i.dropConstraint)this.visitNode(i.dropConstraint);if(i.renameConstraint)this.visitNode(i.renameConstraint);if(i.columnAlterations)this.compileColumnAlterations(i.columnAlterations);if(i.addIndex)this.visitNode(i.addIndex);if(i.dropIndex)this.visitNode(i.dropIndex)}visitAddColumn(i){this.append("add column "),this.visitNode(i.column)}visitRenameColumn(i){this.append("rename column "),this.visitNode(i.column),this.append(" to "),this.visitNode(i.renameTo)}visitDropColumn(i){this.append("drop column "),this.visitNode(i.column)}visitAlterColumn(i){if(this.append("alter column "),this.visitNode(i.column),this.append(" "),i.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(i.dataType),i.dataTypeExpression)this.append("using "),this.visitNode(i.dataTypeExpression)}if(i.setDefault)this.append("set default "),this.visitNode(i.setDefault);if(i.dropDefault)this.append("drop default");if(i.setNotNull)this.append("set not null");if(i.dropNotNull)this.append("drop not null")}visitModifyColumn(i){this.append("modify column "),this.visitNode(i.column)}visitAddConstraint(i){this.append("add "),this.visitNode(i.constraint)}visitDropConstraint(i){if(this.append("drop constraint "),i.ifExists)this.append("if exists ");if(this.visitNode(i.constraintName),i.modifier==="cascade")this.append(" cascade");else if(i.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(i){this.append("rename constraint "),this.visitNode(i.oldName),this.append(" to "),this.visitNode(i.newName)}visitSetOperation(i){if(this.append(i.operator),this.append(" "),i.all)this.append("all ");this.visitNode(i.expression)}visitCreateView(i){if(this.append("create "),i.orReplace)this.append("or replace ");if(i.materialized)this.append("materialized ");if(i.temporary)this.append("temporary ");if(this.append("view "),i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.name),this.append(" "),i.columns)this.append("("),this.compileList(i.columns),this.append(") ");if(i.as)this.append("as "),this.visitNode(i.as)}visitRefreshMaterializedView(i){if(this.append("refresh materialized view "),i.concurrently)this.append("concurrently ");if(this.visitNode(i.name),i.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(i){if(this.append("drop "),i.materialized)this.append("materialized ");if(this.append("view "),i.ifExists)this.append("if exists ");if(this.visitNode(i.name),i.cascade)this.append(" cascade")}visitGenerated(i){if(this.append("generated "),i.always)this.append("always ");if(i.byDefault)this.append("by default ");if(this.append("as "),i.identity)this.append("identity");if(i.expression)this.append("("),this.visitNode(i.expression),this.append(")");if(i.stored)this.append(" stored")}visitDefaultValue(i){this.append("default "),this.visitNode(i.defaultValue)}visitSelectModifier(i){if(i.rawModifier)this.visitNode(i.rawModifier);else this.append(v[i.modifier]);if(i.of)this.append(" of "),this.compileList(i.of,", ")}visitCreateType(i){if(this.append("create type "),this.visitNode(i.name),i.enum)this.append(" as enum "),this.visitNode(i.enum)}visitDropType(i){if(this.append("drop type "),i.ifExists)this.append("if exists ");this.visitNode(i.name)}visitExplain(i){if(this.append("explain"),i.options||i.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),i.options){if(this.visitNode(i.options),i.format)this.append(this.getExplainOptionsDelimiter())}if(i.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(i.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(i){this.append("default")}visitAggregateFunction(i){if(this.append(i.func),this.append("("),i.distinct)this.append("distinct ");if(this.compileList(i.aggregated),i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(this.append(")"),i.withinGroup)this.append(" within group ("),this.visitNode(i.withinGroup),this.append(")");if(i.filter)this.append(" filter("),this.visitNode(i.filter),this.append(")");if(i.over)this.append(" "),this.visitNode(i.over)}visitOver(i){if(this.append("over("),i.partitionBy){if(this.visitNode(i.partitionBy),i.orderBy)this.append(" ")}if(i.orderBy)this.visitNode(i.orderBy);this.append(")")}visitPartitionBy(i){this.append("partition by "),this.compileList(i.items)}visitPartitionByItem(i){this.visitNode(i.partitionBy)}visitBinaryOperation(i){this.visitNode(i.leftOperand),this.append(" "),this.visitNode(i.operator),this.append(" "),this.visitNode(i.rightOperand)}visitUnaryOperation(i){if(this.visitNode(i.operator),!this.isMinusOperator(i.operator))this.append(" ");this.visitNode(i.operand)}isMinusOperator(i){return _o.is(i)&&i.operator==="-"}visitUsing(i){this.append("using "),this.compileList(i.tables)}visitFunction(i){this.append(i.func),this.append("("),this.compileList(i.arguments),this.append(")")}visitCase(i){if(this.append("case"),i.value)this.append(" "),this.visitNode(i.value);if(i.when)this.append(" "),this.compileList(i.when," ");if(i.else)this.append(" else "),this.visitNode(i.else);if(this.append(" end"),i.isStatement)this.append(" case")}visitWhen(i){if(this.append("when "),this.visitNode(i.condition),i.result)this.append(" then "),this.visitNode(i.result)}visitJSONReference(i){this.visitNode(i.reference),this.visitNode(i.traversal)}visitJSONPath(i){if(i.inOperator)this.visitNode(i.inOperator);this.append("'$");for(let t of i.pathLegs)this.visitNode(t);this.append("'")}visitJSONPathLeg(i){let t=i.type==="ArrayLocation",e=String(i.value);if(t)this.append("["),this.append(this.sanitizeStringLiteral(e)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(e)),this.append('"')}visitJSONOperatorChain(i){for(let t=0,e=i.values.length;t<e;t++){if(t===e-1)this.visitNode(i.operator);else this.append("->");this.visitNode(i.values[t])}}visitMergeQuery(i){if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("merge "),i.top)this.visitNode(i.top),this.append(" ");if(this.append("into "),this.visitNode(i.into),i.using)this.append(" "),this.visitNode(i.using);if(i.whens)this.append(" "),this.compileList(i.whens," ");if(i.returning)this.append(" "),this.visitNode(i.returning);if(i.output)this.append(" "),this.visitNode(i.output);if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitMatched(i){if(i.not)this.append("not ");if(this.append("matched"),i.bySource)this.append(" by source")}visitAddIndex(i){if(this.append("add "),i.unique)this.append("unique ");if(this.append("index "),this.visitNode(i.name),i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");if(i.using)this.append(" using "),this.visitNode(i.using)}visitCast(i){this.append("cast("),this.visitNode(i.expression),this.append(" as "),this.visitNode(i.dataType),this.append(")")}visitFetch(i){this.append("fetch next "),this.visitNode(i.rowCount),this.append(` rows ${i.modifier}`)}visitOutput(i){this.append("output "),this.compileList(i.selections)}visitTop(i){if(this.append(`top(${i.expression})`),i.modifiers)this.append(` ${i.modifiers}`)}visitOrAction(i){this.append(i.action)}visitCollate(i){this.append("collate "),this.visitNode(i.collation)}append(i){this.#i+=i}appendValue(i){this.addParameter(i),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(i){let t=this.getLeftIdentifierWrapper(),e=this.getRightIdentifierWrapper(),s="";for(let n of i)if(s+=n,n===t)s+=t;else if(n===e)s+=e;return s}sanitizeStringLiteral(i){return i.replace(m,"''")}sanitizeJSONPathMemberValue(i){return i.replace(N,(t)=>t==="'"?"''":"\\\"")}addParameter(i){this.#t.push(i)}appendImmediateValue(i){if($t(i))this.appendStringLiteral(i);else if(No(i)||sa(i)||Oa(i))this.append(i.toString());else if(Na(i))this.append("null");else if(ru(i))this.appendImmediateValue(i.toISOString());else throw Error(`invalid immediate value ${i}`)}appendStringLiteral(i){this.append("'"),this.append(this.sanitizeStringLiteral(i)),this.append("'")}sortSelectModifiers(i){return i.sort((t,e)=>t.modifier&&e.modifier?o[t.modifier]-o[e.modifier]:1),f(i)}compileColumnAlterations(i){this.compileList(i)}announcesNewColumnDataType(){return!0}}var v=f({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),o=f({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),g=f({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var $r="kysely_migration",ln="kysely_migration_lock";var ai=f({__noMigrations__:!0});
|
|
3
|
+
export{Cn,$t,No,sa,Na,ru,Oa,Np,Qt,vr,f,Fl,En,Un,ze,Op,In,sn,Dp,_o,Dd,Zt,qo,bo,wr,Oo,nu,Ho,Tn,$r,ln};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{T,Zf,Lf,Bf,Uf,Xu,ed,td,rd,nd,Rc}from"./chunk-6bhn1p8v.js";import{mo}from"./chunk-1yacmegc.js";import{ho}from"./chunk-r7dty1tg.js";var o=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],xa=T("activity",o);var a=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],Wn=T("cpu",a);var r=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Io=T("gauge",r);var c=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],on=T("server",c);var n=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],vl=T("shield-alert",n);var i=[["path",{d:"m16 11 2 2 4-4",key:"9rsbq5"}],["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],$s=T("user-check",i);var u=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],Gs=T("dollar-sign",u);var vi={agent_total_tokens:{label:()=>nd(),icon:Wn,unit:"tokens"},agent_cost:{label:()=>ed(),icon:Gs,unit:"$"},agent_mcp_call_count:{label:()=>td(),icon:on,unit:"calls"},agent_bash_call_count:{label:()=>Xu(),icon:ho,unit:"calls"},agent_tool_call_count:{label:()=>rd(),icon:mo,unit:"calls"}};function rs(e,t){if(e==="agent_cost")return`$${t.toFixed(2)}`;return t.toLocaleString()}function wl(e){switch(Rc(e)){case"1hour":return Lf();case"5hour":return Bf();case"1day":return Zf();case"7day":return Uf();default:return e}}
|
|
2
|
+
export{xa,Wn,Gs,Io,on,vl,$s,vi,rs,wl};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var c=(s)=>s;function vs(s,i,t=c){let n=new Map;for(let e of s.tools??[])n.set(t(e.name),e);if(!i)return{immediate:[...n.values()],deferred:new Map};let a=new Set,f=new Set;for(let e of s.messages)if(e.role==="assistant"){for(let o of e.content)if(o.type==="toolCall")f.add(t(o.name))}else if(e.role==="toolResult")for(let o of e.addedToolNames??[]){let l=t(o);if(!f.has(l))a.add(l)}let d=[],r=new Map;for(let[e,o]of n)if(a.has(e))r.set(e,o);else d.push(o);return{immediate:d,deferred:r}}
|
|
3
|
+
export{vs};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function ca(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{ca};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function b(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 Hr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Hr=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 dt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var pt=(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 m extends Error{}class O extends m{constructor(e,t,r,s){super(`${O.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 xe({message:r,cause:pt(t)});let n=t?.error;if(e===400)return new mt(e,n,r,s);if(e===401)return new _t(e,n,r,s);if(e===403)return new gt(e,n,r,s);if(e===404)return new yt(e,n,r,s);if(e===409)return new bt(e,n,r,s);if(e===422)return new wt(e,n,r,s);if(e===429)return new xt(e,n,r,s);if(e>=500)return new At(e,n,r,s);return new O(e,n,r,s)}}class F extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class xe extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ae extends xe{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mt extends O{}class _t extends O{}class gt extends O{}class yt extends O{}class bt extends O{}class wt extends O{}class xt extends O{}class At extends O{}class It extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class Pt extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class se extends Error{constructor(e){super(e)}}var jn=/^[a-z][a-z0-9+.-]*:/i,Cs=(e)=>jn.test(e),U=(e)=>(U=Array.isArray,U(e)),Jr=U;function Xr(e){if(typeof e!=="object")return{};return e??{}}function Es(e){if(!e)return!0;for(let t in e)return!1;return!0}function vs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Be(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var $s=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var ks=(e)=>{try{return JSON.parse(e)}catch(t){return}};var z=(e)=>new Promise((t)=>setTimeout(t,e));var fe="6.26.0";var Ns=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Dn(){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 Wn=()=>{let e=Dn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":Ts(Deno.build.os),"X-Stainless-Arch":Os(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":fe,"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":fe,"X-Stainless-OS":Ts(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Os(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=qn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"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":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qn(){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 Os=(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"},Ts=(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"},Fs,Ms=()=>Fs??(Fs=Wn());function Ls(){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 Vr(...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 pr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Vr({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 Kr(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 Bs(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 Us=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Gr="RFC3986",zr=(e)=>String(e),Qr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:zr},js="RFC1738";var mr=(e,t)=>(mr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),mr(e,t)),Q=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Yr=1024,Ds=(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+=Yr){let d=o.length>=Yr?o.slice(f,f+Yr):o,_=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===js&&(p===40||p===41)){_[_.length]=d.charAt(y);continue}if(p<128){_[_.length]=Q[p];continue}if(p<2048){_[_.length]=Q[192|p>>6]+Q[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Q[224|p>>12]+Q[128|p>>6&63]+Q[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),_[_.length]=Q[240|p>>18]+Q[128|p>>12&63]+Q[128|p>>6&63]+Q[128|p&63]}a+=_.join("")}return a};function Ws(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Zr(e,t){if(U(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Hs={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Js=function(e,t){Array.prototype.push.apply(e,U(t)?t:[t])},qs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ds,encodeValuesOnly:!1,format:Gr,formatter:zr,indices:!1,serializeDate(e){return(qs??(qs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Xn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var es={};function Xs(e,t,r,s,n,o,a,f,d,_,y,p,u,w,g,R,S,I){let A=e,k=I,E=0,W=!1;while((k=k.get(es))!==void 0&&!W){let P=k.get(e);if(E+=1,typeof P<"u")if(P===E)throw RangeError("Cyclic object value");else W=!0;if(typeof k.get(es)>"u")E=0}if(typeof _==="function")A=_(t,A);else if(A instanceof Date)A=u?.(A);else if(r==="comma"&&U(A))A=Zr(A,function(P){if(P instanceof Date)return u?.(P);return P});if(A===null){if(o)return d&&!R?d(t,N.encoder,S,"key",w):t;A=""}if(Xn(A)||Ws(A)){if(d){let P=R?t:d(t,N.encoder,S,"key",w);return[g?.(P)+"="+g?.(d(A,N.encoder,S,"value",w))]}return[g?.(t)+"="+g?.(String(A))]}let T=[];if(typeof A>"u")return T;let C;if(r==="comma"&&U(A)){if(R&&d)A=Zr(A,d);C=[{value:A.length>0?A.join(",")||null:void 0}]}else if(U(_))C=_;else{let P=Object.keys(A);C=y?P.sort(y):P}let j=f?String(t).replace(/\./g,"%2E"):String(t),re=s&&U(A)&&A.length===1?j+"[]":j;if(n&&U(A)&&A.length===0)return re+"[]";for(let P=0;P<C.length;++P){let ue=C[P],Ss=typeof ue==="object"&&typeof ue.value<"u"?ue.value:A[ue];if(a&&Ss===null)continue;let qr=p&&f?ue.replace(/\./g,"%2E"):ue,Bn=U(A)?typeof r==="function"?r(re,qr):re:re+(p?"."+qr:"["+qr+"]");I.set(e,E);let Rs=new WeakMap;Rs.set(es,I),Js(T,Xs(Ss,Bn,r,s,n,o,a,f,r==="comma"&&R&&U(A)?null:d,_,y,p,u,w,g,R,S,Rs))}return T}function Vn(e=N){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||N.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=Gr;if(typeof e.format<"u"){if(!mr(Qr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Qr[r],n=N.filter;if(typeof e.filter==="function"||U(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Hs)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=N.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:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:N.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?N.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:N.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:N.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:N.strictNullHandling}}function Vs(e,t={}){let r=e,s=Vn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(U(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Hs[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let w=n[u];if(s.skipNulls&&r[w]===null)continue;Js(a,Xs(r[w],w,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,_))}let y=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return y.length>0?p+y:""}function Ks(e){return Vs(e,{arrayFormat:"brackets"})}function Qs(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 Gs;function Ue(e){let t;return(Gs??(t=new globalThis.TextEncoder,Gs=t.encode.bind(t)))(e)}var zs;function ts(e){let t;return(zs??(t=new globalThis.TextDecoder,zs=t.decode.bind(t)))(e)}var q,H;class je{constructor(){q.set(this,void 0),H.set(this,void 0),b(this,q,new Uint8Array,"f"),b(this,H,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ue(e):e;b(this,q,Qs([i(this,q,"f"),t]),"f");let r=[],s;while((s=Gn(i(this,q,"f"),i(this,H,"f")))!=null){if(s.carriage&&i(this,H,"f")==null){b(this,H,s.index,"f");continue}if(i(this,H,"f")!=null&&(s.index!==i(this,H,"f")+1||s.carriage)){r.push(ts(i(this,q,"f").subarray(0,i(this,H,"f")-1))),b(this,q,i(this,q,"f").subarray(i(this,H,"f")),"f"),b(this,H,null,"f");continue}let n=i(this,H,"f")!==null?s.preceding-1:s.preceding,o=ts(i(this,q,"f").subarray(0,n));r.push(o),b(this,q,i(this,q,"f").subarray(s.index),"f"),b(this,H,null,"f")}return r}flush(){if(!i(this,q,"f").length)return[];return this.decode(`
|
|
3
|
+
`)}}q=new WeakMap,H=new WeakMap;je.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]);je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Gn(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 Ys(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 gr={off:0,error:200,warn:300,info:400,debug:500},rs=(e,t,r)=>{if(!e)return;if(vs(gr,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gr))}`);return};function St(){}function _r(e,t,r){if(!t||gr[e]>gr[r])return St;else return t[e].bind(t)}var zn={error:St,warn:St,info:St,debug:St},Zs=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return zn;let s=Zs.get(t);if(s&&s[0]===r)return s[1];let n={error:_r("error",t,r),warn:_r("warn",t,r),info:_r("info",t,r),debug:_r("debug",t,r)};return Zs.set(t,[r,n]),n}var ne=(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 Rt;class J{constructor(e,t,r){this.iterator=e,Rt.set(this,void 0),this.controller=t,b(this,Rt,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?v(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Qn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new O(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new O(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(dt(d))return;throw d}finally{if(!f)t.abort()}}return new J(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new je,f=Kr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("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(dt(f))return;throw f}finally{if(!a)t.abort()}}return new J(o,t,r)}[(Rt=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 J(()=>s(e),this.controller,i(this,Rt,"f")),new J(()=>s(t),this.controller,i(this,Rt,"f"))]}toReadableStream(){let e=this,t;return Vr({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=Ue(JSON.stringify(s)+`
|
|
5
|
+
`);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Qn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("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 m("Attempted to iterate over a response with no body")}let r=new en,s=new je,n=Kr(e.body);for await(let o of Yn(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*Yn(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"?Ue(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Ys(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class en{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]=Zn(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 Zn(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 yr(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(v(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 J.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 ss(u,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,ne({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ss(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 Ct;class Ie extends Promise{constructor(e,t,r=yr){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ct.set(this,void 0),b(this,Ct,e,"f")}_thenUnwrap(e){return new Ie(i(this,Ct,"f"),this.responsePromise,async(t,r)=>ss(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,Ct,"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)}}Ct=new WeakMap;var br;class wr{constructor(e,t,r,s){br.set(this,void 0),b(this,br,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 m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class xr extends Ie{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await yr(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class oe extends wr{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 x extends wr{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:{...Xr(this.options.query),after:t}}}}class Y extends wr{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:{...Xr(this.options.query),after:e}}}}var is=()=>{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 De(e,t,r){return is(),new File(e,t??"unknown_file",r)}function Et(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 Ar=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ie=async(e,t)=>{if(!ns(e.body))return e;return{...e,body:await rn(e.body,t)}},V=async(e,t)=>({...e,body:await rn(e.body,t)}),tn=new WeakMap;function to(e){let t=typeof e==="function"?e:e.fetch,r=tn.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 tn.set(t,s),s}var rn=async(e,t)=>{if(!await to(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])=>os(r,s,n))),r},sn=(e)=>e instanceof Blob&&("name"in e),ro=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ar(e)||sn(e)),ns=(e)=>{if(ro(e))return!0;if(Array.isArray(e))return e.some(ns);if(e&&typeof e==="object"){for(let t in e)if(ns(e[t]))return!0}return!1},os=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,De([await r.blob()],Et(r)));else if(Ar(r))e.append(t,De([await new Response(pr(r)).blob()],Et(r)));else if(sn(r))e.append(t,r,Et(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>os(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>os(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 nn=(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",so=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&nn(e),no=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Ir(e,t,r){if(is(),e=await e,so(e)){if(e instanceof File)return e;return De([await e.arrayBuffer()],e.name)}if(no(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),De(await as(n),t,r)}let s=await as(e);if(t||(t=Et(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 De(s,t,r)}async function as(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ar(e))for await(let r of e)t.push(...await as(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${oo(e)}`)}return t}function oo(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 an(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var on=Object.freeze(Object.create(null)),ao=(e=an)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??on)??on)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),R="^".repeat(w.length);return y=w.start+w.length,u+g+R},"");throw new m(`Path parameters result in path with invalid segments:
|
|
7
|
+
${o.map((u)=>u.error).join(`
|
|
8
|
+
`)}
|
|
9
|
+
${a}
|
|
10
|
+
${p}`)}return a},l=ao(an);class We extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,x,{query:t,...r})}}function vt(e){return e!==void 0&&"function"in e&&e.function!==void 0}function $t(e){return e?.$brand==="auto-parseable-response-format"}function Pe(e){return e?.$brand==="auto-parseable-tool"}function ln(e,t){if(!t||!ls(t))return{...e,choices:e.choices.map((r)=>(un(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return kt(e,t)}function kt(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new It;if(s.finish_reason==="content_filter")throw new Pt;return un(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>fo(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?uo(t,s.message.content):null}}});return{...e,choices:r}}function uo(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 fo(e,t){let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Pe(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function cn(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return vt(r)&&(Pe(r)||r?.function.strict||!1)}function ls(e){if($t(e.response_format))return!0;return e.tools?.some((t)=>Pe(t)||t.type==="function"&&t.function.strict===!0)??!1}function un(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function fn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var qe=(e)=>e?.role==="assistant",cs=(e)=>e?.role==="tool";var us,Pr,Sr,Ot,Tt,Rr,Ft,ae,Nt,Cr,Er,He,hn;class Se{constructor(){us.add(this),this.controller=new AbortController,Pr.set(this,void 0),Sr.set(this,()=>{}),Ot.set(this,()=>{}),Tt.set(this,void 0),Rr.set(this,()=>{}),Ft.set(this,()=>{}),ae.set(this,{}),Nt.set(this,!1),Cr.set(this,!1),Er.set(this,!1),He.set(this,!1),b(this,Pr,new Promise((e,t)=>{b(this,Sr,e,"f"),b(this,Ot,t,"f")}),"f"),b(this,Tt,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,Ft,t,"f")}),"f"),i(this,Pr,"f").catch(()=>{}),i(this,Tt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,us,"m",hn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Sr,"f").call(this),this._emit("connect")}get ended(){return i(this,Nt,"f")}get errored(){return i(this,Cr,"f")}get aborted(){return i(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,ae,"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,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(b(this,He,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){b(this,He,!0,"f"),await i(this,Tt,"f")}_emit(e,...t){if(i(this,Nt,"f"))return;if(e==="end")b(this,Nt,!0,"f"),i(this,Rr,"f").call(this);let r=i(this,ae,"f")[e];if(r)i(this,ae,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Pr=new WeakMap,Sr=new WeakMap,Ot=new WeakMap,Tt=new WeakMap,Rr=new WeakMap,Ft=new WeakMap,ae=new WeakMap,Nt=new WeakMap,Cr=new WeakMap,Er=new WeakMap,He=new WeakMap,us=new WeakSet,hn=function(t){if(b(this,Cr,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new F;if(t instanceof F)return b(this,Er,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function dn(e){return typeof e.parse==="function"}var D,fs,vr,hs,ds,ps,pn,mn,ho=10;class Mt extends Se{constructor(){super(...arguments);D.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),cs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(qe(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 m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,D,"m",fs).call(this)}async finalMessage(){return await this.done(),i(this,D,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,D,"m",hs).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,D,"m",ds).call(this)}async totalUsage(){return await this.done(),i(this,D,"m",ps).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,D,"m",vr).call(this);if(t)this._emit("finalMessage",t);let r=i(this,D,"m",fs).call(this);if(r)this._emit("finalContent",r);let s=i(this,D,"m",hs).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,D,"m",ds).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,D,"m",ps).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,D,"m",pn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(kt(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=ho}=r||{},_=t.tools.map((u)=>{if(Pe(u)){if(!u.$callback)throw new m("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}),y={};for(let u of _)if(u.type==="function")y[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.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 g=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let R of g.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:I,arguments:A}=R.function,k=y[I];if(!k){let C=`Invalid tool_call: ${JSON.stringify(I)}. Available options are: ${Object.keys(y).map((j)=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}else if(f&&f!==I){let C=`Invalid tool_call: ${JSON.stringify(I)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}let E;try{E=dn(k)?await k.parse(A):A}catch(C){let j=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:S,content:j});continue}let W=await k.function(E,this),T=i(this,D,"m",mn).call(this,W);if(this._addMessage({role:"tool",tool_call_id:S,content:T}),f)return}}return}}D=new WeakSet,fs=function(){return i(this,D,"m",vr).call(this).content??null},vr=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(qe(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},hs=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(qe(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(cs(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},ps=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},pn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},mn=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Lt extends Mt{static runTools(e,t,r){let s=new Lt,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),qe(e)&&e.content)this._emit("content",e.content)}}var L={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 _n extends Error{}class gn extends Error{}function po(e,t=L.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return mo(e.trim(),t)}var mo=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new _n(`${u} at position ${s}`)},o=(u)=>{throw new gn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||L.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||L.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||L.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||L.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||L.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"||L.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return y()},f=()=>{let u=s,w=!1;s++;while(s<r&&(e[s]!=='"'||w&&e[s-1]==="\\"))w=e[s]==="\\"?!w:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(w)))}catch(g){o(String(g))}else if(L.STR&t)try{return JSON.parse(e.substring(u,s-Number(w))+'"')}catch(g){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&L.OBJ&t)return u;let w=f();p(),s++;try{let g=a();Object.defineProperty(u,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(L.OBJ&t)return u;else throw g}if(p(),e[s]===",")s++}}catch(w){if(L.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(w){if(L.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},y=()=>{if(s===0){if(e==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(w){if(L.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(g){}o(String(w))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(L.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(w){if(e.substring(u,s)==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(g){o(String(g))}}},p=()=>{while(s<r&&`
|
|
11
|
+
\r `.includes(e[s]))s++};return a()},ms=(e)=>po(e,L.ALL^L.NUM);var M,le,Je,he,_s,$r,gs,ys,bs,kr,ws,yn;class de extends Mt{constructor(e){super();M.add(this),le.set(this,void 0),Je.set(this,void 0),he.set(this,void 0),b(this,le,e,"f"),b(this,Je,[],"f")}get currentChatCompletionSnapshot(){return i(this,he,"f")}static fromReadableStream(e){let t=new de(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new de(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,M,"m",_s).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,M,"m",gs).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).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,M,"m",_s).call(this),this._connected();let s=J.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,M,"m",kr).call(this));i(this,M,"m",gs).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}[(le=new WeakMap,Je=new WeakMap,he=new WeakMap,M=new WeakSet,_s=function(){if(this.ended)return;b(this,he,void 0,"f")},$r=function(t){let r=i(this,Je,"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,Je,"f")[t.index]=r,r},gs=function(t){if(this.ended)return;let r=i(this,M,"m",yn).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,M,"m",$r).call(this,n);if(n.finish_reason){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).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,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).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 wn(f?.type)}}},ys=function(t,r){if(i(this,M,"m",$r).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,le,"f")?.tools?.find((a)=>vt(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:Pe(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else wn(n.type)},bs=function(t){let r=i(this,M,"m",$r).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,M,"m",ws).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})},kr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,he,"f");if(!t)throw new m("request ended without sending any chunks");return b(this,he,void 0,"f"),b(this,Je,[],"f"),_o(t,i(this,le,"f"))},ws=function(){let t=i(this,le,"f")?.response_format;if($t(t))return t;return null},yn=function(t){var r,s,n,o;let a=i(this,he,"f"),{choices:f,...d}=t;if(!a)a=b(this,he,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:_,finish_reason:y,index:p,logprobs:u=null,...w}of t.choices){let g=a.choices[p];if(!g)g=a.choices[p]={finish_reason:y,index:p,message:{},logprobs:u,...w};if(u)if(!g.logprobs)g.logprobs=Object.assign({},u);else{let{content:W,refusal:T,...C}=u;if(bn(C),Object.assign(g.logprobs,C),W)(r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...W);if(T)(s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...T)}if(y){if(g.finish_reason=y,i(this,le,"f")&&ls(i(this,le,"f"))){if(y==="length")throw new It;if(y==="content_filter")throw new Pt}}if(Object.assign(g,w),!_)continue;let{content:R,refusal:S,function_call:I,role:A,tool_calls:k,...E}=_;if(bn(E),Object.assign(g.message,E),S)g.message.refusal=(g.message.refusal||"")+S;if(A)g.message.role=A;if(I)if(!g.message.function_call)g.message.function_call=I;else{if(I.name)g.message.function_call.name=I.name;if(I.arguments)(n=g.message.function_call).arguments??(n.arguments=""),g.message.function_call.arguments+=I.arguments}if(R){if(g.message.content=(g.message.content||"")+R,!g.message.refusal&&i(this,M,"m",ws).call(this))g.message.parsed=ms(g.message.content)}if(k){if(!g.message.tool_calls)g.message.tool_calls=[];for(let{index:W,id:T,type:C,function:j,...re}of k){let P=(o=g.message.tool_calls)[W]??(o[W]={});if(Object.assign(P,re),T)P.id=T;if(C)P.type=C;if(j)P.function??(P.function={name:j.name??"",arguments:""});if(j?.name)P.function.name=j.name;if(j?.arguments){if(P.function.arguments+=j.arguments,cn(i(this,le,"f"),P))P.function.parsed_arguments=ms(P.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 J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function _o(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:_,finish_reason:y,index:p,logprobs:u,...w})=>{if(!y)throw new m(`missing finish_reason for choice ${p}`);let{content:g=null,function_call:R,tool_calls:S,...I}=_,A=_.role;if(!A)throw new m(`missing role for choice ${p}`);if(R){let{arguments:k,name:E}=R;if(k==null)throw new m(`missing function_call.arguments for choice ${p}`);if(!E)throw new m(`missing function_call.name for choice ${p}`);return{...w,message:{content:g,function_call:{arguments:k,name:E},role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}if(S)return{...w,index:p,finish_reason:y,logprobs:u,message:{...I,role:A,content:g,refusal:_.refusal??null,tool_calls:S.map((k,E)=>{let{function:W,type:T,id:C,...j}=k,{arguments:re,name:P,...ue}=W||{};if(C==null)throw new m(`missing choices[${p}].tool_calls[${E}].id
|
|
12
|
+
${Or(e)}`);if(T==null)throw new m(`missing choices[${p}].tool_calls[${E}].type
|
|
13
|
+
${Or(e)}`);if(P==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.name
|
|
14
|
+
${Or(e)}`);if(re==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.arguments
|
|
15
|
+
${Or(e)}`);return{...j,id:C,type:T,function:{...ue,name:P,arguments:re}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ln(d,t)}function Or(e){return JSON.stringify(e)}function bn(e){return}function wn(e){}class Xe extends de{static fromReadableStream(e){let t=new Xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Xe(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class pe extends c{constructor(){super(...arguments);this.messages=new We(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",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return fn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Xe.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return de.createChatCompletion(this._client,e,t)}}pe.Messages=We;class Re extends c{constructor(){super(...arguments);this.completions=new pe(this._client)}}Re.Completions=pe;var xn=Symbol("brand.privateNullableHeaders");function*yo(e){if(!e)return;if(xn 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(Jr(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=Jr(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 yo(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{[xn]:!0,values:t,nulls:r}};class Bt 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 Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}},this._client))}}class ce extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ce.Transcriptions=Ut;ce.Translations=jt;ce.Speech=Bt;class Ve 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",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt 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",x,{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 Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ce extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ce.Sessions=Wt;Ce.TranscriptionSessions=qt;class Ht 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 Jt 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",Y,{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`,Y,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}Ee.Sessions=Ht;Ee.Threads=Jt;class Xt 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`,x,{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 Vt 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`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var An=(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 K=(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 B,$e,xs,Z,Tr,G,ke,Ke,ve,Mr,X,Fr,Nr,zt,Kt,Gt,In,Pn,Sn,Rn,Cn,En,vn;class me extends Se{constructor(){super(...arguments);B.add(this),xs.set(this,[]),Z.set(this,{}),Tr.set(this,{}),G.set(this,void 0),ke.set(this,void 0),Ke.set(this,void 0),ve.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),Nr.set(this,void 0),zt.set(this,void 0)}[(xs=new WeakMap,Z=new WeakMap,Tr=new WeakMap,G=new WeakMap,ke=new WeakMap,Ke=new WeakMap,ve=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,Nr=new WeakMap,zt=new WeakMap,B=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 $e;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=J.fromReadableStream(e,this.controller);for await(let n of s)i(this,B,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new $e;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,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new $e;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 $e;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Fr,"f")}currentRun(){return i(this,Nr,"f")}currentMessageSnapshot(){return i(this,G,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Tr,"f"))}async finalRun(){if(await this.done(),!i(this,ke,"f"))throw Error("Final run was not received.");return i(this,ke,"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,B,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).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,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).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(Be(n)&&Be(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(!Be(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)}}$e=me,Kt=function(t){if(this.ended)return;switch(b(this,Fr,t,"f"),i(this,B,"m",Sn).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,B,"m",vn).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,B,"m",Pn).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,B,"m",In).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ko(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,ke,"f"))throw Error("Final run has not been received");return i(this,ke,"f")},In=function(t){let[r,s]=i(this,B,"m",Cn).call(this,t,i(this,G,"f"));b(this,G,r,"f"),i(this,Tr,"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,Ke,"f")){if(i(this,ve,"f"))switch(i(this,ve,"f").type){case"text":this._emit("textDone",i(this,ve,"f").text,i(this,G,"f"));break;case"image_file":this._emit("imageFileDone",i(this,ve,"f").image_file,i(this,G,"f"));break}b(this,Ke,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ke,"f")!==void 0){let n=t.data.content[i(this,Ke,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,G,"f"));break;case"text":this._emit("textDone",n.text,i(this,G,"f"));break}}if(i(this,G,"f"))this._emit("messageDone",t.data);b(this,G,void 0,"f")}},Pn=function(t){let r=i(this,B,"m",Rn).call(this,t);switch(b(this,zt,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,Mr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f"));if(b(this,Mr,o.index,"f"),b(this,X,r.step_details.tool_calls[o.index],"f"),i(this,X,"f"))this._emit("toolCallCreated",i(this,X,"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(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Sn=function(t){i(this,xs,"f").push(t),this._emit("event",t)},Rn=function(t){switch(t.event){case"thread.run.step.created":return i(this,Z,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,Z,"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=$e.accumulateDelta(r,s.delta);i(this,Z,"f")[t.data.id]=n}return i(this,Z,"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,Z,"f")[t.data.id]=t.data;break}if(i(this,Z,"f")[t.data.id])return i(this,Z,"f")[t.data.id];throw Error("No snapshot available")},Cn=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,B,"m",En).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")},En=function(t,r){return $e.accumulateDelta(r,t)},vn=function(t){switch(b(this,Nr,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(b(this,ke,t.data,"f"),i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f");break;case"thread.run.cancelling":break}};function ko(e){}class Ge extends c{constructor(){super(...arguments);this.steps=new Vt(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`,x,{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 me.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 z(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return me.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 me.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}Ge.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new Ge(this._client),this.messages=new Xt(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 me.createThreadAssistantStream(e,this._client.beta.threads,t)}}Oe.Runs=Ge;Oe.Messages=Xt;class ee extends c{constructor(){super(...arguments);this.realtime=new Ce(this._client),this.chatkit=new Ee(this._client),this.assistants=new Dt(this._client),this.threads=new Oe(this._client)}}ee.Realtime=Ce;ee.ChatKit=Ee;ee.Assistants=Dt;ee.Threads=Oe;class ze extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt 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 Ye extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ie({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`,x,{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])})}}Ye.Content=Qt;class Te extends c{constructor(){super(...arguments);this.files=new Ye(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",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Te.Files=Ye;class Yt 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`,Y,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Fe extends c{constructor(){super(...arguments);this.items=new Yt(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)}}Fe.Items=Yt;class Ze extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(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 v(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=An(f)});return o})}}class Zt 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`,x,{query:n,...r})}}class et extends c{constructor(){super(...arguments);this.outputItems=new Zt(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`,x,{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)}}et.OutputItems=Zt;class Ne extends c{constructor(){super(...arguments);this.runs=new et(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",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Ne.Runs=et;class tt extends c{create(e,t){return this._client.post("/files",V({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{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 z(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr 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 rt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}rt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,oe,{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`,Y,{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 st extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}st.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class nt extends c{constructor(){super(...arguments);this.checkpoints=new sr(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",x,{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`,x,{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)}}nt.Checkpoints=sr;class te extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new nt(this._client),this.checkpoints=new st(this._client),this.alpha=new rt(this._client)}}te.Methods=er;te.Jobs=nt;te.Checkpoints=st;te.Alpha=rt;class nr extends c{}class Me extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Me.GraderModels=nr;class ot extends c{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",V({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 it extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class at extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or 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 ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _e extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}_e.ClientSecrets=ir;_e.Calls=or;function $n(e,t){if(!t||!zo(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 As(e,t)}function As(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:Zo(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:Go(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Lr(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 Go(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 zo(e){if($t(e.text?.format))return!0;return!1}function Qo(e){return e?.$brand==="auto-parseable-tool"}function Yo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function Zo(e,t){let r=Yo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Qo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Lr(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 lt,Br,ge,Ur,kn,On,Tn,Fn;class jr extends Se{constructor(e){super();lt.add(this),Br.set(this,void 0),ge.set(this,void 0),Ur.set(this,void 0),b(this,Br,e,"f")}static createResponse(e,t,r){let s=new jr(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,lt,"m",kn).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,lt,"m",On).call(this,a,o);if(n.controller.signal?.aborted)throw new F;return i(this,lt,"m",Tn).call(this)}[(Br=new WeakMap,ge=new WeakMap,Ur=new WeakMap,lt=new WeakSet,kn=function(){if(this.ended)return;b(this,ge,void 0,"f")},On=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,lt,"m",Fn).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 m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`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 m(`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}},Tn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ge,"f");if(!t)throw new m("request ended without sending any events");b(this,ge,void 0,"f");let r=ei(t,i(this,Br,"f"));return b(this,Ur,r,"f"),r},Fn=function(t){let r=i(this,ge,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ge,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 m(`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 m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`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 m(`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 m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ge,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,Ur,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ei(e,t){return $n(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ye extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(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")Lr(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")Lr(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)=>As(r,e))}stream(e,t){return jr.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})}}ye.InputItems=ar;ye.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur 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 ct extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ie({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`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ct.Content=ur;class be extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new ct(this._client)}create(e={},t){return this._client.post("/skills",ie({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",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}be.Content=cr;be.Versions=ct;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,V({body:t,...r},this._client))}}class Le extends c{constructor(){super(...arguments);this.parts=new fr(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})}}Le.Parts=fr;var Nn=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 hr 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`,x,{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 z(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 _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Nn(y),await this.createAndPoll(e,{file_ids:d})}}class dr 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`,x,{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 z(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`,oe,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class we extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(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",x,{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`,oe,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}we.Files=dr;we.FileBatches=hr;class ut extends c{create(e,t){return this._client.post("/videos",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Y,{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`,ie({body:t,...r},this._client))}}var ft,Mn,Dr;class ht extends c{constructor(){super(...arguments);ft.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,ft,"m",Mn).call(this,r);let n=h([t]).values,o=i(this,ft,"m",Dr).call(this,n,"webhook-signature"),a=i(this,ft,"m",Dr).call(this,n,"webhook-timestamp"),f=i(this,ft,"m",Dr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new se("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new se("Webhook timestamp is too old");if(d>_+s)throw new se("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new se("The given webhook signature does not match the expected signature")}}ft=new WeakSet,Mn=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")},Dr=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 Is,Ps,Wr,Ln;class Qe{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("OPENAI_API_KEY"),organization:r=K("OPENAI_ORG_ID")??null,project:s=K("OPENAI_PROJECT_ID")??null,webhookSecret:n=K("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Is.add(this),Wr.set(this,void 0),this.completions=new ze(this),this.chat=new Re(this),this.embeddings=new Ze(this),this.files=new tt(this),this.images=new ot(this),this.audio=new ce(this),this.moderations=new at(this),this.models=new it(this),this.fineTuning=new te(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new ht(this),this.beta=new ee(this),this.batches=new Ve(this),this.uploads=new Le(this),this.responses=new ye(this),this.realtime=new _e(this),this.conversations=new Fe(this),this.evals=new Ne(this),this.containers=new Te(this),this.skills=new be(this),this.videos=new ut(this),t===void 0)throw new m("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&&Ns())throw new m(`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??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"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 Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.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 m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`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,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(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 Ie(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"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>pt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}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 xr(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),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}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 z(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)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...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))}:{},...Ms(),"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:pr(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,Wr,"f").call(this,{body:e,headers:r})}}Ps=Qe,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};Qe.OpenAI=Ps;Qe.DEFAULT_TIMEOUT=600000;Qe.OpenAIError=m;Qe.APIError=O;Qe.APIConnectionError=xe;Qe.APIConnectionTimeoutError=Ae;Qe.APIUserAbortError=F;Qe.NotFoundError=yt;Qe.ConflictError=bt;Qe.RateLimitError=xt;Qe.BadRequestError=mt;Qe.AuthenticationError=_t;Qe.InternalServerError=At;Qe.PermissionDeniedError=gt;Qe.UnprocessableEntityError=wt;Qe.InvalidWebhookSignatureError=se;Qe.toFile=Ir;Qe.Completions=ze;Qe.Chat=Re;Qe.Embeddings=Ze;Qe.Files=tt;Qe.Images=ot;Qe.Audio=ce;Qe.Moderations=at;Qe.Models=it;Qe.FineTuning=te;Qe.Graders=Me;Qe.VectorStores=we;Qe.Webhooks=ht;Qe.Beta=ee;Qe.Batches=Ve;Qe.Uploads=Le;Qe.Responses=ye;Qe.Realtime=_e;Qe.Conversations=Fe;Qe.Evals=Ne;Qe.Containers=Te;Qe.Skills=be;Qe.Videos=ut;class uu extends Qe{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("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 m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("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 m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("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(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(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 ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{Qe,uu};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
class i{queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise((s)=>{this.resolveFinalResult=s})}push(e){if(this.done)return;if(this.isComplete(e))this.done=!0,this.resolveFinalResult(this.extractResult(e));let t=this.waiting.shift();if(t)t({value:e,done:!1});else this.queue.push(e)}end(e){if(this.done=!0,e!==void 0)this.resolveFinalResult(e);while(this.waiting.length>0)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){while(!0)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let e=await new Promise((t)=>this.waiting.push(t));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}}class Vt extends i{constructor(){super((e)=>e.type==="done"||e.type==="error",(e)=>{if(e.type==="done")return e.message;else if(e.type==="error")return e.error;throw Error("Unexpected event type for final result")})}}function Cs(e){if(e instanceof Error)return e.message||e.name;if(typeof e==="string")return e;return String(e)}function n(e){if(!(e instanceof Error))return{name:"ThrownValue",message:Cs(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t==="string"||typeof t==="number"?t:void 0}}function tc(e,t,s){return{type:e,timestamp:Date.now(),error:n(t),details:s}}function zi(e,t){e.diagnostics=[...e.diagnostics??[],t]}
|
|
3
|
+
export{Vt,Cs,tc,zi};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Li,Bi}from"./chunk-32pcmaqm.js";import{w}from"./chunk-rza4ae5z.js";var j=w(function(v,f){var{defineProperty:i,getOwnPropertyDescriptor:s,getOwnPropertyNames:_}=Object,k=Object.prototype.hasOwnProperty,l=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},u=(t,e,o,n)=>{if(e&&typeof e==="object"||typeof e==="function"){for(let r of _(e))if(!k.call(t,r)&&r!==o)i(t,r,{get:()=>e[r],enumerable:!(n=s(e,r))||n.enumerable})}return t},d=(t)=>u(i({},"__esModule",{value:!0}),t),p={};l(p,{refreshToken:()=>O});f.exports=d(p);var c=Li(),a=Bi();async function O(t){let e=t?.project,o=t?.team;if(!e&&!o){let r=(0,a.findProjectInfo)();e=r.projectId,o=r.teamId}else if(!e||!o){let r=(0,a.findProjectInfo)();e=e??r.projectId,o=o??r.teamId}if(!e)throw new c.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let n=(0,a.loadToken)(e);if(!n||(0,a.isExpired)((0,a.getTokenPayload)(n.token),t?.expirationBufferMs)){let r=await(0,a.getVercelToken)({expirationBufferMs:t?.expirationBufferMs});if(n=await(0,a.getVercelOidcToken)(r,e,o),!n)throw new c.VercelOidcTokenError("Failed to refresh OIDC token");(0,a.saveToken)(n,e)}process.env.VERCEL_OIDC_TOKEN=n.token;return}});export default j();
|