@shumai-one/shumai 0.4.3 → 0.4.4
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-071x515q.js +4 -0
- package/bin/chunk-0cmx7k4c.js +1 -0
- package/bin/{chunk-cqb415s6.js → chunk-0qaq0sp8.js} +2 -2
- package/bin/chunk-0qjfahk9.js +2 -0
- package/bin/{chunk-9t1ne8xr.js → chunk-0zv3bks2.js} +2 -2
- package/bin/chunk-16xax8kk.js +1 -0
- package/bin/chunk-1gvscz88.js +5 -0
- package/bin/{chunk-6gg1ymer.js → chunk-1j27fzy1.js} +2 -2
- package/bin/chunk-1t167cvj.js +11 -0
- package/bin/{chunk-pb1zf0vb.js → chunk-1xh34aew.js} +2 -2
- package/bin/{chunk-zmv8cg4s.js → chunk-1zwajpwf.js} +3 -3
- package/bin/chunk-2w5xqhjm.js +1 -0
- package/bin/{chunk-f3ehv01n.js → chunk-3tedzb2j.js} +26 -26
- package/bin/{chunk-zehyn6vd.js → chunk-3ttrhqy3.js} +2 -2
- package/bin/chunk-3zkasqb8.js +1 -0
- package/bin/chunk-453ykvaw.js +2 -0
- package/bin/{chunk-3cyrcgm5.js → chunk-4991gz3y.js} +9 -9
- package/bin/chunk-4hkkdm2q.js +2 -0
- package/bin/chunk-4mjywsj8.js +3 -0
- package/bin/{chunk-cnxwmycy.js → chunk-4v41a1r9.js} +3 -3
- package/bin/{chunk-87zxtf66.js → chunk-4wy87hwd.js} +2 -2
- package/bin/{chunk-sfx2588q.js → chunk-579e4wv4.js} +2 -2
- package/bin/{chunk-1yacmegc.js → chunk-5adsx8x4.js} +2 -2
- package/bin/{chunk-b235azv4.js → chunk-5hg6kcfz.js} +13 -13
- package/bin/{chunk-rbj4fad9.js → chunk-5nm2jvg5.js} +13 -13
- package/bin/chunk-5tcdwep5.js +11 -0
- package/bin/chunk-5vzrpz50.js +2 -0
- package/bin/chunk-6ghcj4a9.js +3 -0
- package/bin/{chunk-b9yrw9et.js → chunk-77fmkpdz.js} +4 -4
- package/bin/chunk-7bcxj1jd.js +2 -0
- package/bin/{chunk-qf24e71w.js → chunk-7gmdnsdg.js} +1 -1
- package/bin/{chunk-fxswt9hc.js → chunk-7jtmwt5a.js} +2 -2
- package/bin/chunk-7kjgvxqa.js +2 -0
- package/bin/{chunk-bay038pj.js → chunk-7pw1550a.js} +2 -2
- package/bin/chunk-7rhz2gze.js +211 -0
- package/bin/chunk-837fky18.js +3 -0
- package/bin/chunk-84as6x83.js +1 -0
- package/bin/chunk-8e28hcny.js +2 -0
- package/bin/{chunk-k7hss0bd.js → chunk-914bp49r.js} +3 -3
- package/bin/chunk-97f2af6d.js +12 -0
- package/bin/{chunk-4r81ghg8.js → chunk-98715kc3.js} +2 -2
- package/bin/chunk-9ccw540k.js +2 -0
- package/bin/{chunk-ag6p3mbf.js → chunk-9t8n2des.js} +2 -2
- package/bin/chunk-9ybt6vbm.js +1 -0
- package/bin/{chunk-f15qyp41.js → chunk-a6gx7f5q.js} +1 -1
- package/bin/chunk-avwgktxb.js +2 -0
- package/bin/chunk-bkr5zm4h.js +2 -0
- package/bin/{chunk-2yxj593j.js → chunk-cbgq517y.js} +2 -2
- package/bin/chunk-d27mm390.js +1 -0
- package/bin/{chunk-185qefn1.js → chunk-dj92fss9.js} +2 -2
- package/bin/{chunk-v9w25rp2.js → chunk-dqxeztfa.js} +2 -2
- package/bin/chunk-drepsbb4.js +2 -0
- package/bin/chunk-f6svp4dp.js +2 -0
- package/bin/{chunk-q2bvyv39.js → chunk-fahk9h62.js} +2 -2
- package/bin/{chunk-v9b3w8q5.js → chunk-fb40xxz3.js} +2 -2
- package/bin/chunk-fnmwksnb.js +3 -0
- package/bin/chunk-fpc4p0j8.js +3 -0
- package/bin/{chunk-aqbrzx9z.js → chunk-fsyzs0tf.js} +1 -1
- package/bin/{chunk-e2mvmq2m.js → chunk-fxecgp5k.js} +1 -1
- package/bin/{chunk-wfzqnpc1.js → chunk-g3fpmyyn.js} +2 -2
- package/bin/{chunk-ehc9adfz.js → chunk-gc5sbfa5.js} +2 -2
- package/bin/chunk-gdm6yfqq.js +2 -0
- package/bin/{chunk-ea79xnn3.js → chunk-gk2q9a3f.js} +2 -2
- package/bin/{chunk-jje8nj8h.js → chunk-gt4csat6.js} +2 -2
- package/bin/chunk-gye8gabk.js +2 -0
- package/bin/{chunk-wry2hvrq.js → chunk-hk5rc6cd.js} +2 -2
- package/bin/{chunk-zqv0zhfb.js → chunk-hm0dkzed.js} +2 -2
- package/bin/chunk-hmpwg5za.js +16 -0
- package/bin/{chunk-rpywcvg1.js → chunk-j1tkmcae.js} +2 -2
- package/bin/chunk-j2bvj2yn.js +2 -0
- package/bin/chunk-jffktpqg.js +1 -0
- package/bin/chunk-jgs8an3h.js +18 -0
- package/bin/{chunk-8fmy5jtp.js → chunk-jmpb5633.js} +1 -1
- package/bin/{chunk-xp59apdb.js → chunk-jrjnqx78.js} +1 -1
- package/bin/chunk-k2k9vjq6.js +1 -0
- package/bin/{chunk-32pcmaqm.js → chunk-kpgfqkp0.js} +2 -2
- package/bin/{chunk-twdxayky.js → chunk-ks8xzc95.js} +2 -2
- package/bin/{chunk-qwqvt9v6.js → chunk-kswvyqq1.js} +2 -2
- package/bin/{chunk-gk3eqd50.js → chunk-m9pr03kn.js} +2 -2
- package/bin/chunk-mfn9qjm4.js +2 -0
- package/bin/{chunk-e99dv20z.js → chunk-msfw3jmc.js} +2 -2
- package/bin/chunk-mz0yjra0.js +5 -0
- package/bin/chunk-nbdw8fen.js +1 -0
- package/bin/{chunk-cak32x57.js → chunk-nkdk229f.js} +1 -1
- package/bin/chunk-nr20tvnw.js +3 -0
- package/bin/{chunk-ck8azecb.js → chunk-pazjhrnf.js} +5 -5
- package/bin/chunk-q806pqeh.js +1 -0
- package/bin/{chunk-abt0azmv.js → chunk-qka4mkmj.js} +2 -2
- package/bin/{chunk-0e4wawpq.js → chunk-qsr1a0rp.js} +1 -1
- package/bin/chunk-rchsme43.js +3 -0
- package/bin/{chunk-tf28796q.js → chunk-reyxk4bw.js} +1 -1
- package/bin/{chunk-av1a8fqp.js → chunk-rhvv1vvk.js} +2 -2
- package/bin/{chunk-a32vreya.js → chunk-rq0n0vcc.js} +2 -2
- package/bin/chunk-rqf7999q.js +42 -0
- package/bin/chunk-rssgmj7x.js +2 -0
- package/bin/chunk-ryzz5fht.js +2 -0
- package/bin/chunk-s2fnfyn9.js +2 -0
- package/bin/{chunk-83e12sjg.js → chunk-s2k4qntr.js} +2 -2
- package/bin/{chunk-c007p0t8.js → chunk-snhsjs4x.js} +56 -56
- package/bin/{chunk-j8fxp8ej.js → chunk-t2hy6tj9.js} +1 -1
- package/bin/chunk-t7nsgg5k.js +4 -0
- package/bin/chunk-tm7f32c7.js +14 -0
- package/bin/{chunk-2291ehh5.js → chunk-trveq4wg.js} +2 -2
- package/bin/chunk-vap4k11j.js +20 -0
- package/bin/chunk-vm5fx7td.js +3 -0
- package/bin/chunk-vy8gntez.js +1 -0
- package/bin/{chunk-awfwk64v.js → chunk-vyzptrea.js} +2 -2
- package/bin/{chunk-hfh0c082.js → chunk-w4ghe71n.js} +1 -1
- package/bin/chunk-wdsf44hs.js +2 -0
- package/bin/chunk-wjyaezs7.js +2 -0
- package/bin/{chunk-3a13dcs1.js → chunk-wndm3px3.js} +1 -1
- package/bin/chunk-x5jwwvs0.js +1 -0
- package/bin/chunk-x92cq59c.js +1 -0
- package/bin/{chunk-vgn5zcpv.js → chunk-xa18z1py.js} +2 -2
- package/bin/{chunk-4v5n0ayb.js → chunk-xarsrs08.js} +1 -1
- package/bin/{chunk-66hsjnw6.js → chunk-xx337zcw.js} +2 -2
- package/bin/chunk-xz6713tj.js +2 -0
- package/bin/chunk-yfnem6se.js +2 -0
- package/bin/{chunk-m7m9d4fb.js → chunk-ytdwk2fq.js} +2 -2
- package/bin/{chunk-jy006gcv.js → chunk-ze20rm02.js} +4 -4
- package/bin/chunk-zw86wnwe.js +7 -0
- package/bin/{chunk-h3tbf521.js → chunk-zxk7q0zk.js} +1 -1
- package/bin/shumai-app.html +1 -1
- package/bin/shumai-app.js +773 -776
- package/package.json +7 -7
- package/prisma/migrations/20260907021754_add_asset_upload_id/migration.sql +2 -0
- package/prisma/schema.prisma +1 -0
- package/bin/chunk-1kw2mbqb.js +0 -1
- package/bin/chunk-1wm6ptdx.js +0 -1
- package/bin/chunk-2520aq8j.js +0 -2
- package/bin/chunk-29zdp63z.js +0 -3
- package/bin/chunk-3swpwb9v.js +0 -1
- package/bin/chunk-3wmcx2bv.js +0 -2
- package/bin/chunk-5a8nt4me.js +0 -1
- package/bin/chunk-6bhn1p8v.js +0 -211
- package/bin/chunk-70c3xrgd.js +0 -2
- package/bin/chunk-7esm0hqb.js +0 -2
- package/bin/chunk-7fst8kdw.js +0 -12
- package/bin/chunk-8zqgaxvv.js +0 -1
- package/bin/chunk-a3dmtt2j.js +0 -1
- package/bin/chunk-ce8m4zeg.js +0 -3
- package/bin/chunk-e7mqtkzn.js +0 -2
- package/bin/chunk-ejbvfj4r.js +0 -1
- package/bin/chunk-ekfem7kf.js +0 -1
- package/bin/chunk-etwkk0xh.js +0 -1
- package/bin/chunk-evrdd32b.js +0 -2
- package/bin/chunk-fm6p03ad.js +0 -2
- package/bin/chunk-fyha3r13.js +0 -2
- package/bin/chunk-g0vs7k2x.js +0 -1
- package/bin/chunk-g84z2w7v.js +0 -16
- package/bin/chunk-h837fyed.js +0 -2
- package/bin/chunk-j20e0qsw.js +0 -7
- package/bin/chunk-n1jwdb0a.js +0 -1
- package/bin/chunk-p5gf1zdm.js +0 -4
- package/bin/chunk-pfgxggaj.js +0 -11
- package/bin/chunk-q16490pv.js +0 -2
- package/bin/chunk-qh81zhg1.js +0 -1
- package/bin/chunk-qwp3kwbz.js +0 -2
- package/bin/chunk-qydeqgyj.js +0 -5
- package/bin/chunk-r7dty1tg.js +0 -2
- package/bin/chunk-rhdxwebf.js +0 -2
- package/bin/chunk-rhh716z0.js +0 -42
- package/bin/chunk-rza4ae5z.js +0 -3
- package/bin/chunk-sk4e6rb1.js +0 -1
- package/bin/chunk-t2n1dbgx.js +0 -4
- package/bin/chunk-x8f4defx.js +0 -3
- package/bin/chunk-z3gkt8w1.js +0 -3
- package/bin/chunk-zh6fqq44.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h,v,u,C,B,t,o,Q,ai,L,U,Me,Rn,Ue,A,Z,Kt,E,S,Re,at,mc,hc,n_,zu,di,Y_,qm,xo,JS,So,We,Ye,Je,Xe,et,tt,rt,nt,fe,ce,pe,qe,ue,q,st,Tt,R,Kr,Dr,Ht,pr,Co,kg}from"./chunk-6bhn1p8v.js";import{To,ea}from"./chunk-3wmcx2bv.js";import"./chunk-ehc9adfz.js";import{Wr}from"./chunk-b9yrw9et.js";import{ns}from"./chunk-6gg1ymer.js";import{Cl,is}from"./chunk-c007p0t8.js";import{qs,Al,yl}from"./chunk-e7mqtkzn.js";import"./chunk-k7hss0bd.js";import{br}from"./chunk-cqb415s6.js";import"./chunk-gk3eqd50.js";import"./chunk-9t1ne8xr.js";import"./chunk-m7m9d4fb.js";import"./chunk-1yacmegc.js";import"./chunk-r7dty1tg.js";import"./chunk-2yxj593j.js";C();var Ft=({item:n})=>{if(n.preview?.thumbnailUrl)return t("img",{src:n.preview.thumbnailUrl,alt:"Preview",className:"w-full h-full object-cover"});if(n.preview?.proxyType==="audio"||n.proxyType==="audio")return t("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:t(To,{className:"w-5 h-5 text-muted-foreground"})});return t("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:t(Kt,{className:"w-5 h-5 text-muted-foreground"})})},Te=({projectId:n,currentAssetId:s,parentFolderId:x,initialFiles:d,initialNextCursor:k})=>{let{ref:a,inView:M}=Tt({threshold:0,rootMargin:"200px"}),b=v(null),N=v(!0),[c,p]=u(d),[f,W]=u(k),[X,J]=u(!!k),[V,g]=u(!1);return h(()=>{p(d),W(k),J(!!k),N.current=!0},[d,k]),h(()=>{(async()=>{if(!f||V||!M||!X)return;g(!0);try{let y=await A.api.folders[":folderId"].search.$post({param:{folderId:x},json:{assetType:"file",after:f,first:200,recursively:!1,conditions:[]}});if(!y.ok)throw Error("Failed to fetch next page");let P=await y.json(),z=P.data||[];p((Y)=>[...Y,...z]),W(P.pageInfo?.cursor||void 0),J(!!P.pageInfo?.cursor&&z.length>0)}catch(y){console.error("Error fetching next page:",y)}finally{g(!1)}})()},[M,f,X,V,x]),h(()=>{if(c.some((y)=>y?.id===s)&&b.current)if(N.current)b.current.scrollIntoView({block:"center",inline:"center",behavior:"auto"}),N.current=!1;else b.current.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})},[c,s]),t("div",{className:"h-24 md:h-full w-full md:w-24 bg-gray-100 dark:bg-gray-950 flex flex-row md:flex-col flex-shrink-0 select-none",children:o("div",{className:"flex-1 overflow-x-auto overflow-y-hidden md:overflow-y-auto md:overflow-x-hidden px-4 md:px-0 py-2 md:py-4 flex flex-row md:flex-col items-center gap-3 no-scrollbar",children:[c.map((m)=>{if(!m)return null;let y=m.id===s;return t("div",{ref:m.id===s?b:null,className:"flex-shrink-0",children:o(Rn,{to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:m.id},search:{version:void 0},className:E("rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block relative",y?"w-[62px] h-[62px] opacity-100":"w-[52px] h-[52px] opacity-60 hover:opacity-100"),children:[t(Ft,{item:m}),m.agent&&t("span",{className:"absolute top-1 right-1 z-10 pointer-events-none select-none rounded bg-black/60 px-1 py-0.5 text-[10px] font-medium leading-none text-white",title:m.agent.name,"data-testid":"carousel-agent-badge",children:"AI"})]})},m.id)}),X&&t("div",{ref:a,className:"px-2 md:px-0 py-2 md:py-4 flex justify-center items-center h-full md:w-full flex-shrink-0",children:V&&t(Z,{className:"h-5 w-5 animate-spin text-muted-foreground"})})]})})};C();function kt(){let{projectId:n,fileId:s}=$e.useParams(),x=$e.useSearch(),{version:d,start:k}=x,a=d||s,{cmpLeft:M,cmpRight:b}=x,N=x.cmpActive??"left",c=!!x.compare&&!!M&&!!b,p=v(null),{teamId:f,ensureTeamIdForProject:W}=st(),[X,J]=u(360),[V,g]=u([]),{fileViewRightSidebarCollapsed:m}=Ht(),{isChatbotOpen:y}=pr(),[P,z]=u(0),[Y,_]=u(null),[he,Ne]=u(null),[Le,ge]=u(void 0),[K,ne]=u({show:!1,files:[],nextCursor:void 0,folderId:void 0}),Ee=A.api.files[":fileId"].metadata.$patch,{mutate:Ve}=U({mutationFn:async(e)=>{let r=await Ee(e);if(!r.ok)throw Error("Failed to patch metadata");return await r.json()}}),G=Q(),{members:Pe,fetchProjectMembers:ye}=Dr(),ze=Co();h(()=>{W(n)},[n,W]),h(()=>{if(n)ye(n,!0)},[n,ye]),h(()=>{if(n&&s)A.api.projects[":projectId"].recents.view.$post({param:{projectId:n},json:{assetId:s}}).catch(()=>{})},[n,s]);let{data:Ie,isLoading:_e,isError:Ke,isFetching:Oe}=L({queryKey:["files",s],queryFn:async()=>{let e=await A.api.files[":fileId"].$get({param:{fileId:s}});if(!e.ok)throw Error("Failed to fetch stack");return await e.json()},enabled:!!f,placeholderData:ai}),{data:He,isLoading:Qe,isError:Be,isFetching:Ge}=L({queryKey:["files",d],queryFn:async()=>{let e=await A.api.files[":fileId"].$get({param:{fileId:d}});if(!e.ok)throw Error("Failed to fetch version");return await e.json()},enabled:!!f&&!!d,placeholderData:ai}),{data:Ze}=L({queryKey:["version_stacks",s,"versions"],queryFn:async()=>{let e=await A.api.version_stacks[":stackId"].versions.$get({param:{stackId:s}});if(!e.ok)throw Error("Failed to fetch versions");return await e.json()},enabled:!!n&&!!s&&(!!d||c)}),{data:j}=L({queryKey:["projects",n],queryFn:async()=>{let e=await A.api.projects[":projectId"].$get({param:{projectId:n}});if(!e.ok)throw Error("Failed to fetch project");return await e.json()}}),I=Me(),{setProjectState:ve,clearProjectState:we}=Kr(),ot=_e||!!d&&Qe,it=Ke||!!d&&Be,lt=Oe||!!d&&Ge,i=He||Ie,F=d?Ze:Ie?.versionStack?.versions,l=i?.ancestorFolders?.[0]?.id??j?.rootFolder??"",[re,ee]=u(!1),[te,xe]=u(""),se=v(null),ae=v(!1),[ct,ie]=u(!1),dt=A.api.files[":fileId"].$put,{mutate:ft,mutateAsync:pt,isPending:be}=U({mutationFn:async(e)=>{let r=await dt(e);if(!r.ok)throw Error("Failed to rename file");return await r.json()},onSuccess:()=>{G.invalidateQueries({queryKey:["files"]}),G.invalidateQueries({queryKey:["version_stacks"]}),R.success(JS?.()||"Renamed successfully"),ee(!1)},onError:()=>{R.error(Y_?.()||"Failed to rename")}}),ut=A.api.files.$delete,{mutate:mt,mutateAsync:ht,isPending:Fe}=U({mutationFn:async(e)=>{if(!(await ut(e)).ok)throw Error("Failed to delete file")},onSuccess:()=>{if(G.invalidateQueries({queryKey:["files"]}),G.invalidateQueries({queryKey:["version_stacks"]}),R.success(n_?.()||"Deleted"),ie(!1),l&&l!==j?.rootFolder)I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:l}});else I({to:"/projects/$projectId",params:{projectId:n}})},onError:()=>{R.error(di?.()||"Failed to delete")}}),gt=(e)=>{if(e?.preventDefault(),!te.trim()||!a)return;ft({param:{fileId:a},json:{name:te.trim()}})},yt=()=>{if(!a)return;mt({json:{ids:[a]}})};h(()=>{if(i&&j&&f)ve({teamId:f,projectId:n,projectName:j.name??"",ancestorFolders:i.ancestorFolders??[],currentAsset:{id:a||s,name:i.name,type:"file",version:F?F.find((e)=>e.id===a)?.version??F.length:void 0,proxyType:i.proxyType},isRootFolder:!1,fileId:s,downloadInfo:{originalKey:i.media?.original?.key,videoTranscodes:i.media?.videoTranscodes?.map((e)=>({key:e.key,width:e.width,height:e.height}))},versions:F,compareMode:c,canCompareVersions:(F?.length??0)>=2,onCompareVersions:()=>{let e=Cl(F);if(!e)return;I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,version:void 0,compare:!0,cmpLeft:e.left.id,cmpRight:e.right.id,cmpActive:"left"})})},onFolderClick:(e)=>{I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:e}})},onRename:()=>{ae.current=!1,xe(i?.name??""),ee(!0)},onDelete:()=>{ie(!0)}});return()=>we()},[f,n,j,i,F,a,s,c,ve,we,I]),h(()=>{if(!re)return;let e=setTimeout(()=>{ae.current=!0},1000);return()=>clearTimeout(e)},[re]);let It=()=>{if(ae.current)return;setTimeout(()=>{if(se.current)ea(se.current)},0)};if(h(()=>{if(!l||!a)return;if(K.folderId===l)return;let e=!0;return(async()=>{try{let w="",D=!1,T=[],de=void 0;for(let Ce=0;Ce<5;Ce++){let De=await A.api.folders[":folderId"].search.$post({param:{folderId:l},json:{assetType:"file",after:w,first:200,recursively:!1,conditions:[]}});if(!De.ok)throw Error("Failed to search parent folder for carousel");let H=await De.json(),me=H.data||[];if(T.push(...me),me.some((oe)=>oe.id===a)){if(D=!0,de=H.pageInfo?.cursor||void 0,H.pageInfo?.cursor)try{let oe=await A.api.folders[":folderId"].search.$post({param:{folderId:l},json:{assetType:"file",after:H.pageInfo.cursor,first:200,recursively:!1,conditions:[]}});if(oe.ok){let Se=await oe.json(),bt=Se.data||[];T.push(...bt),de=Se.pageInfo?.cursor||void 0}}catch{}break}if(!H.pageInfo?.cursor||me.length<200)break;w=H.pageInfo.cursor}if(e)if(D)ne({show:!0,files:T,nextCursor:de,folderId:l});else ne({show:!1,files:[],nextCursor:void 0,folderId:l})}catch(w){if(console.error(w),e)ne({show:!1,files:[],nextCursor:void 0,folderId:l})}})(),()=>{e=!1}},[l,a,K.folderId]),h(()=>{z(0),_(null),g([])},[i?.id]),h(()=>{_(null),g([])},[he?.id]),h(()=>{Wr.getState().reset(),Wr.getState().setIsDrawing(!1),g([]),_(null)},[a]),ot&&!i)return t(kg,{});if(it||!i||!j||!f)return t("div",{children:qm()});let O=c?he:i,ke=O?.id??a,je=(e,r)=>{if(!f)return;Ve({param:{fileId:ke},json:[{key:e,value:r}]},{onSuccess:()=>{G.invalidateQueries({queryKey:["files",ke]})}})},le=(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,...e})})},vt=()=>{le({compare:void 0,cmpLeft:void 0,cmpRight:void 0,cmpActive:void 0,version:N==="left"?M:b})},wt=(e)=>{_(e.id||null);let r=e.annotations;if(r&&r.length>0)g(r);else g([]);if(c){if(e.second!==null&&e.second!==void 0)ge({second:e.second,nonce:Date.now()});return}if(e.second!==null&&e.second!==void 0)p.current?.seekTo(e.second),p.current?.pause();else if(r&&r.length>0)p.current?.pause()},xt=(e)=>{_(e.id||null);let w=e.details,D=w?.annotations;if(D&&D.length>0)g(D);else g([]);let T=w?.position?.type==="time"?w.position.seconds:w?.position?.type==="page"?w.position.page:void 0;if(c){if(T!==void 0)ge({second:T,nonce:Date.now()});return}if(T!==void 0)p.current?.seekTo(T),p.current?.pause();else if(D&&D.length>0)p.current?.pause()},Ae=()=>{g([]),_(null)};if(ze&&!c)return t(Al,{projectId:n,teamId:f,fileId:s,file:i,projectInfo:j,ancestorFolders:i.ancestorFolders??[],parentFolderId:l,versions:F,activeFileId:a,startTime:k,siblingFiles:K.files,onNavigateToFile:(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:e}})},onNavigateBack:()=>{if(l&&l!==j?.rootFolder)I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:l}});else I({to:"/projects/$projectId",params:{projectId:n}})},onSelectVersion:(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,version:e})})},onRenameFile:async(e)=>{await pt({param:{fileId:a},json:{name:e}})},onDeleteFile:async()=>{await ht({json:{ids:[a]}})},onSaveField:je});return o("div",{className:"h-full flex flex-1 flex-col bg-background",children:[o("div",{className:"h-full flex flex-1 overflow-hidden",children:[o("div",{className:"flex-1 relative",children:[lt&&!c&&t("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:t(Z,{className:"h-8 w-8 animate-spin text-foreground"})}),c&&M&&b?t(yl,{versions:F??[],leftId:M,rightId:b,activeSide:N,annotations:V,seekRequest:Le,onActiveSideChange:(e)=>le({cmpActive:e}),onSwitchVersion:(e,r)=>le(e==="left"?{cmpLeft:r}:{cmpRight:r}),onExit:vt,onActiveAssetChange:Ne,onPlay:Ae,onTimeUpdate:z}):t(qs,{file:i,mediaControllerRef:p,onPlay:Ae,onTimeUpdate:z,annotations:V,startTime:k,children:K.show&&t(Te,{projectId:n,currentAssetId:a,parentFolderId:l,initialFiles:K.files,initialNextCursor:K.nextCursor})})]}),(!m||y)&&o(B,{children:[t(br,{onResize:(e)=>{J((r)=>Math.max(300,Math.min(600,r-e)))},className:"hidden md:block"}),t("div",{style:{width:X},className:"flex-shrink-0 bg-background flex flex-col",children:y?t(ns,{projectId:n,contextAssetId:a,file:O,currentTime:P,frameRate:O?.media?.metadata?.frameRate||30,startTimecode:O?.media?.metadata?.startTimecode,onTyping:()=>{if(c)return;p.current?.pause()},onSelectMessage:xt,selectedMessageId:Y}):t(is,{teamId:f,projectId:n,file:O,onSaveField:je,members:Pe,onCommentSelect:wt,currentTime:P,onTyping:()=>{if(c)return;p.current?.pause()},selectedCommentId:Y,hideAnnotationControl:O?.proxyType==="audio"})})]})]}),t(fe,{open:re,onOpenChange:ee,children:t(ce,{children:o("form",{onSubmit:gt,children:[t(pe,{children:t(ue,{children:xo()})}),t("div",{className:"py-4",children:t(q,{ref:se,value:te,onChange:(e)=>xe(e.target.value),placeholder:zu?.()||"Enter new name",onFocus:It,autoFocus:!0})}),o(qe,{children:[t(S,{type:"button",variant:"outline",onClick:()=>ee(!1),children:Re()}),o(S,{type:"submit",disabled:be||!te.trim(),children:[be&&t(Z,{className:"mr-2 h-4 w-4 animate-spin"}),So()]})]})]})})}),t(We,{open:ct,onOpenChange:ie,children:o(Ye,{children:[o(Je,{children:[t(et,{children:hc?.()||"Delete Asset?"}),t(tt,{children:mc?.()||"Deleted items can be recovered for 30 days before being permanently deleted."})]}),o(Xe,{children:[t(nt,{children:Re()}),o(rt,{onClick:yt,disabled:Fe,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[Fe&&t(Z,{className:"mr-2 h-4 w-4 animate-spin"}),at()]})]})]})})]})}var $e=Ue("/projects/$projectId/files/$fileId")({component:kt});export{$e as Route};
|
|
1
|
+
import{h,w,u,C,B,t,o,K,wi,Z,U,Re,Zn,Fe,A,L,Xt,E,S,ke,at,Nc,Oc,C_,id,Ii,_b,dh,No,bC,Oo,Je,Xe,et,tt,rt,nt,ot,st,pe,ue,me,$e,de,H,it,Mt,R,en,Ur,Qt,yr,Do,Xg}from"./chunk-7rhz2gze.js";import{Zo,ps}from"./chunk-7kjgvxqa.js";import"./chunk-gc5sbfa5.js";import{tn}from"./chunk-77fmkpdz.js";import{ga}from"./chunk-1j27fzy1.js";import{Zl,ba}from"./chunk-snhsjs4x.js";import{ni,Nl,Ol}from"./chunk-f6svp4dp.js";import"./chunk-914bp49r.js";import{Sr}from"./chunk-0qaq0sp8.js";import"./chunk-m9pr03kn.js";import"./chunk-5adsx8x4.js";import"./chunk-j2bvj2yn.js";import"./chunk-cbgq517y.js";import"./chunk-ytdwk2fq.js";import"./chunk-0zv3bks2.js";C();var Ft=({item:n})=>{if(n.preview?.thumbnailUrl)return t("img",{src:n.preview.thumbnailUrl,alt:"Preview",className:"w-full h-full object-cover"});if(n.preview?.proxyType==="audio"||n.proxyType==="audio")return t("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:t(Zo,{className:"w-5 h-5 text-muted-foreground"})});return t("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:t(Xt,{className:"w-5 h-5 text-muted-foreground"})})},Ne=({projectId:n,currentAssetId:s,parentFolderId:x,initialFiles:d,initialNextCursor:k})=>{let{ref:a,inView:M}=Mt({threshold:0,rootMargin:"200px"}),b=w(null),N=w(!0),[c,p]=u(d),[f,W]=u(k),[X,J]=u(!!k),[V,g]=u(!1);return h(()=>{p(d),W(k),J(!!k),N.current=!0},[d,k]),h(()=>{(async()=>{if(!f||V||!M||!X)return;g(!0);try{let y=await A.api.folders[":folderId"].search.$post({param:{folderId:x},json:{assetType:"file",after:f,first:200,recursively:!1,conditions:[]}});if(!y.ok)throw Error("Failed to fetch next page");let q=await y.json(),P=q.data||[];p((Y)=>[...Y,...P]),W(q.pageInfo?.cursor||void 0),J(!!q.pageInfo?.cursor&&P.length>0)}catch(y){console.error("Error fetching next page:",y)}finally{g(!1)}})()},[M,f,X,V,x]),h(()=>{if(c.some((y)=>y?.id===s)&&b.current)if(N.current)b.current.scrollIntoView({block:"center",inline:"center",behavior:"auto"}),N.current=!1;else b.current.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})},[c,s]),t("div",{className:"h-24 md:h-full w-full md:w-24 bg-gray-100 dark:bg-gray-950 flex flex-row md:flex-col flex-shrink-0 select-none",children:o("div",{className:"flex-1 overflow-x-auto overflow-y-hidden md:overflow-y-auto md:overflow-x-hidden px-4 md:px-0 py-2 md:py-4 flex flex-row md:flex-col items-center gap-3 no-scrollbar",children:[c.map((m)=>{if(!m)return null;let y=m.id===s;return t("div",{ref:m.id===s?b:null,className:"flex-shrink-0",children:o(Zn,{to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:m.id},search:{version:void 0},className:E("rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block relative",y?"w-[62px] h-[62px] opacity-100":"w-[52px] h-[52px] opacity-60 hover:opacity-100"),children:[t(Ft,{item:m}),m.agent&&t("span",{className:"absolute top-1 right-1 z-10 pointer-events-none select-none rounded bg-black/60 px-1 py-0.5 text-[10px] font-medium leading-none text-white",title:m.agent.name,"data-testid":"carousel-agent-badge",children:"AI"})]})},m.id)}),X&&t("div",{ref:a,className:"px-2 md:px-0 py-2 md:py-4 flex justify-center items-center h-full md:w-full flex-shrink-0",children:V&&t(L,{className:"h-5 w-5 animate-spin text-muted-foreground"})})]})})};C();function kt(){let{projectId:n,fileId:s}=Le.useParams(),x=Le.useSearch(),{version:d,start:k}=x,a=d||s,{cmpLeft:M,cmpRight:b}=x,N=x.cmpActive??"left",c=!!x.compare&&!!M&&!!b,p=w(null),{teamId:f,ensureTeamIdForProject:W}=it(),[X,J]=u(360),[V,g]=u([]),{fileViewRightSidebarCollapsed:m}=Qt(),{isChatbotOpen:y}=yr(),[q,P]=u(0),[Y,z]=u(null),[he,Ee]=u(null),[Ve,ge]=u(void 0),[_,ne]=u({show:!1,files:[],nextCursor:void 0,folderId:void 0}),qe=A.api.files[":fileId"].metadata.$patch,{mutate:Pe}=U({mutationFn:async(e)=>{let r=await qe(e);if(!r.ok)throw Error("Failed to patch metadata");return await r.json()}}),G=K(),{members:ze,fetchProjectMembers:ye}=Ur(),_e=Do();h(()=>{W(n)},[n,W]),h(()=>{if(n)ye(n,!0)},[n,ye]),h(()=>{if(n&&s)A.api.projects[":projectId"].recents.view.$post({param:{projectId:n},json:{assetId:s}}).catch(()=>{})},[n,s]);let{data:Ie,isLoading:Ke,isError:Oe,isFetching:He}=Z({queryKey:["files",s],queryFn:async()=>{let e=await A.api.files[":fileId"].$get({param:{fileId:s}});if(!e.ok)throw Error("Failed to fetch stack");return await e.json()},enabled:!!f,placeholderData:wi}),{data:Qe,isLoading:Be,isError:Ue,isFetching:We}=Z({queryKey:["files",d],queryFn:async()=>{let e=await A.api.files[":fileId"].$get({param:{fileId:d}});if(!e.ok)throw Error("Failed to fetch version");return await e.json()},enabled:!!f&&!!d,placeholderData:wi}),{data:Ge}=Z({queryKey:["version_stacks",s,"versions"],queryFn:async()=>{let e=await A.api.version_stacks[":stackId"].versions.$get({param:{stackId:s}});if(!e.ok)throw Error("Failed to fetch versions");return await e.json()},enabled:!!n&&!!s&&(!!d||c)}),{data:j}=Z({queryKey:["projects",n],queryFn:async()=>{let e=await A.api.projects[":projectId"].$get({param:{projectId:n}});if(!e.ok)throw Error("Failed to fetch project");return await e.json()}}),I=Re(),{setProjectState:ve,clearProjectState:we}=en(),Ye=Ke||!!d&&Be,Ze=Oe||!!d&&Ue,lt=He||!!d&&We,i=Qe||Ie,F=d?Ge:Ie?.versionStack?.versions,l=i?.ancestorFolders?.[0]?.id??j?.rootFolder??"",[re,ee]=u(!1),[te,xe]=u(""),se=w(null),ae=w(!1),[ct,ie]=u(!1),dt=A.api.files[":fileId"].$put,{mutate:ft,mutateAsync:pt,isPending:be}=U({mutationFn:async(e)=>{let r=await dt(e);if(!r.ok)throw Error("Failed to rename file");return await r.json()},onSuccess:()=>{G.invalidateQueries({queryKey:["files"]}),G.invalidateQueries({queryKey:["version_stacks"]}),R.success(bC?.()||"Renamed successfully"),ee(!1)},onError:()=>{R.error(_b?.()||"Failed to rename")}}),ut=A.api.files.$delete,{mutate:mt,mutateAsync:ht,isPending:je}=U({mutationFn:async(e)=>{if(!(await ut(e)).ok)throw Error("Failed to delete file")},onSuccess:()=>{if(G.invalidateQueries({queryKey:["files"]}),G.invalidateQueries({queryKey:["version_stacks"]}),R.success(C_?.()||"Deleted"),ie(!1),l&&l!==j?.rootFolder)I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:l}});else I({to:"/projects/$projectId",params:{projectId:n}})},onError:()=>{R.error(Ii?.()||"Failed to delete")}}),gt=(e)=>{if(e?.preventDefault(),!te.trim()||!a)return;ft({param:{fileId:a},json:{name:te.trim()}})},yt=()=>{if(!a)return;mt({json:{ids:[a]}})};h(()=>{if(i&&j&&f)ve({teamId:f,projectId:n,projectName:j.name??"",ancestorFolders:i.ancestorFolders??[],currentAsset:{id:a||s,name:i.name,type:"file",version:F?F.find((e)=>e.id===a)?.version??F.length:void 0,proxyType:i.proxyType},isRootFolder:!1,fileId:s,downloadInfo:{originalKey:i.media?.original?.key,videoTranscodes:i.media?.videoTranscodes?.map((e)=>({key:e.key,width:e.width,height:e.height}))},versions:F,compareMode:c,canCompareVersions:(F?.length??0)>=2,onCompareVersions:()=>{let e=Zl(F);if(!e)return;I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,version:void 0,compare:!0,cmpLeft:e.left.id,cmpRight:e.right.id,cmpActive:"left"})})},onFolderClick:(e)=>{I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:e}})},onRename:()=>{ae.current=!1,xe(i?.name??""),ee(!0)},onDelete:()=>{ie(!0)}});return()=>we()},[f,n,j,i,F,a,s,c,ve,we,I]),h(()=>{if(!re)return;let e=setTimeout(()=>{ae.current=!0},1000);return()=>clearTimeout(e)},[re]);let It=()=>{if(ae.current)return;setTimeout(()=>{if(se.current)ps(se.current)},0)};if(h(()=>{if(!l||!a)return;if(_.folderId===l)return;let e=!0;return(async()=>{try{let v="",D=!1,T=[],ce=void 0;for(let Se=0;Se<5;Se++){let Te=await A.api.folders[":folderId"].search.$post({param:{folderId:l},json:{assetType:"file",after:v,first:200,recursively:!1,conditions:[]}});if(!Te.ok)throw Error("Failed to search parent folder for carousel");let Q=await Te.json(),fe=Q.data||[];if(T.push(...fe),fe.some((oe)=>oe.id===a)){if(D=!0,ce=Q.pageInfo?.cursor||void 0,Q.pageInfo?.cursor)try{let oe=await A.api.folders[":folderId"].search.$post({param:{folderId:l},json:{assetType:"file",after:Q.pageInfo.cursor,first:200,recursively:!1,conditions:[]}});if(oe.ok){let Me=await oe.json(),bt=Me.data||[];T.push(...bt),ce=Me.pageInfo?.cursor||void 0}}catch{}break}if(!Q.pageInfo?.cursor||fe.length<200)break;v=Q.pageInfo.cursor}if(e)if(D)ne({show:!0,files:T,nextCursor:ce,folderId:l});else ne({show:!1,files:[],nextCursor:void 0,folderId:l})}catch(v){if(console.error(v),e)ne({show:!1,files:[],nextCursor:void 0,folderId:l})}})(),()=>{e=!1}},[l,a,_.folderId]),h(()=>{P(0),z(null),g([])},[i?.id]),h(()=>{z(null),g([])},[he?.id]),h(()=>{tn.getState().reset(),tn.getState().setIsDrawing(!1),g([]),z(null)},[a]),Ye&&!i)return t(Xg,{});if(Ze||!i||!j||!f)return t("div",{children:dh()});let O=c?he:i,Ae=O?.id??a,Ce=(e,r)=>{if(!f)return;Pe({param:{fileId:Ae},json:[{key:e,value:r}]},{onSuccess:()=>{G.invalidateQueries({queryKey:["files",Ae]})}})},le=(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,...e})})},vt=()=>{le({compare:void 0,cmpLeft:void 0,cmpRight:void 0,cmpActive:void 0,version:N==="left"?M:b})},wt=(e)=>{z(e.id||null);let r=e.annotations;if(r&&r.length>0)g(r);else g([]);if(c){if(e.second!==null&&e.second!==void 0)ge({second:e.second,nonce:Date.now()});return}if(e.second!==null&&e.second!==void 0)p.current?.seekTo(e.second),p.current?.pause();else if(r&&r.length>0)p.current?.pause()},xt=(e)=>{z(e.id||null);let v=e.details,D=v?.annotations;if(D&&D.length>0)g(D);else g([]);let T=v?.position?.type==="time"?v.position.seconds:v?.position?.type==="page"?v.position.page:void 0;if(c){if(T!==void 0)ge({second:T,nonce:Date.now()});return}if(T!==void 0)p.current?.seekTo(T),p.current?.pause();else if(D&&D.length>0)p.current?.pause()},De=()=>{g([]),z(null)};if(_e&&!c)return t(Nl,{projectId:n,teamId:f,fileId:s,file:i,projectInfo:j,ancestorFolders:i.ancestorFolders??[],parentFolderId:l,versions:F,activeFileId:a,startTime:k,siblingFiles:_.files,onNavigateToFile:(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:e}})},onNavigateBack:()=>{if(l&&l!==j?.rootFolder)I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:l}});else I({to:"/projects/$projectId",params:{projectId:n}})},onSelectVersion:(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,version:e})})},onRenameFile:async(e)=>{await pt({param:{fileId:a},json:{name:e}})},onDeleteFile:async()=>{await ht({json:{ids:[a]}})},onSaveField:Ce});return o("div",{className:"h-full flex flex-1 flex-col bg-background",children:[o("div",{className:"h-full flex flex-1 overflow-hidden",children:[o("div",{className:"flex-1 relative",children:[lt&&!c&&t("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:t(L,{className:"h-8 w-8 animate-spin text-foreground"})}),c&&M&&b?t(Ol,{versions:F??[],leftId:M,rightId:b,activeSide:N,annotations:V,seekRequest:Ve,onActiveSideChange:(e)=>le({cmpActive:e}),onSwitchVersion:(e,r)=>le(e==="left"?{cmpLeft:r}:{cmpRight:r}),onExit:vt,onActiveAssetChange:Ee,onPlay:De,onTimeUpdate:P}):t(ni,{file:i,mediaControllerRef:p,onPlay:De,onTimeUpdate:P,annotations:V,startTime:k,children:_.show&&t(Ne,{projectId:n,currentAssetId:a,parentFolderId:l,initialFiles:_.files,initialNextCursor:_.nextCursor})})]}),(!m||y)&&o(B,{children:[t(Sr,{onResize:(e)=>{J((r)=>Math.max(300,Math.min(600,r-e)))},className:"hidden md:block"}),t("div",{style:{width:X},className:"flex-shrink-0 bg-background flex flex-col",children:y?t(ga,{projectId:n,contextAssetId:a,file:O,currentTime:q,frameRate:O?.media?.metadata?.frameRate||30,startTimecode:O?.media?.metadata?.startTimecode,onTyping:()=>{if(c)return;p.current?.pause()},onSelectMessage:xt,selectedMessageId:Y}):t(ba,{teamId:f,projectId:n,file:O,onSaveField:Ce,members:ze,onCommentSelect:wt,currentTime:q,onTyping:()=>{if(c)return;p.current?.pause()},selectedCommentId:Y,hideAnnotationControl:O?.proxyType==="audio"})})]})]}),t(pe,{open:re,onOpenChange:ee,children:t(ue,{children:o("form",{onSubmit:gt,children:[t(me,{children:t(de,{children:No()})}),t("div",{className:"py-4",children:t(H,{ref:se,value:te,onChange:(e)=>xe(e.target.value),placeholder:id?.()||"Enter new name",onFocus:It,autoFocus:!0})}),o($e,{children:[t(S,{type:"button",variant:"outline",onClick:()=>ee(!1),children:ke()}),o(S,{type:"submit",disabled:be||!te.trim(),children:[be&&t(L,{className:"mr-2 h-4 w-4 animate-spin"}),Oo()]})]})]})})}),t(Je,{open:ct,onOpenChange:ie,children:o(Xe,{children:[o(et,{children:[t(rt,{children:Oc?.()||"Delete Asset?"}),t(nt,{children:Nc?.()||"Deleted items can be recovered for 30 days before being permanently deleted."})]}),o(tt,{children:[t(st,{children:ke()}),o(ot,{onClick:yt,disabled:je,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[je&&t(L,{className:"mr-2 h-4 w-4 animate-spin"}),at()]})]})]})})]})}var Le=Fe("/projects/$projectId/files/$fileId")({component:kt});export{Le as Route};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function
|
|
3
|
-
export{
|
|
2
|
+
function As(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{As};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{
|
|
1
|
+
import{xt,D,N,St,O,w,C,t,E,as,dt,Y,Lt,se,zn,aa,cl,ul}from"./chunk-7rhz2gze.js";C();C();var S=Object.defineProperty,z=(s,e)=>S(s,"name",{value:e,configurable:!0}),M="Toggle",T=D(z(function(e,o){let{pressed:r,defaultPressed:n,onPressedChange:a,...g}=e,[l,i]=Lt({prop:r,onChange:a,defaultProp:n??!1,caller:M});return t(se.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":e.disabled?"":void 0,...g,ref:o,onClick:Y(e.onClick,()=>{if(!e.disabled)i(!l)})})},"Toggle"));C();var k=Object.defineProperty,p=(s,e)=>k(s,"name",{value:e,configurable:!0}),m="ToggleGroup",[b,ie]=dt(m,[aa]),R=aa(),F=D(p(function(e,o){let{type:r,...n}=e;if(r==="single")return t(A,{role:"radiogroup",...n,ref:o});if(r==="multiple")return t(j,{role:"toolbar",...n,ref:o});throw Error(`Missing prop \`type\` expected on \`${m}\``)},"ToggleGroup")),[h,x]=b(m),A=D(p(function(e,o){let{value:r,defaultValue:n,onValueChange:a=p(()=>{},"onValueChange"),...g}=e,[l,i]=Lt({prop:r,defaultProp:n??"",onChange:a,caller:m});return t(h,{scope:e.__scopeToggleGroup,type:"single",value:O(()=>l?[l]:[],[l]),onItemActivate:i,onItemDeactivate:N(()=>i(""),[i]),children:t(I,{...g,ref:o})})},"ToggleGroupImplSingle")),j=D(p(function(e,o){let{value:r,defaultValue:n,onValueChange:a=p(()=>{},"onValueChange"),...g}=e,[l,i]=Lt({prop:r,defaultProp:n??[],onChange:a,caller:m}),u=N((c)=>i((d=[])=>[...d,c]),[i]),f=N((c)=>i((d=[])=>d.filter((y)=>y!==c)),[i]);return t(h,{scope:e.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:u,onItemDeactivate:f,children:t(I,{...g,ref:o})})},"ToggleGroupImplMultiple")),[B,H]=b(m),I=D(p(function(e,o){let{__scopeToggleGroup:r,disabled:n=!1,rovingFocus:a=!0,orientation:g,dir:l,loop:i=!0,...u}=e,f=R(r),c=zn(l),d={dir:c,...u};return t(B,{scope:r,rovingFocus:a,disabled:n,children:a?t(cl,{asChild:!0,...f,orientation:g,dir:c,loop:i,children:t(se.div,{...d,ref:o})}):t(se.div,{...d,ref:o})})},"ToggleGroupImpl")),v="ToggleGroupItem",L=D(p(function(e,o){let r=x(v,e.__scopeToggleGroup),n=H(v,e.__scopeToggleGroup),a=R(e.__scopeToggleGroup),g=r.value.includes(e.value),l=n.disabled||e.disabled,i={...e,pressed:g,disabled:l},u=w(null);return n.rovingFocus?t(ul,{asChild:!0,...a,focusable:!l,active:g,ref:u,children:t(P,{...i,ref:o})}):t(P,{...i,ref:o})},"ToggleGroupItem")),P=D(p(function(e,o){let{__scopeToggleGroup:r,value:n,...a}=e,g=x(v,r),l={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=g.type==="single"?l:void 0;return t(T,{...i,...a,ref:o,onPressedChange:(u)=>{if(u)g.onItemActivate(n);else g.onItemDeactivate(n)}})},"ToggleGroupItemImpl"));var _=as("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 min-w-9 px-2",sm:"h-8 min-w-8 px-1.5",lg:"h-10 min-w-10 px-2.5"}},defaultVariants:{variant:"default",size:"default"}});var V=xt({size:"default",variant:"default",spacing:0});function Eo({className:s,variant:e,size:o,spacing:r=0,children:n,...a}){return t(F,{"data-slot":"toggle-group","data-variant":e,"data-size":o,"data-spacing":r,style:{"--gap":r},className:E("group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",s),...a,children:t(V.Provider,{value:{variant:e,size:o,spacing:r},children:n})})}function pr({className:s,children:e,variant:o,size:r,...n}){let a=St(V);return t(L,{"data-slot":"toggle-group-item","data-variant":a.variant||o,"data-size":a.size||r,"data-spacing":a.spacing,className:E(_({variant:a.variant||o,size:a.size||r}),"w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10","data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",s),...n,children:e})}
|
|
2
|
+
export{Eo,pr};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Jd,kn,nc,oc,sc,ac,mu,hu,em,nA,ys,zo,Fr}from"./chunk-nkdk229f.js";export{sc as EncryptJWT,oc as SignJWT,em as UnsecuredJWT,Jd as base64url,ac as calculateJwkThumbprint,mu as createLocalJWKSet,hu as createRemoteJWKSet,Fr as decodeJwt,zo as decodeProtectedHeader,ys as importJWK,nA as importPKCS8,nc as jwtDecrypt,kn as jwtVerify};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{T}from"./chunk-
|
|
2
|
-
export{
|
|
1
|
+
import{T}from"./chunk-7rhz2gze.js";var e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],pn=T("circle-alert",e);
|
|
2
|
+
export{pn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function c(e){if(!(e instanceof Error)||!("status"in e)||!("headers"in e))return!1;return(e.status===void 0||typeof e.status==="number")&&(e.headers===void 0||e.headers instanceof Headers)}function d(e){let t=e.headers?.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===void 0)return!0;return e.status===408||e.status===409||e.status===429||typeof e.status==="number"&&e.status>=500}function o(e,t,a){let r=t??60000;if(r>0&&e>r)throw Error(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s). ${a}`);return e}function l(e,t,a){let r=e.headers?.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(!Number.isNaN(s))return o(s,a,e.message)}let n=e.headers?.get("retry-after");if(n){let s=Number.parseFloat(n),f=Number.isNaN(s)?Date.parse(n)-Date.now():s*1000;return o(f,a,e.message)}return Math.min(0.5*2**t,8)*1000*(1-Math.random()*0.25)}function i(){let e=Error("Request aborted");return e.name="AbortError",e}function m(e,t){return new Promise((a,r)=>{if(t?.aborted){r(i());return}let n=()=>{clearTimeout(u),r(i())},u=setTimeout(()=>{t?.removeEventListener("abort",n),a()},Math.max(0,e));t?.addEventListener("abort",n,{once:!0})})}async function
|
|
3
|
-
export{
|
|
2
|
+
function c(e){if(!(e instanceof Error)||!("status"in e)||!("headers"in e))return!1;return(e.status===void 0||typeof e.status==="number")&&(e.headers===void 0||e.headers instanceof Headers)}function d(e){let t=e.headers?.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===void 0)return!0;return e.status===408||e.status===409||e.status===429||typeof e.status==="number"&&e.status>=500}function o(e,t,a){let r=t??60000;if(r>0&&e>r)throw Error(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s). ${a}`);return e}function l(e,t,a){let r=e.headers?.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(!Number.isNaN(s))return o(s,a,e.message)}let n=e.headers?.get("retry-after");if(n){let s=Number.parseFloat(n),f=Number.isNaN(s)?Date.parse(n)-Date.now():s*1000;return o(f,a,e.message)}return Math.min(0.5*2**t,8)*1000*(1-Math.random()*0.25)}function i(){let e=Error("Request aborted");return e.name="AbortError",e}function m(e,t){return new Promise((a,r)=>{if(t?.aborted){r(i());return}let n=()=>{clearTimeout(u),r(i())},u=setTimeout(()=>{t?.removeEventListener("abort",n),a()},Math.max(0,e));t?.addEventListener("abort",n,{once:!0})})}async function ts(e,t={}){let a=t.maxRetries??0,r=a;for(;;)try{return await e()}catch(n){if(t.signal?.aborted)throw i();if(r<=0||!c(n)||!d(n))throw n;let u=a-r;r--,await m(l(n,u,t.maxRetryDelayMs),t.signal)}}
|
|
3
|
+
export{ts};
|
|
@@ -12,7 +12,7 @@ ${p}`)}return a},l=ao(an);class We extends c{list(e,t={},r){return this._client.
|
|
|
12
12
|
${Or(e)}`);if(T==null)throw new m(`missing choices[${p}].tool_calls[${E}].type
|
|
13
13
|
${Or(e)}`);if(P==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.name
|
|
14
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.
|
|
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,Ge,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),Ge.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,Ge=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,Ge,"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,Ge,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ge,"f")!==void 0){let n=t.data.content[i(this,Ge,"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 ze 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)}}ze.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new ze(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=ze;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 Qe 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 Ke{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 Qe(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
16
|
|
|
17
17
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
18
18
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -21,4 +21,4 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
21
21
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
22
22
|
|
|
23
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};
|
|
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=Ke,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};Ke.OpenAI=Ps;Ke.DEFAULT_TIMEOUT=600000;Ke.OpenAIError=m;Ke.APIError=O;Ke.APIConnectionError=xe;Ke.APIConnectionTimeoutError=Ae;Ke.APIUserAbortError=F;Ke.NotFoundError=yt;Ke.ConflictError=bt;Ke.RateLimitError=xt;Ke.BadRequestError=mt;Ke.AuthenticationError=_t;Ke.InternalServerError=At;Ke.PermissionDeniedError=gt;Ke.UnprocessableEntityError=wt;Ke.InvalidWebhookSignatureError=se;Ke.toFile=Ir;Ke.Completions=Qe;Ke.Chat=Re;Ke.Embeddings=Ze;Ke.Files=tt;Ke.Images=ot;Ke.Audio=ce;Ke.Moderations=at;Ke.Models=it;Ke.FineTuning=te;Ke.Graders=Me;Ke.VectorStores=we;Ke.Webhooks=ht;Ke.Beta=ee;Ke.Batches=Ve;Ke.Uploads=Le;Ke.Responses=ye;Ke.Realtime=_e;Ke.Conversations=Fe;Ke.Evals=Ne;Ke.Containers=Te;Ke.Skills=be;Ke.Videos=ut;class pu extends Ke{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{Ke,pu};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function
|
|
3
|
-
export{
|
|
2
|
+
function je(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}function tc(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function rc(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let o=t.slice(e.input.length);if(!r&&o.length===0)return;let i="";if(!e.started)i+=`{${JSON.stringify(n)}:"`,e.started=!0;if(i+=JSON.stringify(o).slice(1,-1),e.input=t,r)i+='"}',e.closed=!0;return i}function C(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function io(e,n){let t=e.constrainedSampling;if(!t||t.type!=="json_schema")return;if(n)return!0;if(t.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Hi(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,o=t.variants.openai_regex,i=typeof r==="string"&&r.trim().length>0,d=typeof o==="string"&&o.trim().length>0;if(!i&&!d)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:i?"lark":"regex",definition:i?r:o,inputProperty:C(e)}}catch(l){let c=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${c}.`)}}function $n(e,n){let t=new Map;for(let r of e??[]){let o=Hi(r,n);if(o)t.set(r.name,o.inputProperty)}return t}function R(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function S(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function N(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:4800;return n}function k(e){return Math.ceil(e.length/4)}function y(e){return Math.ceil(N(e)/4)}function I(e){let n=0;if(e.role==="user")return y(e.content);if(e.role==="toolResult")return y(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+S(t.arguments).length;return Math.ceil(n/4)}function O(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let o=e[r];if(o.role==="assistant"){let i=o;if(i.timestamp>=n&&i.stopReason!=="aborted"&&i.stopReason!=="error"&&R(i.usage)>0)t={usage:i.usage,index:r}}n=Math.max(n,o.timestamp)}return t}function E(e){let n=O(e);if(n){let r=R(n.usage),o=0;for(let i=n.index+1;i<e.length;i++)o+=I(e[i]);return{tokens:r+o,usageTokens:r,trailingTokens:o,lastUsageIndex:n.index}}let t=0;for(let r of e)t+=I(r);return{tokens:t,usageTokens:0,trailingTokens:t,lastUsageIndex:null}}function M(e){if(!e||e.length===0)return 0;return k(S(e))}function D(e){return Array.isArray(e)}function w(e){if(D(e))return E(e);let n=E(e.messages);if(n.lastUsageIndex!==null){let r=new Set(e.messages.slice(n.lastUsageIndex+1).filter((i)=>i.role==="toolResult").flatMap((i)=>i.addedToolNames??[])),o=M(e.tools?.filter((i)=>r.has(i.name)));return{tokens:n.tokens+o,usageTokens:n.usageTokens,trailingTokens:n.trailingTokens+o,lastUsageIndex:n.lastUsageIndex}}let t=(e.systemPrompt?k(e.systemPrompt):0)+M(e.tools);return{tokens:n.tokens+t,usageTokens:n.usageTokens,trailingTokens:n.trailingTokens+t,lastUsageIndex:n.lastUsageIndex}}var P=4096,_=1;function Kd(e,n,t){if(e.contextWindow<=0)return Math.max(_,t);let r=e.contextWindow-w(n).tokens-P;return Math.min(t,Math.max(_,r))}function Cr(e,n,t,r){return{temperature:t?.temperature,maxTokens:Kd(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,apiKey:r||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}function v(e){return e==="xhigh"||e==="max"?"high":e}function Xp(e,n,t,r){let i={...{minimal:1024,low:2048,medium:8192,high:16384},...r},d=1024,l=v(t),c=i[l],f=e===void 0?n:Math.min(e+c,n);if(f<=c)c=Math.max(0,f-1024);return{maxTokens:f,thinkingBudget:c}}function A(e,n){let t=[],r=!1;for(let o of e){if(o.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(o),r=o.text===n}return t}function F(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:A(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:A(t.content,"(tool image omitted: model does not support images)")};return t})}function lo(e,n,t){let r=new Map,o=e.map((a)=>a.content==null?{...a,content:[]}:a),d=F(o,n).map((a)=>{if(a.role==="user")return a;if(a.role==="toolResult"){let s=r.get(a.toolCallId);if(s&&s!==a.toolCallId)return{...a,toolCallId:s};return a}if(a.role==="assistant"){let s=a,p=s.provider===n.provider&&s.api===n.api&&s.model===n.id,h=s.content.flatMap((u)=>{if(u.type==="thinking"){if(u.redacted)return p?u:[];if(p&&u.thinkingSignature)return u;if(!u.thinking||u.thinking.trim()==="")return[];if(p)return u;return{type:"text",text:u.thinking}}if(u.type==="text"){if(p)return u;return{type:"text",text:u.text}}if(u.type==="toolCall"){let m=u,g=m;if(!p&&m.thoughtSignature)g={...m},delete g.thoughtSignature;if(!p&&t){let x=t(m.id,n,s);if(x!==m.id)r.set(m.id,x),g={...g,id:x}}return g}return u});return{...s,content:h}}return a}),l=[],c=[],f=new Set,T=()=>{if(c.length>0){for(let a of c)if(!f.has(a.id))l.push({role:"toolResult",toolCallId:a.id,toolName:a.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});c=[],f=new Set}};for(let a=0;a<d.length;a++){let s=d[a];if(s.role==="assistant"){T();let p=s;if(p.stopReason==="error"||p.stopReason==="aborted")continue;let h=p.content.filter((u)=>u.type==="toolCall");if(h.length>0)c=h,f=new Set;l.push(s)}else if(s.role==="toolResult")f.add(s.toolCallId),l.push(s);else if(s.role==="user")T(),l.push(s);else l.push(s)}return T(),l}
|
|
3
|
+
export{je,tc,rc,io,Hi,$n,Kd,Cr,Xp,lo};
|