@shumai-one/shumai-agent 0.4.2 → 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-07a5rjnq.js +2 -0
- package/bin/chunk-1a493esq.js +2 -0
- package/bin/chunk-1y3q1jce.js +2 -0
- package/bin/chunk-2mcnt6jh.js +8 -0
- package/bin/chunk-33n9p9q4.js +3 -0
- package/bin/chunk-40bcg5we.js +2 -0
- package/bin/chunk-4926dhzq.js +4 -0
- package/bin/chunk-4q9h14c1.js +3 -0
- package/bin/chunk-5n4wvh5p.js +3 -0
- package/bin/chunk-6195gx01.js +8 -0
- package/bin/chunk-8jd9p0bt.js +45 -0
- package/bin/chunk-8tj47emj.js +2 -0
- package/bin/chunk-9bpp5v13.js +13320 -0
- package/bin/chunk-a4xcn19j.js +3 -0
- package/bin/chunk-as1vqgag.js +2 -0
- package/bin/chunk-b2205272.js +3 -0
- package/bin/chunk-bbz8hcag.js +2 -0
- package/bin/chunk-cwq65x99.js +2 -0
- package/bin/chunk-dc4f80kq.js +2 -0
- package/bin/chunk-e7m6nsvr.js +3 -0
- package/bin/chunk-edkxjkdy.js +2 -0
- package/bin/chunk-fvz08he3.js +2 -0
- package/bin/chunk-gekdwjxf.js +2 -0
- package/bin/chunk-gqtret3n.js +2 -0
- package/bin/chunk-grtavkr4.js +3 -0
- package/bin/chunk-h65eqsrp.js +7 -0
- package/bin/chunk-hbmbvjjq.js +3 -0
- package/bin/chunk-jkx975yd.js +2 -0
- package/bin/chunk-jt36jdn3.js +2 -0
- package/bin/chunk-k975ym8c.js +7 -0
- package/bin/chunk-kd561cva.js +2 -0
- package/bin/chunk-m8jmvj7p.js +3 -0
- package/bin/chunk-nmxr1m3s.js +2 -0
- package/bin/chunk-nwjh8gnr.js +3 -0
- package/bin/chunk-s1e2nv5w.js +5 -0
- package/bin/chunk-sbtjx4y3.js +2 -0
- package/bin/chunk-sfx1j3yr.js +11 -0
- package/bin/chunk-sq5rat8t.js +2 -0
- package/bin/chunk-td2tpqfb.js +12 -0
- package/bin/chunk-tdah647g.js +13 -0
- package/bin/chunk-vnn8sej7.js +24 -0
- package/bin/chunk-vv932dz6.js +2 -0
- package/bin/chunk-vvvkt1vd.js +2 -0
- package/bin/chunk-wdvv14a7.js +2 -0
- package/bin/chunk-wg6xrc3y.js +3 -0
- package/bin/chunk-wzysrq4c.js +16 -0
- package/bin/chunk-xp2anj2s.js +3 -0
- package/bin/chunk-y2adfzyt.js +2 -0
- package/bin/chunk-zdkpvcak.js +4 -0
- package/bin/shumai-agent-app.js +912 -666
- package/package.json +18 -18
- package/prisma/migrations/20260904022457_add_agent_id_to_assets_and_audit_logs/migration.sql +17 -0
- package/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql +15 -0
- package/prisma/migrations/20260907021754_add_asset_upload_id/migration.sql +2 -0
- package/prisma/schema.prisma +10 -0
- package/bin/chunk-1ep7nnzp.js +0 -5
- package/bin/chunk-1jq2vgrd.js +0 -3
- package/bin/chunk-2ntm65jn.js +0 -3
- package/bin/chunk-3nh1p64q.js +0 -12
- package/bin/chunk-41gh01qj.js +0 -3
- package/bin/chunk-4n1309xp.js +0 -2
- package/bin/chunk-616f7y5x.js +0 -8
- package/bin/chunk-6a9h5d64.js +0 -3
- package/bin/chunk-6dp3ybh2.js +0 -3
- package/bin/chunk-6nd8f70y.js +0 -4
- package/bin/chunk-6vs3gb9g.js +0 -2
- package/bin/chunk-7dyx5m0f.js +0 -6
- package/bin/chunk-7j3qbvwc.js +0 -7
- package/bin/chunk-9h5qhgqx.js +0 -13
- package/bin/chunk-b9s67nd8.js +0 -2
- package/bin/chunk-c14kvr2r.js +0 -11
- package/bin/chunk-cb5p7shk.js +0 -12240
- package/bin/chunk-ccx6803n.js +0 -44
- package/bin/chunk-cm4dpd3k.js +0 -4
- package/bin/chunk-dd2tfwzy.js +0 -45
- package/bin/chunk-dk9vz5tv.js +0 -4
- package/bin/chunk-e6691p0v.js +0 -3
- package/bin/chunk-e9d2ah8y.js +0 -3
- package/bin/chunk-fvmb8en4.js +0 -24
- package/bin/chunk-gegf6d3m.js +0 -2
- package/bin/chunk-gx9vdcbm.js +0 -2
- package/bin/chunk-j427r7a5.js +0 -2
- package/bin/chunk-jperx2a8.js +0 -6
- package/bin/chunk-k4jm2gt4.js +0 -3
- package/bin/chunk-m29dphbf.js +0 -3
- package/bin/chunk-mpgy1y53.js +0 -3
- package/bin/chunk-n1t3he2k.js +0 -3
- package/bin/chunk-pmdb6y7t.js +0 -2
- package/bin/chunk-qx9njyk7.js +0 -3
- package/bin/chunk-r5h7vczc.js +0 -3
- package/bin/chunk-spm76160.js +0 -2
- package/bin/chunk-t8k09sgb.js +0 -3
- package/bin/chunk-tvef1ck8.js +0 -2
- package/bin/chunk-v4j6yxch.js +0 -3
- package/bin/chunk-vjzrmneg.js +0 -2
- package/bin/chunk-x25enwfz.js +0 -3
- package/bin/chunk-xg9xscqz.js +0 -1
- package/bin/chunk-xqg06q7q.js +0 -2
- package/bin/chunk-xvbd9e2b.js +0 -8
- package/bin/chunk-y2z3xj0m.js +0 -12
- package/bin/chunk-ywhrsshf.js +0 -2
- package/bin/chunk-z512b49m.js +0 -3
- package/bin/chunk-z58rb52r.js +0 -3
- package/bin/chunk-zazbsz25.js +0 -3
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{c,Ae}from"./shumai-agent-app.js";function S(e,y){if(typeof e==="string"&&typeof y==="string")return e.toLowerCase()===y.toLowerCase();return e===y}function W(e,y){if(typeof e!=="string")return y.includes(e);return y.some((O)=>typeof O==="string"&&e.toLowerCase()===O.toLowerCase())}function T(e,y){return!W(e,y)}function D(e,y){if(typeof e!=="string"||typeof y!=="string")return!1;return e.toLowerCase().includes(y.toLowerCase())}function k(e,y){if(typeof e!=="string"||typeof y!=="string")return!1;return e.toLowerCase().startsWith(y.toLowerCase())}function B(e,y){if(typeof e!=="string"||typeof y!=="string")return!1;return e.toLowerCase().endsWith(y.toLowerCase())}var N=(e,y)=>{let O=null,I=Ae({config:{adapterId:"memory",adapterName:"Memory Adapter",usePlural:!1,debugLogs:y?.debugLogs||!1,supportsArrays:!0,customTransformInput(d){if(d.options.advanced?.database?.generateId==="serial"&&d.field==="id"&&d.action==="create")return e[d.model].length+1;return d.data},transaction:async(d)=>{let M=structuredClone(e);try{return await d(I(O))}catch(b){throw Object.keys(e).forEach((A)=>{e[A]=M[A]}),b}}},adapter:({getFieldName:d,getDefaultFieldName:M,options:b,getModelName:A})=>{let R=(t,i,l)=>{if(!i)return t;return t.sort((o,f)=>{let g=d({model:l,field:i.field}),p=o[g],u=f[g],a=0;if(p==null&&u==null)a=0;else if(p==null)a=-1;else if(u==null)a=1;else if(typeof p==="string"&&typeof u==="string")a=p.localeCompare(u);else if(p instanceof Date&&u instanceof Date)a=p.getTime()-u.getTime();else if(typeof p==="number"&&typeof u==="number")a=p-u;else if(typeof p==="boolean"&&typeof u==="boolean")a=p===u?0:p?1:-1;else a=String(p).localeCompare(String(u));return i.direction==="asc"?a:-a})};function C(t,i,l,o){let f=(()=>{let u=e[i];if(!u)throw c.error(`[MemoryAdapter] Model ${i} not found in the DB`,Object.keys(e)),Error(`Model ${i} not found`);let a=(n,h)=>{let{field:s,value:r,operator:j,mode:v="sensitive"}=h,m=v==="insensitive"&&(typeof r==="string"||Array.isArray(r)&&r.every((L)=>typeof L==="string"));switch(j){case"in":if(!Array.isArray(r))throw Error("Value must be an array");if(m)return W(n[s],r);return r.includes(n[s]);case"not_in":if(!Array.isArray(r))throw Error("Value must be an array");if(m)return T(n[s],r);return!r.includes(n[s]);case"contains":if(m)return D(n[s],r);return n[s]?.includes(r);case"starts_with":if(m)return k(n[s],r);return n[s].startsWith(r);case"ends_with":if(m)return B(n[s],r);return n[s].endsWith(r);case"ne":return m?!S(n[s],r):n[s]!==r;case"gt":return r!=null&&Boolean(n[s]>r);case"gte":return r!=null&&Boolean(n[s]>=r);case"lt":return r!=null&&Boolean(n[s]<r);case"lte":return r!=null&&Boolean(n[s]<=r);default:if(m)return S(n[s],r);if(r===null)return n[s]==null;return n[s]===r}},w=u.filter((n)=>{if(!t.length||t.length===0)return!0;let h=a(n,t[0]);for(let s of t){let r=a(n,s);if(s.connector==="OR")h=h||r;else h=h&&r}return h});if(o?.length&&o.length>0)w=w.map((n)=>Object.fromEntries(Object.entries(n).filter(([h])=>o.includes(M({model:i,field:h})))));return w})();if(!l)return f;let g=new Map,p=new Map;for(let u of f){let a=String(u.id);if(!g.has(a)){let n={...u};for(let[h,s]of Object.entries(l)){let r=A(h);if(s.relation==="one-to-one")n[r]=null;else n[r]=[],p.set(`${a}-${h}`,new Set)}g.set(a,n)}let w=g.get(a);for(let[n,h]of Object.entries(l)){let s=A(n),r=e[s];if(!r)throw c.error(`[MemoryAdapter] JoinOption model ${s} not found in the DB`,Object.keys(e)),Error(`JoinOption model ${s} not found`);let j=r.filter((v)=>v[h.on.to]===u[h.on.from]);if(h.relation==="one-to-one")w[s]=j[0]||null;else{let v=p.get(`${a}-${n}`),m=h.limit??100,L=0;for(let E of j){if(L>=m)break;if(!v.has(E.id))w[s].push(E),v.add(E.id),L++}}}}return Array.from(g.values())}return{create:async({model:t,data:i})=>{if(b.advanced?.database?.generateId==="serial")i.id=e[A(t)].length+1;if(!e[t])e[t]=[];return e[t].push(i),i},findOne:async({model:t,where:i,select:l,join:o})=>{let f=C(i,t,o,l);if(o){let g=f;if(!g.length)return null;return g[0]}return f[0]||null},findMany:async({model:t,where:i,sortBy:l,limit:o,select:f,offset:g,join:p})=>{let u=C(i||[],t,p,f);if(p){let w=u;if(!w.length)return[];R(w,l,t);let n=w;if(g!==void 0)n=n.slice(g);if(o!==void 0)n=n.slice(0,o);return n}let a=R(u,l,t);if(g!==void 0)a=a.slice(g);if(o!==void 0)a=a.slice(0,o);return a||[]},count:async({model:t,where:i})=>{if(i)return C(i,t).length;return e[t].length},update:async({model:t,where:i,update:l})=>{let o=C(i,t);return o.forEach((f)=>{Object.assign(f,l)}),o[0]||null},delete:async({model:t,where:i})=>{let l=e[t],o=C(i,t);e[t]=l.filter((f)=>!o.includes(f))},deleteMany:async({model:t,where:i})=>{let l=e[t],o=C(i,t),f=0;return e[t]=l.filter((g)=>{if(o.includes(g))return f++,!1;return!o.includes(g)}),f},consumeOne:async({model:t,where:i})=>{let l=e[t],o=C(i,t)[0];if(!o)return null;return e[t]=l.filter((f)=>f!==o),o},updateMany({model:t,where:i,update:l}){let o=C(i,t);return o.forEach((f)=>{Object.assign(f,l)}),o[0]||null}}}});return(d)=>(O=d,I(d))};export{N as memoryAdapter};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{R}from"./chunk-s1e2nv5w.js";import{ne}from"./chunk-wg6xrc3y.js";import{d,We,He,M,Ue,O}from"./chunk-xp2anj2s.js";import{v}from"./shumai-agent-app.js";function J(i,o){let a={v:1,id:i};if(o)a.phase=o;return JSON.stringify(a)}function w(i){if(!i)return;if(i.startsWith("{"))try{let o=JSON.parse(i);if(o.v===1&&typeof o.id==="string"){if(o.phase==="commentary"||o.phase==="final_answer")return{id:o.id,phase:o.phase};return{id:o.id}}}catch{}return{id:i}}function P(i,o){let a=o.filter((l)=>l.type==="text").map((l)=>l.text).join(`
|
|
3
|
+
`),f=o.filter((l)=>l.type==="image"),p=a.length>0;if(f.length===0||!i.input.includes("image"))return d(p?a:f.length>0?"(see attached image)":"(no tool output)");let g=[];if(p)g.push({type:"input_text",text:d(a)});for(let l of f)g.push({type:"input_image",detail:"auto",image_url:`data:${l.mimeType};base64,${l.data}`});return g}function ce(i,o,a,f){let p=[],g=new Set,l=(r)=>{let c=r.replace(/[^a-zA-Z0-9_-]/g,"_");return(c.length>64?c.slice(0,64):c).replace(/_+$/,"")},x=(r)=>{let c=`fc_${ne(r)}`;return c.length>64?c.slice(0,64):c},_=(r,c,t)=>{if(!a.has(i.provider))return l(r);if(!r.includes("|"))return l(r);let[e,n]=r.split("|"),s=l(e),m=t.provider!==i.provider||t.api!==i.api?x(n):l(n);if(!m.startsWith("fc_"))m=l(`fc_${m}`);return`${s}|${m}`},y=O(o.messages,i,_);if((f?.includeSystemPrompt??!0)&&o.systemPrompt){let r=i.compat,c=i.reasoning&&r?.supportsDeveloperRole!==!1?"developer":"system";p.push({role:c,content:d(o.systemPrompt)})}let k=0;for(let r of y){if(r.role==="user")if(typeof r.content==="string")p.push({role:"user",content:[{type:"input_text",text:d(r.content)}]});else{let c=r.content.map((t)=>{if(t.type==="text")return{type:"input_text",text:d(t.text)};return{type:"input_image",detail:"auto",image_url:`data:${t.mimeType};base64,${t.data}`}});if(c.length===0)continue;p.push({role:"user",content:c})}else if(r.role==="assistant"){let c=[],t=r,e=t.model!==i.id&&t.provider===i.provider&&t.api===i.api,n=0;for(let s of r.content)if(s.type==="thinking"){if(s.thinkingSignature){let u=JSON.parse(s.thinkingSignature);c.push(u)}}else if(s.type==="text"){let u=s,m=w(u.textSignature),S=n===0?`msg_pi_${k}`:`msg_pi_${k}_${n}`;n++;let h=m?.id;if(!h)h=S;else if(h.length>64)h=`msg_${ne(h)}`;c.push({type:"message",role:"assistant",content:[{type:"output_text",text:d(u.text),annotations:[]}],status:"completed",id:h,phase:m?.phase})}else if(s.type==="toolCall"){let u=s,[m,S]=u.id.split("|"),h=f?.grammarToolInputProperties?.get(u.name),I=S;if(e&&I?.startsWith("fc_")||h===void 0&&!I?.startsWith("fc_"))I=void 0;if(h!==void 0)c.push({type:"custom_tool_call",id:I,call_id:m,name:u.name,input:d(We(u.name,u.arguments,h))});else c.push({type:"function_call",id:I,call_id:m,name:u.name,arguments:JSON.stringify(u.arguments)})}if(c.length===0)continue;p.push(...c)}else if(r.role==="toolResult"){let[c]=r.toolCallId.split("|"),t=P(i,r.content);if(f?.grammarToolInputProperties?.has(r.toolName))p.push({type:"custom_tool_call_output",call_id:c,output:t});else p.push({type:"function_call_output",call_id:c,output:t});let e=[];for(let n of r.addedToolNames??[]){let s=f?.deferredTools?.get(n);if(!s||g.has(n))continue;g.add(n),e.push(s)}if(e.length>0){let n=e.map((u)=>u.name),s=`pi_tool_load_${ne(`${r.toolCallId}:${n.join(",")}`)}`;p.push({type:"tool_search_call",call_id:s,execution:"client",status:"completed",arguments:{query:n.join(" "),limit:n.length}}),p.push({type:"tool_search_output",call_id:s,execution:"client",status:"completed",tools:ue(e,{...f?.toolOptions,deferLoading:!0})})}}k++}return p}function ue(i,o){let a=o?.strict===void 0?!1:o.strict,f=o?.supportsStrictMode??!0,p=o?.supportsOpenAIGrammarTools??!1;return i.map((g)=>{let l=Ue(g,p);if(l)return{type:"custom",name:g.name,description:g.description,format:{type:"grammar",syntax:l.format,definition:l.definition},...o?.deferLoading?{defer_loading:!0}:{}};let x=M(g,f),_={type:"function",name:g.name,description:g.description,parameters:g.parameters,...o?.deferLoading?{defer_loading:!0}:{}};if(f)_.strict=x??a;return _})}function C(i){let o=i.customInput?.property;if(o===void 0)return"";let a=i.arguments[o];return typeof a==="string"?a:""}function T(i,o,a){let f=i.customInput;if(!f)return;let p=He(f.jsonBuffer,f.property,o,a);return i.arguments={[f.property]:o},p}async function de(i,o,a,f,p){let g=!1,l=new Map,x=new Map,_=(t,e)=>{let n=l.get(t);return n?.type===e?n:void 0},y=(t,e)=>{if(e===void 0)return;a.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},b=(t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let s={type:"thinking",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){let n={type:"text",text:""};o.content.push(n);let s={type:"text",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||""};o.content.push(n);let s={type:"toolCall",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){let n=p?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",u={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(u);let m={type:"toolCall",block:u,contentIndex:o.content.length-1};return l.set(t,m),a.push({type:"toolcall_start",contentIndex:m.contentIndex,partial:o}),m}return},k=(t,e)=>l.get(t)??b(t,e),r=(t)=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=x.get(e.id);if(!n?.thinkingSignature)continue;let s=JSON.parse(n.thinkingSignature);if(s.encrypted_content)continue;n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content})}},c=(t)=>{if(g=!0,r(t.output??[]),t?.id)o.responseId=t.id;if(t?.usage){let e=t.usage.input_tokens_details,n=e?.cached_tokens||0,s=e?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-n-s),output:t.usage.output_tokens||0,cacheRead:n,cacheWrite:s,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(v(f,o.usage),p?.applyServiceTierPricing){let e=p.resolveServiceTier?p.resolveServiceTier(t?.service_tier,p.serviceTier):t?.service_tier??p.serviceTier;p.applyServiceTierPricing(o.usage,e)}if(o.stopReason=z(t?.status),o.content.some((e)=>e.type==="toolCall")&&o.stopReason==="stop")o.stopReason="toolUse"};for await(let t of i)if(t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")b(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
|
|
4
|
+
|
|
5
|
+
`,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
|
|
6
|
+
|
|
7
|
+
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=_(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=_(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=_(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=R(e.block.partialJson),y(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=_(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=R(e.block.partialJson),t.arguments.startsWith(n)){let s=t.arguments.slice(n.length);if(s.length>0)y(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=_(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;y(e,T(e.block,C(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=_(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;y(e,T(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item,n=k(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let s=e.summary?.map((m)=>m.text).join(`
|
|
8
|
+
|
|
9
|
+
`)||"",u=e.content?.map((m)=>m.text).join(`
|
|
10
|
+
|
|
11
|
+
`)||"";n.block.thinking=s||u||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),x.set(e.id,n.block),a.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),l.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=J(e.id,e.phase??void 0),a.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),l.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0)n.block.arguments=R(e.arguments||n.block.partialJson||"{}"),delete n.block.partialJson,a.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index);else if(e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput)y(n,T(n.block,e.input??C(n.block),!0)),delete n.block.customInput,a.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index)}else if(t.type==="response.completed"||t.type==="response.incomplete")c(t.response);else if(t.type==="error")throw Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");else if(t.type==="response.failed"){g=!0;let e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw Error(s)}if(!g)throw Error("OpenAI Responses stream ended before a terminal response event")}function z(i){if(!i)return"stop";switch(i){case"completed":return"stop";case"incomplete":return"length";case"failed":case"cancelled":return"error";case"in_progress":case"queued":return"stop";default:throw Error(`Unhandled stop reason: ${i}`)}}
|
|
12
|
+
export{ce,ue,de};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{n,a}from"./chunk-y2adfzyt.js";var ne=n(function(Nt,re){var T=1000,M=T*60,j=M*60,I=j*24,Ie=I*7,Re=I*365.25;re.exports=function(e,r){r=r||{};var t=typeof e;if(t==="string"&&e.length>0)return Ae(e);else if(t==="number"&&isFinite(e))return r.long?Me(e):Te(e);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Ae(e){if(e=String(e),e.length>100)return;var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!r)return;var t=parseFloat(r[1]),o=(r[2]||"ms").toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return t*Re;case"weeks":case"week":case"w":return t*Ie;case"days":case"day":case"d":return t*I;case"hours":case"hour":case"hrs":case"hr":case"h":return t*j;case"minutes":case"minute":case"mins":case"min":case"m":return t*M;case"seconds":case"second":case"secs":case"sec":case"s":return t*T;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}function Te(e){var r=Math.abs(e);if(r>=I)return Math.round(e/I)+"d";if(r>=j)return Math.round(e/j)+"h";if(r>=M)return Math.round(e/M)+"m";if(r>=T)return Math.round(e/T)+"s";return e+"ms"}function Me(e){var r=Math.abs(e);if(r>=I)return k(e,r,I,"day");if(r>=j)return k(e,r,j,"hour");if(r>=M)return k(e,r,M,"minute");if(r>=T)return k(e,r,T,"second");return e+" ms"}function k(e,r,t,o){var s=r>=t*1.5;return Math.round(e/t)+" "+o+(s?"s":"")}});var J=n(function(Lt,oe){function je(e){t.debug=t,t.default=t,t.coerce=x,t.disable=f,t.enable=s,t.enabled=F,t.humanize=ne(),t.destroy=L,Object.keys(e).forEach((i)=>{t[i]=e[i]}),t.names=[],t.skips=[],t.formatters={};function r(i){let c=0;for(let l=0;l<i.length;l++)c=(c<<5)-c+i.charCodeAt(l),c|=0;return t.colors[Math.abs(c)%t.colors.length]}t.selectColor=r;function t(i){let c,l=null,p,_;function h(...C){if(!h.enabled)return;let w=h,O=Number(new Date),S=O-(c||O);if(w.diff=S,w.prev=c,w.curr=O,c=O,C[0]=t.coerce(C[0]),typeof C[0]!=="string")C.unshift("%O");let E=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(P,A)=>{if(P==="%%")return"%";E++;let te=t.formatters[A];if(typeof te==="function"){let Pe=C[E];P=te.call(w,Pe),C.splice(E,1),E--}return P}),t.formatArgs.call(w,C),(w.log||t.log).apply(w,C)}if(h.namespace=i,h.useColors=t.useColors(),h.color=t.selectColor(i),h.extend=o,h.destroy=t.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(l!==null)return l;if(p!==t.namespaces)p=t.namespaces,_=t.enabled(i);return _},set:(C)=>{l=C}}),typeof t.init==="function")t.init(h);return h}function o(i,c){let l=t(this.namespace+(typeof c>"u"?":":c)+i);return l.log=this.log,l}function s(i){t.save(i),t.namespaces=i,t.names=[],t.skips=[];let c=(typeof i==="string"?i:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let l of c)if(l[0]==="-")t.skips.push(l.slice(1));else t.names.push(l)}function u(i,c){let l=0,p=0,_=-1,h=0;while(l<i.length)if(p<c.length&&(c[p]===i[l]||c[p]==="*"))if(c[p]==="*")_=p,h=l,p++;else l++,p++;else if(_!==-1)p=_+1,h++,l=h;else return!1;while(p<c.length&&c[p]==="*")p++;return p===c.length}function f(){let i=[...t.names,...t.skips.map((c)=>"-"+c)].join(",");return t.enable(""),i}function F(i){for(let c of t.skips)if(u(i,c))return!1;for(let c of t.names)if(u(i,c))return!0;return!1}function x(i){if(i instanceof Error)return i.stack||i.message;return i}function L(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}oe.exports=je});var se=n(function(W,U){W.formatArgs=Le;W.save=Be;W.load=qe;W.useColors=Ne;W.storage=De();W.destroy=(()=>{let e=!1;return()=>{if(!e)e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();W.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ne(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Le(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+U.exports.humanize(this.diff),!this.useColors)return;let r="color: "+this.color;e.splice(1,0,r,"color: inherit");let t=0,o=0;e[0].replace(/%[a-zA-Z%]/g,(s)=>{if(s==="%%")return;if(t++,s==="%c")o=t}),e.splice(o,0,r)}W.log=console.debug||console.log||(()=>{});function Be(e){try{if(e)W.storage.setItem("debug",e);else W.storage.removeItem("debug")}catch(r){}}function qe(){let e;try{e=W.storage.getItem("debug")||W.storage.getItem("DEBUG")}catch(r){}if(!e&&typeof process<"u"&&"env"in process)e=process.env.DEBUG;return e}function De(){try{return localStorage}catch(e){}}U.exports=J()(W);var{formatters:ke}=U.exports;ke.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}});var ce=n(function(qt,ie){ie.exports=(e,r=process.argv)=>{let t=e.startsWith("-")?"":e.length===1?"-":"--",o=r.indexOf(t+e),s=r.indexOf("--");return o!==-1&&(s===-1||o<s)}});var fe=n(function(Dt,ae){var Je=a("os"),ue=a("tty"),b=ce(),{env:d}=process,H;if(b("no-color")||b("no-colors")||b("color=false")||b("color=never"))H=0;else if(b("color")||b("colors")||b("color=true")||b("color=always"))H=1;function We(){if("FORCE_COLOR"in d){if(d.FORCE_COLOR==="true")return 1;if(d.FORCE_COLOR==="false")return 0;return d.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(d.FORCE_COLOR,10),3)}}function Ke(e){if(e===0)return!1;return{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Ze(e,{streamIsTTY:r,sniffFlags:t=!0}={}){let o=We();if(o!==void 0)H=o;let s=t?H:o;if(s===0)return 0;if(t){if(b("color=16m")||b("color=full")||b("color=truecolor"))return 3;if(b("color=256"))return 2}if(e&&!r&&s===void 0)return 0;let u=s||0;if(d.TERM==="dumb")return u;if(process.platform==="win32"){let f=Je.release().split(".");if(Number(f[0])>=10&&Number(f[2])>=10586)return Number(f[2])>=14931?3:2;return 1}if("CI"in d){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some((f)=>(f in d))||d.CI_NAME==="codeship")return 1;return u}if("TEAMCITY_VERSION"in d)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(d.TEAMCITY_VERSION)?1:0;if(d.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in d){let f=Number.parseInt((d.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(d.TERM_PROGRAM){case"iTerm.app":return f>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(d.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(d.TERM))return 1;if("COLORTERM"in d)return 1;return u}function K(e,r={}){let t=Ze(e,{streamIsTTY:e&&e.isTTY,...r});return Ke(t)}ae.exports={supportsColor:K,stdout:K({isTTY:ue.isatty(1)}),stderr:K({isTTY:ue.isatty(2)})}});var de=n(function(Z,z){var Qe=a("tty"),G=a("util");Z.init=st;Z.log=rt;Z.formatArgs=et;Z.save=nt;Z.load=ot;Z.useColors=Xe;Z.destroy=G.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Z.colors=[6,2,3,4,5,1];try{let e=fe();if(e&&(e.stderr||e).level>=2)Z.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(e){}Z.inspectOpts=Object.keys(process.env).filter((e)=>/^debug_/i.test(e)).reduce((e,r)=>{let t=r.substring(6).toLowerCase().replace(/_([a-z])/g,(s,u)=>u.toUpperCase()),o=process.env[r];if(/^(yes|on|true|enabled)$/i.test(o))o=!0;else if(/^(no|off|false|disabled)$/i.test(o))o=!1;else if(o==="null")o=null;else o=Number(o);return e[t]=o,e},{});function Xe(){return"colors"in Z.inspectOpts?Boolean(Z.inspectOpts.colors):Qe.isatty(process.stderr.fd)}function et(e){let{namespace:r,useColors:t}=this;if(t){let o=this.color,s="\x1B[3"+(o<8?o:"8;5;"+o),u=` ${s};1m${r} \x1B[0m`;e[0]=u+e[0].split(`
|
|
3
|
+
`).join(`
|
|
4
|
+
`+u),e.push(s+"m+"+z.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=tt()+r+" "+e[0]}function tt(){if(Z.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function rt(...e){return process.stderr.write(G.formatWithOptions(Z.inspectOpts,...e)+`
|
|
5
|
+
`)}function nt(e){if(e)process.env.DEBUG=e;else delete process.env.DEBUG}function ot(){return process.env.DEBUG}function st(e){e.inspectOpts={};let r=Object.keys(Z.inspectOpts);for(let t=0;t<r.length;t++)e.inspectOpts[r[t]]=Z.inspectOpts[r[t]]}z.exports=J()(Z);var{formatters:le}=z.exports;le.o=function(e){return this.inspectOpts.colors=this.useColors,G.inspect(e,this.inspectOpts).split(`
|
|
6
|
+
`).map((r)=>r.trim()).join(" ")};le.O=function(e){return this.inspectOpts.colors=this.useColors,G.inspect(e,this.inspectOpts)}});var X=n(function($t,Q){if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Q.exports=se();else Q.exports=de()});var ye=n(function(y){var dt=y&&y.__createBinding||(Object.create?function(e,r,t,o){if(o===void 0)o=t;var s=Object.getOwnPropertyDescriptor(r,t);if(!s||("get"in s?!r.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return r[t]}};Object.defineProperty(e,o,s)}:function(e,r,t,o){if(o===void 0)o=t;e[o]=r[t]}),ht=y&&y.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),he=y&&y.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null){for(var t in e)if(t!=="default"&&Object.prototype.hasOwnProperty.call(e,t))dt(r,e,t)}return ht(r,e),r};Object.defineProperty(y,"__esModule",{value:!0});y.req=y.json=y.toBuffer=void 0;var Ct=he(a("http")),yt=he(a("https"));async function Ce(e){let r=0,t=[];for await(let o of e)r+=o.length,t.push(o);return Buffer.concat(t,r)}y.toBuffer=Ce;async function gt(e){let t=(await Ce(e)).toString("utf8");try{return JSON.parse(t)}catch(o){let s=o;throw s.message+=` (input: ${t})`,s}}y.json=gt;function bt(e,r={}){let o=((typeof e==="string"?e:e.href).startsWith("https:")?yt:Ct).request(e,r),s=new Promise((u,f)=>{o.once("response",u).once("error",f).end()});return o.then=s.then.bind(s),o}y.req=bt});var Oe=n(function(g){var be=g&&g.__createBinding||(Object.create?function(e,r,t,o){if(o===void 0)o=t;var s=Object.getOwnPropertyDescriptor(r,t);if(!s||("get"in s?!r.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return r[t]}};Object.defineProperty(e,o,s)}:function(e,r,t,o){if(o===void 0)o=t;e[o]=r[t]}),mt=g&&g.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),me=g&&g.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null){for(var t in e)if(t!=="default"&&Object.prototype.hasOwnProperty.call(e,t))be(r,e,t)}return mt(r,e),r},_t=g&&g.__exportStar||function(e,r){for(var t in e)if(t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t))be(r,e,t)};Object.defineProperty(g,"__esModule",{value:!0});g.Agent=void 0;var Ot=me(a("net")),ge=me(a("http")),vt=a("https");_t(ye(),g);var v=Symbol("AgentBaseInternalState");class _e extends ge.Agent{constructor(e){super(e);this[v]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==="boolean")return e.secureEndpoint;if(typeof e.protocol==="string")return e.protocol==="https:"}let{stack:r}=Error();if(typeof r!=="string")return!1;return r.split(`
|
|
7
|
+
`).some((t)=>t.indexOf("(https.js:")!==-1||t.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[e])this.sockets[e]=[];let r=new Ot.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let t=this.sockets[e],o=t.indexOf(r);if(o!==-1){if(t.splice(o,1),this.totalSocketCount--,t.length===0)delete this.sockets[e]}}getName(e){if(this.isSecureEndpoint(e))return vt.Agent.prototype.getName.call(this,e);return super.getName(e)}createSocket(e,r,t){let o={...r,secureEndpoint:this.isSecureEndpoint(r)},s=this.getName(o),u=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then((f)=>{if(this.decrementSockets(s,u),f instanceof ge.Agent)try{return f.addRequest(e,o)}catch(F){return t(F)}this[v].currentSocket=f,super.createSocket(e,r,t)},(f)=>{this.decrementSockets(s,u),t(f)})}createConnection(){let e=this[v].currentSocket;if(this[v].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[v].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){if(this[v])this[v].defaultPort=e}get protocol(){return this[v].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){if(this[v])this[v].protocol=e}}g.Agent=_e});var ve=n(function(N){var wt=N&&N.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(N,"__esModule",{value:!0});N.parseProxyResponse=void 0;var Ft=wt(X()),Y=(0,Ft.default)("https-proxy-agent:parse-proxy-response");function xt(e){return new Promise((r,t)=>{let o=0,s=[];function u(){let i=e.read();if(i)L(i);else e.once("readable",u)}function f(){e.removeListener("end",F),e.removeListener("error",x),e.removeListener("readable",u)}function F(){f(),Y("onend"),t(Error("Proxy connection ended before receiving CONNECT response"))}function x(i){f(),Y("onerror %o",i),t(i)}function L(i){s.push(i),o+=i.length;let c=Buffer.concat(s,o),l=c.indexOf(`\r
|
|
8
|
+
\r
|
|
9
|
+
`);if(l===-1){Y("have not received end of HTTP headers yet..."),u();return}let p=c.slice(0,l).toString("ascii").split(`\r
|
|
10
|
+
`),_=p.shift();if(!_)return e.destroy(),t(Error("No header received from proxy CONNECT response"));let h=_.split(" "),C=+h[1],w=h.slice(2).join(" "),O={};for(let S of p){if(!S)continue;let E=S.indexOf(":");if(E===-1)return e.destroy(),t(Error(`Invalid header from proxy CONNECT response: "${S}"`));let D=S.slice(0,E).toLowerCase(),P=S.slice(E+1).trimStart(),A=O[D];if(typeof A==="string")O[D]=[A,P];else if(Array.isArray(A))A.push(P);else O[D]=P}Y("got proxy server response: %o %o",_,O),f(),r({connect:{statusCode:C,statusText:w,headers:O},buffered:c})}e.on("error",x),e.on("end",F),u()})}N.parseProxyResponse=xt});var jt=n(function(m){var Et=m&&m.__createBinding||(Object.create?function(e,r,t,o){if(o===void 0)o=t;var s=Object.getOwnPropertyDescriptor(r,t);if(!s||("get"in s?!r.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return r[t]}};Object.defineProperty(e,o,s)}:function(e,r,t,o){if(o===void 0)o=t;e[o]=r[t]}),St=m&&m.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),Ee=m&&m.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null){for(var t in e)if(t!=="default"&&Object.prototype.hasOwnProperty.call(e,t))Et(r,e,t)}return St(r,e),r},Se=m&&m.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(m,"__esModule",{value:!0});m.HttpsProxyAgent=void 0;var V=Ee(a("net")),we=Ee(a("tls")),Pt=Se(a("assert")),It=Se(X()),Rt=Oe(),At=a("url"),Tt=ve(),q=(0,It.default)("https-proxy-agent"),Fe=(e)=>{if(e.servername===void 0&&e.host&&!V.isIP(e.host))return{...e,servername:e.host};return e};class ee extends Rt.Agent{constructor(e,r){super(r);this.options={path:void 0},this.proxy=typeof e==="string"?new At.URL(e):e,this.proxyHeaders=r?.headers??{},q("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let t=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...r?xe(r,"headers"):null,host:t,port:o}}async connect(e,r){let{proxy:t}=this;if(!r.host)throw TypeError('No "host" provided');let o;if(t.protocol==="https:")q("Creating `tls.Socket`: %o",this.connectOpts),o=we.connect(Fe(this.connectOpts));else q("Creating `net.Socket`: %o",this.connectOpts),o=V.connect(this.connectOpts);let s=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},u=V.isIPv6(r.host)?`[${r.host}]`:r.host,f=`CONNECT ${u}:${r.port} HTTP/1.1\r
|
|
11
|
+
`;if(t.username||t.password){let c=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(c).toString("base64")}`}if(s.Host=`${u}:${r.port}`,!s["Proxy-Connection"])s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let c of Object.keys(s))f+=`${c}: ${s[c]}\r
|
|
12
|
+
`;let F=Tt.parseProxyResponse(o);o.write(`${f}\r
|
|
13
|
+
`);let{connect:x,buffered:L}=await F;if(e.emit("proxyConnect",x),this.emit("proxyConnect",x,e),x.statusCode===200){if(e.once("socket",Mt),r.secureEndpoint)return q("Upgrading socket connection to TLS"),we.connect({...xe(Fe(r),"host","path","port"),socket:o});return o}o.destroy();let i=new V.Socket({writable:!1});return i.readable=!0,e.once("socket",(c)=>{q("Replaying proxy buffer for failed request"),(0,Pt.default)(c.listenerCount("data")>0),c.push(L),c.push(null)}),i}}ee.protocols=["http","https"];m.HttpsProxyAgent=ee;function Mt(e){e.resume()}function xe(e,...r){let t={},o;for(o in e)if(!r.includes(o))t[o]=e[o];return t}});export default jt();
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function b(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jr=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function pt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var mt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class T extends m{constructor(e,t,r,s){super(`${T.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Ae({message:r,cause:mt(t)});let n=t?.error;if(e===400)return new _t(e,n,r,s);if(e===401)return new gt(e,n,r,s);if(e===403)return new yt(e,n,r,s);if(e===404)return new bt(e,n,r,s);if(e===409)return new wt(e,n,r,s);if(e===422)return new xt(e,n,r,s);if(e===429)return new At(e,n,r,s);if(e>=500)return new It(e,n,r,s);return new T(e,n,r,s)}}class N extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ae extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ie extends Ae{constructor({message:e}={}){super({message:e??"Request timed out."})}}class _t extends T{}class gt extends T{}class yt extends T{}class bt extends T{}class wt extends T{}class xt extends T{}class At extends T{}class It extends T{}class Pt extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class St extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ne extends Error{constructor(e){super(e)}}var Dn=/^[a-z][a-z0-9+.-]*:/i,Es=(e)=>Dn.test(e),j=(e)=>(j=Array.isArray,j(e)),Xr=j;function Vr(e){if(typeof e!=="object")return{};return e??{}}function vs(e){if(!e)return!0;for(let t in e)return!1;return!0}function $s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ue(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var ks=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var Os=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Q=(e)=>new Promise((t)=>setTimeout(t,e));var he="6.26.0";var Ms=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Wn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var qn=()=>{let e=Wn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(Deno.build.os),"X-Stainless-Arch":Ts(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ts(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Hn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hn(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Ts=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Fs=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Ns,Ls=()=>Ns??(Ns=qn());function Bs(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Kr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function mr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Kr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Gr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Us(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var js=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var zr="RFC3986",Qr=(e)=>String(e),Yr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:Qr},Ds="RFC1738";var _r=(e,t)=>(_r=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),_r(e,t)),Y=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Zr=1024,Ws=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Zr){let d=o.length>=Zr?o.slice(f,f+Zr):o,_=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===Ds&&(p===40||p===41)){_[_.length]=d.charAt(y);continue}if(p<128){_[_.length]=Y[p];continue}if(p<2048){_[_.length]=Y[192|p>>6]+Y[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Y[224|p>>12]+Y[128|p>>6&63]+Y[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),_[_.length]=Y[240|p>>18]+Y[128|p>>12&63]+Y[128|p>>6&63]+Y[128|p&63]}a+=_.join("")}return a};function qs(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function es(e,t){if(j(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Js={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Xs=function(e,t){Array.prototype.push.apply(e,j(t)?t:[t])},Hs,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ws,encodeValuesOnly:!1,format:zr,formatter:Qr,indices:!1,serializeDate(e){return(Hs??(Hs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Vn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var ts={};function Vs(e,t,r,s,n,o,a,f,d,_,y,p,u,w,g,C,R,P){let I=e,O=P,v=0,q=!1;while((O=O.get(ts))!==void 0&&!q){let S=O.get(e);if(v+=1,typeof S<"u")if(S===v)throw RangeError("Cyclic object value");else q=!0;if(typeof O.get(ts)>"u")v=0}if(typeof _==="function")I=_(t,I);else if(I instanceof Date)I=u?.(I);else if(r==="comma"&&j(I))I=es(I,function(S){if(S instanceof Date)return u?.(S);return S});if(I===null){if(o)return d&&!C?d(t,M.encoder,R,"key",w):t;I=""}if(Vn(I)||qs(I)){if(d){let S=C?t:d(t,M.encoder,R,"key",w);return[g?.(S)+"="+g?.(d(I,M.encoder,R,"value",w))]}return[g?.(t)+"="+g?.(String(I))]}let F=[];if(typeof I>"u")return F;let E;if(r==="comma"&&j(I)){if(C&&d)I=es(I,d);E=[{value:I.length>0?I.join(",")||null:void 0}]}else if(j(_))E=_;else{let S=Object.keys(I);E=y?S.sort(y):S}let D=f?String(t).replace(/\./g,"%2E"):String(t),se=s&&j(I)&&I.length===1?D+"[]":D;if(n&&j(I)&&I.length===0)return se+"[]";for(let S=0;S<E.length;++S){let fe=E[S],Rs=typeof fe==="object"&&typeof fe.value<"u"?fe.value:I[fe];if(a&&Rs===null)continue;let Hr=p&&f?fe.replace(/\./g,"%2E"):fe,Un=j(I)?typeof r==="function"?r(se,Hr):se:se+(p?"."+Hr:"["+Hr+"]");P.set(e,v);let Cs=new WeakMap;Cs.set(ts,P),Xs(F,Vs(Rs,Un,r,s,n,o,a,f,r==="comma"&&C&&j(I)?null:d,_,y,p,u,w,g,C,R,Cs))}return F}function Kn(e=M){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||M.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=zr;if(typeof e.format<"u"){if(!_r(Yr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Yr[r],n=M.filter;if(typeof e.filter==="function"||j(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Js)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=M.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:M.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?M.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:M.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:M.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:M.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:M.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:M.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:M.strictNullHandling}}function Ks(e,t={}){let r=e,s=Kn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(j(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Js[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let w=n[u];if(s.skipNulls&&r[w]===null)continue;Xs(a,Vs(r[w],w,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,_))}let y=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return y.length>0?p+y:""}function Gs(e){return Ks(e,{arrayFormat:"brackets"})}function Ys(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var zs;function je(e){let t;return(zs??(t=new globalThis.TextEncoder,zs=t.encode.bind(t)))(e)}var Qs;function rs(e){let t;return(Qs??(t=new globalThis.TextDecoder,Qs=t.decode.bind(t)))(e)}var H,J;class De{constructor(){H.set(this,void 0),J.set(this,void 0),b(this,H,new Uint8Array,"f"),b(this,J,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?je(e):e;b(this,H,Ys([i(this,H,"f"),t]),"f");let r=[],s;while((s=zn(i(this,H,"f"),i(this,J,"f")))!=null){if(s.carriage&&i(this,J,"f")==null){b(this,J,s.index,"f");continue}if(i(this,J,"f")!=null&&(s.index!==i(this,J,"f")+1||s.carriage)){r.push(rs(i(this,H,"f").subarray(0,i(this,J,"f")-1))),b(this,H,i(this,H,"f").subarray(i(this,J,"f")),"f"),b(this,J,null,"f");continue}let n=i(this,J,"f")!==null?s.preceding-1:s.preceding,o=rs(i(this,H,"f").subarray(0,n));r.push(o),b(this,H,i(this,H,"f").subarray(s.index),"f"),b(this,J,null,"f")}return r}flush(){if(!i(this,H,"f").length)return[];return this.decode(`
|
|
3
|
+
`)}}H=new WeakMap,J=new WeakMap;De.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]);De.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Zs(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var yr={off:0,error:200,warn:300,info:400,debug:500},ss=(e,t,r)=>{if(!e)return;if($s(yr,e))return e;k(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(yr))}`);return};function Rt(){}function gr(e,t,r){if(!t||yr[e]>yr[r])return Rt;else return t[e].bind(t)}var Qn={error:Rt,warn:Rt,info:Rt,debug:Rt},en=new WeakMap;function k(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Qn;let s=en.get(t);if(s&&s[0]===r)return s[1];let n={error:gr("error",t,r),warn:gr("warn",t,r),info:gr("info",t,r),debug:gr("debug",t,r)};return en.set(t,[r,n]),n}var oe=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var Ct;class X{constructor(e,t,r){this.iterator=e,Ct.set(this,void 0),this.controller=t,b(this,Ct,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?k(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Yn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new T(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new T(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(pt(d))return;throw d}finally{if(!f)t.abort()}}return new X(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new De,f=Gr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(pt(f))return;throw f}finally{if(!a)t.abort()}}return new X(o,t,r)}[(Ct=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new X(()=>s(e),this.controller,i(this,Ct,"f")),new X(()=>s(t),this.controller,i(this,Ct,"f"))]}toReadableStream(){let e=this,t;return Kr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=je(JSON.stringify(s)+`
|
|
5
|
+
`);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Yn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new tn,s=new De,n=Gr(e.body);for await(let o of Zn(n))for(let a of s.decode(o)){let f=r.decode(a);if(f)yield f}for(let o of s.flush()){let a=r.decode(o);if(a)yield a}}async function*Zn(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?je(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Zs(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class tn{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
|
|
6
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=eo(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function eo(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function br(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(k(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return X.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ns(u,r)}return await r.text()})();return k(e).debug(`[${s}] response parsed`,oe({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ns(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Et;class Pe extends Promise{constructor(e,t,r=br){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Et.set(this,void 0),b(this,Et,e,"f")}_thenUnwrap(e){return new Pe(i(this,Et,"f"),this.responsePromise,async(t,r)=>ns(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Et,"f"),e));return this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Et=new WeakMap;var wr;class xr{constructor(e,t,r,s){wr.set(this,void 0),b(this,wr,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,wr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(wr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class Ar extends Pe{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await br(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class ie extends xr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class x extends xr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Vr(this.options.query),after:t}}}}class Z extends xr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Vr(this.options.query),after:e}}}}var as=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function We(e,t,r){return as(),new File(e,t??"unknown_file",r)}function vt(e){return(typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var Ir=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ae=async(e,t)=>{if(!os(e.body))return e;return{...e,body:await sn(e.body,t)}},K=async(e,t)=>({...e,body:await sn(e.body,t)}),rn=new WeakMap;function ro(e){let t=typeof e==="function"?e:e.fetch,r=rn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return rn.set(t,s),s}var sn=async(e,t)=>{if(!await ro(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,n])=>is(r,s,n))),r},nn=(e)=>e instanceof Blob&&("name"in e),so=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ir(e)||nn(e)),os=(e)=>{if(so(e))return!0;if(Array.isArray(e))return e.some(os);if(e&&typeof e==="object"){for(let t in e)if(os(e[t]))return!0}return!1},is=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,We([await r.blob()],vt(r)));else if(Ir(r))e.append(t,We([await new Response(mr(r)).blob()],vt(r)));else if(nn(r))e.append(t,r,vt(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>is(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>is(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var on=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",no=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&on(e),oo=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Pr(e,t,r){if(as(),e=await e,no(e)){if(e instanceof File)return e;return We([await e.arrayBuffer()],e.name)}if(oo(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),We(await ls(n),t,r)}let s=await ls(e);if(t||(t=vt(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return We(s,t,r)}async function ls(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(on(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ir(e))for await(let r of e)t.push(...await ls(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${io(e)}`)}return t}function io(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function ln(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var an=Object.freeze(Object.create(null)),lo=(e=ln)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??an)??an)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),C="^".repeat(w.length);return y=w.start+w.length,u+g+C},"");throw new m(`Path parameters result in path with invalid segments:
|
|
7
|
+
${o.map((u)=>u.error).join(`
|
|
8
|
+
`)}
|
|
9
|
+
${a}
|
|
10
|
+
${p}`)}return a},l=lo(ln);class qe extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,x,{query:t,...r})}}function $t(e){return e!==void 0&&"function"in e&&e.function!==void 0}function kt(e){return e?.$brand==="auto-parseable-response-format"}function Se(e){return e?.$brand==="auto-parseable-tool"}function cn(e,t){if(!t||!cs(t))return{...e,choices:e.choices.map((r)=>(fn(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return Ot(e,t)}function Ot(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new Pt;if(s.finish_reason==="content_filter")throw new St;return fn(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>ho(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?fo(t,s.message.content):null}}});return{...e,choices:r}}function fo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function ho(e,t){let r=e.tools?.find((s)=>$t(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Se(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function un(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>$t(s)&&s.function?.name===t.function.name);return $t(r)&&(Se(r)||r?.function.strict||!1)}function cs(e){if(kt(e.response_format))return!0;return e.tools?.some((t)=>Se(t)||t.type==="function"&&t.function.strict===!0)??!1}function fn(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function hn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var He=(e)=>e?.role==="assistant",us=(e)=>e?.role==="tool";var fs,Sr,Rr,Tt,Ft,Cr,Nt,le,Mt,Er,vr,Je,dn;class Re{constructor(){fs.add(this),this.controller=new AbortController,Sr.set(this,void 0),Rr.set(this,()=>{}),Tt.set(this,()=>{}),Ft.set(this,void 0),Cr.set(this,()=>{}),Nt.set(this,()=>{}),le.set(this,{}),Mt.set(this,!1),Er.set(this,!1),vr.set(this,!1),Je.set(this,!1),b(this,Sr,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,Tt,t,"f")}),"f"),b(this,Ft,new Promise((e,t)=>{b(this,Cr,e,"f"),b(this,Nt,t,"f")}),"f"),i(this,Sr,"f").catch(()=>{}),i(this,Ft,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,fs,"m",dn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Rr,"f").call(this),this._emit("connect")}get ended(){return i(this,Mt,"f")}get errored(){return i(this,Er,"f")}get aborted(){return i(this,vr,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,le,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(b(this,Je,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){b(this,Je,!0,"f"),await i(this,Ft,"f")}_emit(e,...t){if(i(this,Mt,"f"))return;if(e==="end")b(this,Mt,!0,"f"),i(this,Cr,"f").call(this);let r=i(this,le,"f")[e];if(r)i(this,le,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Tt,"f").call(this,s),i(this,Nt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Tt,"f").call(this,s),i(this,Nt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Sr=new WeakMap,Rr=new WeakMap,Tt=new WeakMap,Ft=new WeakMap,Cr=new WeakMap,Nt=new WeakMap,le=new WeakMap,Mt=new WeakMap,Er=new WeakMap,vr=new WeakMap,Je=new WeakMap,fs=new WeakSet,dn=function(t){if(b(this,Er,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new N;if(t instanceof N)return b(this,vr,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function pn(e){return typeof e.parse==="function"}var W,hs,$r,ds,ps,ms,mn,_n,po=10;class Lt extends Re{constructor(){super(...arguments);W.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(He(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,W,"m",hs).call(this)}async finalMessage(){return await this.done(),i(this,W,"m",$r).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,W,"m",ds).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,W,"m",ps).call(this)}async totalUsage(){return await this.done(),i(this,W,"m",ms).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,W,"m",$r).call(this);if(t)this._emit("finalMessage",t);let r=i(this,W,"m",hs).call(this);if(r)this._emit("finalContent",r);let s=i(this,W,"m",ds).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,W,"m",ps).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,W,"m",ms).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,W,"m",mn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ot(n,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=po}=r||{},_=t.tools.map((u)=>{if(Se(u)){if(!u.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),y={};for(let u of _)if(u.type==="function")y[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let g=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let C of g.tool_calls){if(C.type!=="function")continue;let R=C.id,{name:P,arguments:I}=C.function,O=y[P];if(!O){let E=`Invalid tool_call: ${JSON.stringify(P)}. Available options are: ${Object.keys(y).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:E});continue}else if(f&&f!==P){let E=`Invalid tool_call: ${JSON.stringify(P)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:E});continue}let v;try{v=pn(O)?await O.parse(I):I}catch(E){let D=E instanceof Error?E.message:String(E);this._addMessage({role:"tool",tool_call_id:R,content:D});continue}let q=await O.function(v,this),F=i(this,W,"m",_n).call(this,q);if(this._addMessage({role:"tool",tool_call_id:R,content:F}),f)return}}return}}W=new WeakSet,hs=function(){return i(this,W,"m",$r).call(this).content??null},$r=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(He(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(He(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ps=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(us(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ms=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},mn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_n=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Bt extends Lt{static runTools(e,t,r){let s=new Bt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),He(e)&&e.content)this._emit("content",e.content)}}var B={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class gn extends Error{}class yn extends Error{}function mo(e,t=B.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return _o(e.trim(),t)}var _o=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new gn(`${u} at position ${s}`)},o=(u)=>{throw new yn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||B.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||B.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||B.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||B.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||B.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||B.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return y()},f=()=>{let u=s,w=!1;s++;while(s<r&&(e[s]!=='"'||w&&e[s-1]==="\\"))w=e[s]==="\\"?!w:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(w)))}catch(g){o(String(g))}else if(B.STR&t)try{return JSON.parse(e.substring(u,s-Number(w))+'"')}catch(g){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&B.OBJ&t)return u;let w=f();p(),s++;try{let g=a();Object.defineProperty(u,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(B.OBJ&t)return u;else throw g}if(p(),e[s]===",")s++}}catch(w){if(B.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(w){if(B.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},y=()=>{if(s===0){if(e==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(w){if(B.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(g){}o(String(w))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(B.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(w){if(e.substring(u,s)==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(g){o(String(g))}}},p=()=>{while(s<r&&`
|
|
11
|
+
\r `.includes(e[s]))s++};return a()},_s=(e)=>mo(e,B.ALL^B.NUM);var L,ce,Xe,de,gs,kr,ys,bs,ws,Or,xs,bn;class pe extends Lt{constructor(e){super();L.add(this),ce.set(this,void 0),Xe.set(this,void 0),de.set(this,void 0),b(this,ce,e,"f"),b(this,Xe,[],"f")}get currentChatCompletionSnapshot(){return i(this,de,"f")}static fromReadableStream(e){let t=new pe(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new pe(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,L,"m",gs).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)i(this,L,"m",ys).call(this,o);if(n.controller.signal?.aborted)throw new N;return this._addChatCompletion(i(this,L,"m",Or).call(this))}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}i(this,L,"m",gs).call(this),this._connected();let s=X.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,L,"m",Or).call(this));i(this,L,"m",ys).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new N;return this._addChatCompletion(i(this,L,"m",Or).call(this))}[(ce=new WeakMap,Xe=new WeakMap,de=new WeakMap,L=new WeakSet,gs=function(){if(this.ended)return;b(this,de,void 0,"f")},kr=function(t){let r=i(this,Xe,"f")[t.index];if(r)return r;return r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i(this,Xe,"f")[t.index]=r,r},ys=function(t){if(this.ended)return;let r=i(this,L,"m",bn).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let n=r.choices[s.index];if(s.delta.content!=null&&n.message?.role==="assistant"&&n.message?.content)this._emit("content",s.delta.content,n.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:n.message.content,parsed:n.message.parsed});if(s.delta.refusal!=null&&n.message?.role==="assistant"&&n.message?.refusal)this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:n.message.refusal});if(s.logprobs?.content!=null&&n.message?.role==="assistant")this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:n.logprobs?.content??[]});if(s.logprobs?.refusal!=null&&n.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:n.logprobs?.refusal??[]});let o=i(this,L,"m",kr).call(this,n);if(n.finish_reason){if(i(this,L,"m",ws).call(this,n),o.current_tool_call_index!=null)i(this,L,"m",bs).call(this,n,o.current_tool_call_index)}for(let a of s.delta.tool_calls??[]){if(o.current_tool_call_index!==a.index){if(i(this,L,"m",ws).call(this,n),o.current_tool_call_index!=null)i(this,L,"m",bs).call(this,n,o.current_tool_call_index)}o.current_tool_call_index=a.index}for(let a of s.delta.tool_calls??[]){let f=n.message.tool_calls?.[a.index];if(!f?.type)continue;if(f?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:f.function?.name,index:a.index,arguments:f.function.arguments,parsed_arguments:f.function.parsed_arguments,arguments_delta:a.function?.arguments??""});else xn(f?.type)}}},bs=function(t,r){if(i(this,L,"m",kr).call(this,t).done_tool_calls.has(r))return;let n=t.message.tool_calls?.[r];if(!n)throw Error("no tool call snapshot");if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type==="function"){let o=i(this,ce,"f")?.tools?.find((a)=>$t(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:r,arguments:n.function.arguments,parsed_arguments:Se(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else xn(n.type)},ws=function(t){let r=i(this,L,"m",kr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,L,"m",xs).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}if(t.message.refusal&&!r.refusal_done)r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal});if(t.logprobs?.content&&!r.logprobs_content_done)r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!r.logprobs_refusal_done)r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},Or=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,de,"f");if(!t)throw new m("request ended without sending any chunks");return b(this,de,void 0,"f"),b(this,Xe,[],"f"),go(t,i(this,ce,"f"))},xs=function(){let t=i(this,ce,"f")?.response_format;if(kt(t))return t;return null},bn=function(t){var r,s,n,o;let a=i(this,de,"f"),{choices:f,...d}=t;if(!a)a=b(this,de,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:_,finish_reason:y,index:p,logprobs:u=null,...w}of t.choices){let g=a.choices[p];if(!g)g=a.choices[p]={finish_reason:y,index:p,message:{},logprobs:u,...w};if(u)if(!g.logprobs)g.logprobs=Object.assign({},u);else{let{content:q,refusal:F,...E}=u;if(wn(E),Object.assign(g.logprobs,E),q)(r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...q);if(F)(s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...F)}if(y){if(g.finish_reason=y,i(this,ce,"f")&&cs(i(this,ce,"f"))){if(y==="length")throw new Pt;if(y==="content_filter")throw new St}}if(Object.assign(g,w),!_)continue;let{content:C,refusal:R,function_call:P,role:I,tool_calls:O,...v}=_;if(wn(v),Object.assign(g.message,v),R)g.message.refusal=(g.message.refusal||"")+R;if(I)g.message.role=I;if(P)if(!g.message.function_call)g.message.function_call=P;else{if(P.name)g.message.function_call.name=P.name;if(P.arguments)(n=g.message.function_call).arguments??(n.arguments=""),g.message.function_call.arguments+=P.arguments}if(C){if(g.message.content=(g.message.content||"")+C,!g.message.refusal&&i(this,L,"m",xs).call(this))g.message.parsed=_s(g.message.content)}if(O){if(!g.message.tool_calls)g.message.tool_calls=[];for(let{index:q,id:F,type:E,function:D,...se}of O){let S=(o=g.message.tool_calls)[q]??(o[q]={});if(Object.assign(S,se),F)S.id=F;if(E)S.type=E;if(D)S.function??(S.function={name:D.name??"",arguments:""});if(D?.name)S.function.name=D.name;if(D?.arguments){if(S.function.arguments+=D.arguments,un(i(this,ce,"f"),S))S.function.parsed_arguments=_s(S.function.arguments)}}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function go(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:_,finish_reason:y,index:p,logprobs:u,...w})=>{if(!y)throw new m(`missing finish_reason for choice ${p}`);let{content:g=null,function_call:C,tool_calls:R,...P}=_,I=_.role;if(!I)throw new m(`missing role for choice ${p}`);if(C){let{arguments:O,name:v}=C;if(O==null)throw new m(`missing function_call.arguments for choice ${p}`);if(!v)throw new m(`missing function_call.name for choice ${p}`);return{...w,message:{content:g,function_call:{arguments:O,name:v},role:I,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}if(R)return{...w,index:p,finish_reason:y,logprobs:u,message:{...P,role:I,content:g,refusal:_.refusal??null,tool_calls:R.map((O,v)=>{let{function:q,type:F,id:E,...D}=O,{arguments:se,name:S,...fe}=q||{};if(E==null)throw new m(`missing choices[${p}].tool_calls[${v}].id
|
|
12
|
+
${Tr(e)}`);if(F==null)throw new m(`missing choices[${p}].tool_calls[${v}].type
|
|
13
|
+
${Tr(e)}`);if(S==null)throw new m(`missing choices[${p}].tool_calls[${v}].function.name
|
|
14
|
+
${Tr(e)}`);if(se==null)throw new m(`missing choices[${p}].tool_calls[${v}].function.arguments
|
|
15
|
+
${Tr(e)}`);return{...D,id:E,type:F,function:{...fe,name:S,arguments:se}}})}};return{...w,message:{...P,content:g,role:I,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return cn(d,t)}function Tr(e){return JSON.stringify(e)}function wn(e){return}function xn(e){}class Ve extends pe{static fromReadableStream(e){let t=new Ve(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Ve(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class me extends c{constructor(){super(...arguments);this.messages=new qe(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return hn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>Ot(r,e))}runTools(e,t){if(e.stream)return Ve.runTools(this._client,e,t);return Bt.runTools(this._client,e,t)}stream(e,t){return pe.createChatCompletion(this._client,e,t)}}me.Messages=qe;class Ce extends c{constructor(){super(...arguments);this.completions=new me(this._client)}}Ce.Completions=me;var An=Symbol("brand.privateNullableHeaders");function*bo(e){if(!e)return;if(An in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Xr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Xr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of bo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[An]:!0,values:t,nulls:r}};class Ut extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class jt extends c{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Dt extends c{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}}class ue extends c{constructor(){super(...arguments);this.transcriptions=new jt(this._client),this.translations=new Dt(this._client),this.speech=new Ut(this._client)}}ue.Transcriptions=jt;ue.Translations=Dt;ue.Speech=Ut;class Ke 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 Wt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",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 qt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ht extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new qt(this._client),this.transcriptionSessions=new Ht(this._client)}}Ee.Sessions=qt;Ee.TranscriptionSessions=Ht;class Jt extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Xt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Z,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Z,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class ve extends c{constructor(){super(...arguments);this.sessions=new Jt(this._client),this.threads=new Xt(this._client)}}ve.Sessions=Jt;ve.Threads=Xt;class Vt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,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 Kt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var In=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var G=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim();return};var U,ke,As,ee,Fr,z,Oe,Ge,$e,Lr,V,Nr,Mr,Qt,Gt,zt,Pn,Sn,Rn,Cn,En,vn,$n;class _e extends Re{constructor(){super(...arguments);U.add(this),As.set(this,[]),ee.set(this,{}),Fr.set(this,{}),z.set(this,void 0),Oe.set(this,void 0),Ge.set(this,void 0),$e.set(this,void 0),Lr.set(this,void 0),V.set(this,void 0),Nr.set(this,void 0),Mr.set(this,void 0),Qt.set(this,void 0)}[(As=new WeakMap,ee=new WeakMap,Fr=new WeakMap,z=new WeakMap,Oe=new WeakMap,Ge=new WeakMap,$e=new WeakMap,Lr=new WeakMap,V=new WeakMap,Nr=new WeakMap,Mr=new WeakMap,Qt=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new ke;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=X.fromReadableStream(e,this.controller);for await(let n of s)i(this,U,"m",Gt).call(this,n);if(s.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Gt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}static createThreadAssistantStream(e,t,r){let s=new ke;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Nr,"f")}currentRun(){return i(this,Mr,"f")}currentMessageSnapshot(){return i(this,z,"f")}currentRunStepSnapshot(){return i(this,Qt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,ee,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Fr,"f"))}async finalRun(){if(await this.done(),!i(this,Oe,"f"))throw Error("Final run was not received.");return i(this,Oe,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,U,"m",Gt).call(this,a);if(o.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Gt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Ue(n)&&Ue(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Ue(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}ke=_e,Gt=function(t){if(this.ended)return;switch(b(this,Nr,t,"f"),i(this,U,"m",Rn).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":i(this,U,"m",$n).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":i(this,U,"m",Sn).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,U,"m",Pn).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:Oo(t)}},zt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,Oe,"f"))throw Error("Final run has not been received");return i(this,Oe,"f")},Pn=function(t){let[r,s]=i(this,U,"m",En).call(this,t,i(this,z,"f"));b(this,z,r,"f"),i(this,Fr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ge,"f")){if(i(this,$e,"f"))switch(i(this,$e,"f").type){case"text":this._emit("textDone",i(this,$e,"f").text,i(this,z,"f"));break;case"image_file":this._emit("imageFileDone",i(this,$e,"f").image_file,i(this,z,"f"));break}b(this,Ge,n.index,"f")}b(this,$e,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,z,"f"));break;case"text":this._emit("textDone",n.text,i(this,z,"f"));break}}if(i(this,z,"f"))this._emit("messageDone",t.data);b(this,z,void 0,"f")}},Sn=function(t){let r=i(this,U,"m",Cn).call(this,t);switch(b(this,Qt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Lr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f"));if(b(this,Lr,o.index,"f"),b(this,V,r.step_details.tool_calls[o.index],"f"),i(this,V,"f"))this._emit("toolCallCreated",i(this,V,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(b(this,Qt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),b(this,V,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Rn=function(t){i(this,As,"f").push(t),this._emit("event",t)},Cn=function(t){switch(t.event){case"thread.run.step.created":return i(this,ee,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,ee,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=ke.accumulateDelta(r,s.delta);i(this,ee,"f")[t.data.id]=n}return i(this,ee,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":i(this,ee,"f")[t.data.id]=t.data;break}if(i(this,ee,"f")[t.data.id])return i(this,ee,"f")[t.data.id];throw Error("No snapshot available")},En=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,U,"m",vn).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},vn=function(t,r){return ke.accumulateDelta(r,t)},$n=function(t){switch(b(this,Mr,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(b(this,Oe,t.data,"f"),i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),b(this,V,void 0,"f");break;case"thread.run.cancelling":break}};function Oo(e){}class ze extends c{constructor(){super(...arguments);this.steps=new Kt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,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 _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return _e.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}ze.Steps=Kt;class Te extends c{constructor(){super(...arguments);this.runs=new ze(this._client),this.messages=new Vt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}}Te.Runs=ze;Te.Messages=Vt;class te extends c{constructor(){super(...arguments);this.realtime=new Ee(this._client),this.chatkit=new ve(this._client),this.assistants=new Wt(this._client),this.threads=new Te(this._client)}}te.Realtime=Ee;te.ChatKit=ve;te.Assistants=Wt;te.Threads=Te;class Qe extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Yt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Ye extends c{constructor(){super(...arguments);this.content=new Yt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,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=Yt;class Fe 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])})}}Fe.Files=Ye;class Zt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Z,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Ne extends c{constructor(){super(...arguments);this.items=new Zt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Ne.Items=Zt;class Ze extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)k(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return k(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=In(f)});return o})}}class er extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class et extends c{constructor(){super(...arguments);this.outputItems=new er(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,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=er;class Me 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)}}Me.Runs=et;class tt extends c{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",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 Q(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ie({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class tr extends c{}class rr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class rt extends c{constructor(){super(...arguments);this.graders=new rr(this._client)}}rt.Graders=rr;class sr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,ie,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Z,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class st extends c{constructor(){super(...arguments);this.permissions=new sr(this._client)}}st.Permissions=sr;class nr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class ot extends c{constructor(){super(...arguments);this.checkpoints=new nr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",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)}}ot.Checkpoints=nr;class re extends c{constructor(){super(...arguments);this.methods=new tr(this._client),this.jobs=new ot(this._client),this.checkpoints=new st(this._client),this.alpha=new rt(this._client)}}re.Methods=tr;re.Jobs=ot;re.Checkpoints=st;re.Alpha=rt;class or extends c{}class Le extends c{constructor(){super(...arguments);this.graderModels=new or(this._client)}}Le.GraderModels=or;class it extends c{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class at extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ie,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class lt extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class ir extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ar extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class ge extends c{constructor(){super(...arguments);this.clientSecrets=new ar(this._client),this.calls=new ir(this._client)}}ge.ClientSecrets=ar;ge.Calls=ir;function kn(e,t){if(!t||!Qo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return Is(e,t)}function Is(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:ei(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:zo(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Br(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function zo(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function Qo(e){if(kt(e.text?.format))return!0;return!1}function Yo(e){return e?.$brand==="auto-parseable-tool"}function Zo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function ei(e,t){let r=Zo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Yo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Br(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var ct,Ur,ye,jr,On,Tn,Fn,Nn;class Dr extends Re{constructor(e){super();ct.add(this),Ur.set(this,void 0),ye.set(this,void 0),jr.set(this,void 0),b(this,Ur,e,"f")}static createResponse(e,t,r){let s=new Dr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,ct,"m",On).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,ct,"m",Tn).call(this,a,o);if(n.controller.signal?.aborted)throw new N;return i(this,ct,"m",Fn).call(this)}[(Ur=new WeakMap,ye=new WeakMap,jr=new WeakMap,ct=new WeakSet,On=function(){if(this.ended)return;b(this,ye,void 0,"f")},Tn=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,ct,"m",Nn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new 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}},Fn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ye,"f");if(!t)throw new m("request ended without sending any events");b(this,ye,void 0,"f");let r=ti(t,i(this,Ur,"f"));return b(this,jr,r,"f"),r},Nn=function(t){let r=i(this,ye,"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,ye,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new 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,ye,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,jr,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ti(e,t){return kn(e,t)}class lr extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class cr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class be extends c{constructor(){super(...arguments);this.inputItems=new lr(this._client),this.inputTokens=new cr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Br(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Br(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>Is(r,e))}stream(e,t){return Dr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}be.InputItems=lr;be.InputTokens=cr;class ur extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class fr extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class ut extends c{constructor(){super(...arguments);this.content=new fr(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ut.Content=fr;class we extends c{constructor(){super(...arguments);this.content=new ur(this._client),this.versions=new ut(this._client)}create(e={},t){return this._client.post("/skills",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}we.Content=ur;we.Versions=ut;class hr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,K({body:t,...r},this._client))}}class Be extends c{constructor(){super(...arguments);this.parts=new hr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Be.Parts=hr;var Mn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,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 Q(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(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 Mn(y),await this.createAndPoll(e,{file_ids:d})}}class pr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,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 Q(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,ie,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class xe extends c{constructor(){super(...arguments);this.files=new pr(this._client),this.fileBatches=new dr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",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`,ie,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}xe.Files=pr;xe.FileBatches=dr;class ft extends c{create(e,t){return this._client.post("/videos",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Z,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ae({body:t,...r},this._client))}}var ht,Ln,Wr;class dt extends c{constructor(){super(...arguments);ht.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");i(this,ht,"m",Ln).call(this,r);let n=h([t]).values,o=i(this,ht,"m",Wr).call(this,n,"webhook-signature"),a=i(this,ht,"m",Wr).call(this,n,"webhook-timestamp"),f=i(this,ht,"m",Wr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new ne("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new ne("Webhook timestamp is too old");if(d>_+s)throw new ne("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 C=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,C,new TextEncoder().encode(u)))return}catch{continue}throw new ne("The given webhook signature does not match the expected signature")}}ht=new WeakSet,Ln=function(t){if(typeof t!=="string"||t.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Wr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Ps,Ss,qr,Bn;class A{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("OPENAI_API_KEY"),organization:r=G("OPENAI_ORG_ID")??null,project:s=G("OPENAI_PROJECT_ID")??null,webhookSecret:n=G("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Ps.add(this),qr.set(this,void 0),this.completions=new Qe(this),this.chat=new Ce(this),this.embeddings=new Ze(this),this.files=new tt(this),this.images=new it(this),this.audio=new ue(this),this.moderations=new lt(this),this.models=new at(this),this.fineTuning=new re(this),this.graders=new Le(this),this.vectorStores=new xe(this),this.webhooks=new dt(this),this.beta=new te(this),this.batches=new Ke(this),this.uploads=new Be(this),this.responses=new be(this),this.realtime=new ge(this),this.conversations=new Ne(this),this.evals=new Me(this),this.containers=new Fe(this),this.skills=new we(this),this.videos=new ft(this),t===void 0)throw new 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&&Ms())throw new m(`It looks like you're running in a browser-like environment.
|
|
16
|
+
|
|
17
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
18
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
19
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
20
|
+
|
|
21
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
22
|
+
|
|
23
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
24
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Ss.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=ss(a.logLevel,"ClientOptions.logLevel",this)??ss(G("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Bs(),b(this,qr,js,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Gs(e)}getUserAgent(){return`${this.constructor.name}/JS ${he}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jr()}`}makeStatusError(e,t,r,s){return T.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof 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,Ps,"m",Bn).call(this)&&r||this.baseURL,n=Es(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!vs(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Pe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(k(this).debug(`[${d}] sending request`,oe({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new N;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(mt),w=Date.now();if(u instanceof globalThis.Error){let R=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new N;let P=pt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return k(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${R}`),k(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${R})`,oe({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(k(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),k(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,oe({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),P)throw new Ie;throw new Ae({cause:u})}let g=[...u.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,P])=>", "+R+": "+JSON.stringify(P)).join(""),C=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let R=await this.shouldRetry(u);if(t&&R){let F=`retrying, ${t} attempts remaining`;return await Us(u.body),k(this).info(`${C} - ${F}`),k(this).debug(`[${d}] response error (${F})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let P=R?"error; no more retries left":"error; not retryable";k(this).info(`${C} - ${P}`);let I=await u.text().catch((F)=>mt(F).message),O=Os(I),v=O?void 0:I;throw k(this).debug(`[${d}] response error (${P})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:v,durationMs:Date.now()-y})),this.makeStatusError(u.status,O,v,u.headers)}return k(this).info(C),k(this).debug(`[${d}] response start`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs: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 Ar(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=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 Q(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)ks("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=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))}:{},...Ls(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:mr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,qr,"f").call(this,{body:e,headers:r})}}Ss=A,qr=new WeakMap,Ps=new WeakSet,Bn=function(){return this.baseURL!=="https://api.openai.com/v1"};A.OpenAI=Ss;A.DEFAULT_TIMEOUT=600000;A.OpenAIError=m;A.APIError=T;A.APIConnectionError=Ae;A.APIConnectionTimeoutError=Ie;A.APIUserAbortError=N;A.NotFoundError=bt;A.ConflictError=wt;A.RateLimitError=At;A.BadRequestError=_t;A.AuthenticationError=gt;A.InternalServerError=It;A.PermissionDeniedError=yt;A.UnprocessableEntityError=xt;A.InvalidWebhookSignatureError=ne;A.toFile=Pr;A.Completions=Qe;A.Chat=Ce;A.Embeddings=Ze;A.Files=tt;A.Images=it;A.Audio=ue;A.Moderations=lt;A.Models=at;A.FineTuning=re;A.Graders=Le;A.VectorStores=xe;A.Webhooks=dt;A.Beta=te;A.Batches=Ke;A.Uploads=Be;A.Responses=be;A.Realtime=ge;A.Conversations=Ne;A.Evals=Me;A.Containers=Fe;A.Skills=we;A.Videos=ft;class nt extends A{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("AZURE_OPENAI_API_KEY"),apiVersion:r=G("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new 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(fi.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Ue(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var fi=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{A,nt};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{G,E,m,N,b,V,h,q,H,f,pe,K,ee}from"./shumai-agent-app.js";var{awsEndpointFunctions:De,emitWarningIfUnsupportedVersion:ke,createDefaultUserAgentProvider:$e,NODE_APP_ID_CONFIG_OPTIONS:we,getAwsRegionExtensionConfiguration:Ne,resolveAwsRegionExtensionConfiguration:be,resolveUserAgentConfig:Ue,resolveHostHeaderConfig:Fe,getUserAgentPlugin:qe,getHostHeaderPlugin:He,getLoggerPlugin:Me,getRecursionDetectionPlugin:Ge}=f(),{NoAuthSigner:je,getHttpAuthSchemeEndpointRuleSetPlugin:Ke,DefaultIdentityProviderConfig:Ve,getHttpSigningPlugin:ze}=H(),{normalizeProvider:Z,getSmithyContext:Le,ServiceException:Be,NoOpLogger:We,emitWarningIfUnsupportedVersion:Ye,loadConfigsForDefaultMode:Je,getDefaultExtensionConfiguration:Xe,resolveDefaultRuntimeConfig:Qe,Client:te,makeBuilder:Ze,createAggregatedClient:et}=E(),{Command:tt}=E();var Vr=tt,zr=te;var{resolveDefaultsModeConfig:rt,loadConfig:_,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:ot,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:nt,NODE_REGION_CONFIG_OPTIONS:st,NODE_REGION_CONFIG_FILE_OPTIONS:it,resolveRegionConfig:ct}=m(),{BinaryDecisionDiagram:at,EndpointCache:pt,decideEndpoint:dt,customEndpointFunctions:ut,resolveEndpointConfig:lt,getEndpointPlugin:ht}=N(),{parseUrl:_t,getHttpHandlerExtensionConfiguration:gt,resolveHttpHandlerRuntimeConfig:Et,getContentLengthPlugin:mt}=h(),{DEFAULT_RETRY_MODE:xt,NODE_RETRY_MODE_CONFIG_OPTIONS:ft,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:St,resolveRetryConfig:vt,getRetryPlugin:Pt}=q(),{TypeRegistry:re,getSchemaSerdePlugin:It}=G(),{resolveAwsSdkSigV4Config:Ct,AwsSdkSigV4Signer:At,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:yt}=K(),{toUtf8:Tt,fromUtf8:Ot,toBase64:Rt,fromBase64:Dt,calculateBodyLength:kt}=b(),{streamCollector:$t,NodeHttpHandler:wt}=ee(),{AwsRestJsonProtocol:Nt}=pe(),{Sha256:bt}=V(),Ut=async(e,t,n)=>({operation:Le(t).operation,region:await Z(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Ft(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function qt(e){return{schemeId:"smithy.api#noAuth"}}var Ht=(e)=>{let t=[];switch(e.operation){case"CreateToken":{t.push(qt());break}default:t.push(Ft(e))}return t},Mt=(e)=>{let t=Ct(e);return Object.assign(t,{authSchemePreference:Z(e.authSchemePreference??[])})},Gt=(e)=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),jt={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Kt="3.997.43",Vt={version:Kt},S="ref",g=-1,P=!0,Y="isSet",oe="PartitionResult",I="booleanEquals",j="getAttr",J={[S]:"Endpoint"},z={[S]:oe},x={},X=[{[S]:"Region"}],Q={conditions:[[Y,[J]],[Y,X],["aws.partition",X,oe],[I,[{[S]:"UseFIPS"},P]],[I,[{[S]:"UseDualStack"},P]],[I,[{fn:j,argv:[z,"supportsDualStack"]},P]],[I,[{fn:j,argv:[z,"supportsFIPS"]},P]],["stringEquals",[{fn:j,argv:[z,"name"]},"aws-us-gov"]]],results:[[g],[g,"Invalid Configuration: FIPS and custom endpoint are not supported"],[g,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[J,x],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",x],[g,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",x],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",x],[g,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",x],[g,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",x],[g,"Invalid Configuration: Missing Region"]]},zt=2,c=1e8,Lt=new Int32Array([-1,1,-1,0,13,3,1,4,c+12,2,5,c+12,3,8,6,4,7,c+11,5,c+9,c+10,4,11,9,6,10,c+8,7,c+6,c+7,5,12,c+5,6,c+4,c+5,3,c+1,14,4,c+2,c+3]),Bt=at.from(Lt,zt,Q.conditions,Q.results),Wt=new pt({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Yt=(e,t={})=>Wt.get(e,()=>dt(Bt,{endpointParams:e,logger:t.logger}));ut.aws=De;class i extends Be{constructor(e){super(e);Object.setPrototypeOf(this,i.prototype)}}class C extends i{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class A extends i{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e});Object.setPrototypeOf(this,A.prototype),this.error=e.error,this.error_description=e.error_description}}class y extends i{name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,y.prototype),this.error=e.error,this.error_description=e.error_description}}class T extends i{name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e});Object.setPrototypeOf(this,T.prototype),this.error=e.error,this.error_description=e.error_description}}class O extends i{name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e});Object.setPrototypeOf(this,O.prototype),this.error=e.error,this.error_description=e.error_description}}class R extends i{name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e});Object.setPrototypeOf(this,R.prototype),this.error=e.error,this.error_description=e.error_description}}class D extends i{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,D.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class k extends i{name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e});Object.setPrototypeOf(this,k.prototype),this.error=e.error,this.error_description=e.error_description}}class w extends i{name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e});Object.setPrototypeOf(this,w.prototype),this.error=e.error,this.error_description=e.error_description}}class U extends i{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e});Object.setPrototypeOf(this,U.prototype),this.error=e.error,this.error_description=e.error_description}}class F extends i{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e});Object.setPrototypeOf(this,F.prototype),this.error=e.error,this.error_description=e.error_description}}var Jt="AccessDeniedException",Xt="AuthorizationPendingException",Qt="AccessToken",Zt="ClientSecret",er="CreateToken",tr="CreateTokenRequest",rr="CreateTokenResponse",or="CodeVerifier",nr="ExpiredTokenException",sr="InvalidClientException",ir="InvalidGrantException",cr="InvalidRequestException",ar="InternalServerException",pr="InvalidScopeException",dr="IdToken",ur="RefreshToken",lr="SlowDownException",hr="UnauthorizedClientException",_r="UnsupportedGrantTypeException",gr="accessToken",l="client",Er="clientId",mr="clientSecret",xr="codeVerifier",fr="code",Sr="deviceCode",r="error",vr="expiresIn",d="error_description",Pr="grantType",Ir="http",u="httpError",Cr="idToken",ne="reason",se="refreshToken",Ar="redirectUri",ie="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",yr="scope",Tr="server",Or="tokenType",o="com.amazonaws.ssooidc",ce=re.for(ie),ae=[-3,ie,"SSOOIDCServiceException",0,[],[]];ce.registerError(ae,i);var a=re.for(o),de=[-3,o,Jt,{[r]:l,[u]:400},[r,ne,d],[0,0,0]];a.registerError(de,C);var ue=[-3,o,Xt,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(ue,A);var le=[-3,o,nr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(le,y);var he=[-3,o,ar,{[r]:Tr,[u]:500},[r,d],[0,0]];a.registerError(he,T);var _e=[-3,o,sr,{[r]:l,[u]:401},[r,d],[0,0]];a.registerError(_e,O);var ge=[-3,o,ir,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(ge,R);var Ee=[-3,o,cr,{[r]:l,[u]:400},[r,ne,d],[0,0,0]];a.registerError(Ee,D);var me=[-3,o,pr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(me,k);var xe=[-3,o,lr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(xe,w);var fe=[-3,o,hr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(fe,U);var Se=[-3,o,_r,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(Se,F);var ve=[ce,a],Rr=[0,o,Qt,8,0],Dr=[0,o,Zt,8,0],kr=[0,o,or,8,0],$r=[0,o,dr,8,0],Pe=[0,o,ur,8,0],Ie=[3,o,tr,0,[Er,mr,Pr,Sr,fr,se,yr,Ar,xr],[0,[()=>Dr,0],0,0,0,[()=>Pe,0],64,0,[()=>kr,0]],3],Ce=[3,o,rr,0,[gr,Or,vr,se,Cr],[[()=>Rr,0],0,1,[()=>Pe,0],[()=>$r,0]]],Ae=[9,o,er,{[Ir]:["POST","/token",200]},()=>Ie,()=>Ce],wr=(e)=>({apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??Dt,base64Encoder:e?.base64Encoder??Rt,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??Yt,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??Ht,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new At},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new je}],logger:e?.logger??new We,protocol:e?.protocol??Nt,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:ve,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:e?.serviceId??"SSO OIDC",sha256:e?.sha256??bt,urlParser:e?.urlParser??_t,utf8Decoder:e?.utf8Decoder??Ot,utf8Encoder:e?.utf8Encoder??Tt}),Nr=(e)=>{Ye(process.version);let t=rt(e),n=()=>t().then(Je),p=wr(e);ke(process.version);let s={profile:e?.profile,logger:p.logger};return{...p,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??_(yt,s),bodyLengthChecker:e?.bodyLengthChecker??kt,defaultUserAgentProvider:e?.defaultUserAgentProvider??$e({serviceId:p.serviceId,clientVersion:Vt.version}),maxAttempts:e?.maxAttempts??_(St,e),region:e?.region??_(st,{...it,...s}),requestHandler:wt.create(e?.requestHandler??n),retryMode:e?.retryMode??_({...ft,default:async()=>(await n()).retryMode||xt},e),streamCollector:e?.streamCollector??$t,useDualstackEndpoint:e?.useDualstackEndpoint??_(nt,s),useFipsEndpoint:e?.useFipsEndpoint??_(ot,s),userAgentAppId:e?.userAgentAppId??_(we,s)}},br=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:n,credentials:p}=e;return{setHttpAuthScheme(s){let v=t.findIndex((M)=>M.schemeId===s.schemeId);if(v===-1)t.push(s);else t.splice(v,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){n=s},httpAuthSchemeProvider(){return n},setCredentials(s){p=s},credentials(){return p}}},Ur=(e)=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),Fr=(e,t)=>{let n=Object.assign(Ne(e),Xe(e),gt(e),br(e));return t.forEach((p)=>p.configure(n)),Object.assign(e,be(n),Qe(n),Et(n),Ur(n))};class L extends te{config;constructor(...[e]){let t=Nr(e||{});super(t);this.initConfig=t;let n=Gt(t),p=Ue(n),s=vt(p),v=ct(s),M=Fe(v),ye=lt(M),Te=Mt(ye),Oe=Fr(Te,e?.extensions||[]);this.config=Oe,this.middlewareStack.use(It(this.config)),this.middlewareStack.use(qe(this.config)),this.middlewareStack.use(Pt(this.config)),this.middlewareStack.use(mt(this.config)),this.middlewareStack.use(He(this.config)),this.middlewareStack.use(Me(this.config)),this.middlewareStack.use(Ge(this.config)),this.middlewareStack.use(Ke(this.config,{httpAuthSchemeParametersProvider:Ut,identityProviderConfigProvider:async(Re)=>new Ve({"aws.auth#sigv4":Re.credentials})})),this.middlewareStack.use(ze(this.config))}destroy(){super.destroy()}}var qr=Ze(jt,"AWSSSOOIDCService","SSOOIDCClient",ht),Hr={},Mr=(e,t,n,p)=>[];class B extends qr(Hr,Mr,"CreateToken",Ae){}var Gr={CreateTokenCommand:B};class W extends L{}et(Gr,W);var jr={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},Kr={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};var Lr=C,Br=de,Wr=jr,Yr=A,Jr=ue,Xr=Ae,Qr=B,Zr=Ie,eo=Ce,to=y,ro=le,oo=T,no=he,so=O,io=_e,co=R,ao=ge,po=D,uo=Ee,lo=Kr,ho=k,_o=me,go=W,Eo=L,mo=i,xo=ae,fo=w,So=xe,vo=U,Po=fe,Io=F,Co=Se,Ao=ve;export{Vr as $Command,zr as __Client,Lr as AccessDeniedException,Br as AccessDeniedException$,Wr as AccessDeniedExceptionReason,Yr as AuthorizationPendingException,Jr as AuthorizationPendingException$,Xr as CreateToken$,Qr as CreateTokenCommand,Zr as CreateTokenRequest$,eo as CreateTokenResponse$,to as ExpiredTokenException,ro as ExpiredTokenException$,oo as InternalServerException,no as InternalServerException$,so as InvalidClientException,io as InvalidClientException$,co as InvalidGrantException,ao as InvalidGrantException$,po as InvalidRequestException,uo as InvalidRequestException$,lo as InvalidRequestExceptionReason,ho as InvalidScopeException,_o as InvalidScopeException$,go as SSOOIDC,Eo as SSOOIDCClient,mo as SSOOIDCServiceException,xo as SSOOIDCServiceException$,fo as SlowDownException,So as SlowDownException$,vo as UnauthorizedClientException,Po as UnauthorizedClientException$,Io as UnsupportedGrantTypeException,Co as UnsupportedGrantTypeException$,Ao as errorTypeRegistries};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{yt,D,qe,Ke,$e,et,at,lt,St,xt,oe,Z,x}from"./chunk-y2adfzyt.js";export{$e as EncryptJWT,Ke as SignJWT,St as UnsecuredJWT,yt as base64url,et as calculateJwkThumbprint,at as createLocalJWKSet,lt as createRemoteJWKSet,x as decodeJwt,Z as decodeProtectedHeader,oe as importJWK,xt as importPKCS8,qe as jwtDecrypt,D as jwtVerify};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function ne(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{ne};
|