sliccy 1.23.1 → 1.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/ui/assets/{___vite-browser-external_commonjs-proxy-BKv5OE3C.js → ___vite-browser-external_commonjs-proxy-BZRJ6_X4.js} +1 -1
  2. package/dist/ui/assets/anthropic-CFRG0Hfe.js +2 -0
  3. package/dist/ui/assets/anthropic-h0YkYJvY.js +2 -0
  4. package/dist/ui/assets/azure-openai-responses-B72ahkq2.js +1 -0
  5. package/dist/ui/assets/azure-openai-responses-DiuVg7QC.js +1 -0
  6. package/dist/ui/assets/{bsh-watchdog-DB83IzZv.js → bsh-watchdog-BHj7Fs8o.js} +1 -1
  7. package/dist/ui/assets/client-CLc9DbbF.js +23 -0
  8. package/dist/ui/assets/client-DFw1b8C8.js +23 -0
  9. package/dist/ui/assets/github-copilot-headers-CrHPofPv.js +1 -0
  10. package/dist/ui/assets/github-copilot-headers-Dz44zqGk.js +1 -0
  11. package/dist/ui/assets/google-CVSsY19W.js +1 -0
  12. package/dist/ui/assets/google-FJTEoy_e.js +1 -0
  13. package/dist/ui/assets/google-gemini-cli-T80C305w.js +2 -0
  14. package/dist/ui/assets/google-gemini-cli-gF7kFWc4.js +2 -0
  15. package/dist/ui/assets/google-shared-BjArPveV.js +2 -0
  16. package/dist/ui/assets/google-shared-CYYiav7i.js +2 -0
  17. package/dist/ui/assets/google-vertex-6VDNXf5n.js +1 -0
  18. package/dist/ui/assets/google-vertex-CjjOIg6q.js +1 -0
  19. package/dist/ui/assets/hash-DMDecQcg.js +1 -0
  20. package/dist/ui/assets/hash-k-C9KAKF.js +1 -0
  21. package/dist/ui/assets/{index-CrfoZPQJ.js → index-BTBHJQVY.js} +1 -1
  22. package/dist/ui/assets/{index-CQRAjoqa.js → index-BbFB6aZt.js} +2 -2
  23. package/dist/ui/assets/{index-CjFLX_BQ.js → index-C7KXlIoI.js} +1 -1
  24. package/dist/ui/assets/{index-CB9d8R5t.js → index-C9qsgFXA.js} +1 -1
  25. package/dist/ui/assets/{index-nN116LF3.js → index-CMitoXJI.js} +1 -1
  26. package/dist/ui/assets/index-CYH9nDaE.js +15023 -0
  27. package/dist/ui/assets/{index-DPxj4SEp.js → index-CmZETbUD.js} +1 -1
  28. package/dist/ui/assets/{index-POROIraC.js → index-Et7zk9Rb.js} +2 -2
  29. package/dist/ui/assets/{index-Dx4-d-T7.js → index-TCK0ykMx.js} +1 -1
  30. package/dist/ui/assets/index-uz_REvSi.js +5 -0
  31. package/dist/ui/assets/json-parse-BRxcI2Wj.js +1 -0
  32. package/dist/ui/assets/json-parse-zqPLE5kv.js +1 -0
  33. package/dist/ui/assets/mistral-BnNh3LzR.js +8 -0
  34. package/dist/ui/assets/mistral-DBk4zmZV.js +8 -0
  35. package/dist/ui/assets/{offscreen-client-DB1yW_jz.js → offscreen-client-DdMA5sAC.js} +1 -1
  36. package/dist/ui/assets/openai-codex-responses-BRTJp-Ny.js +7 -0
  37. package/dist/ui/assets/openai-codex-responses-DXePmJ37.js +7 -0
  38. package/dist/ui/assets/openai-completions-BJ5tXvNF.js +6 -0
  39. package/dist/ui/assets/openai-completions-CFS00Zu3.js +6 -0
  40. package/dist/ui/assets/openai-responses-D0cbe-PZ.js +1 -0
  41. package/dist/ui/assets/openai-responses-GLrZ6X81.js +1 -0
  42. package/dist/ui/assets/openai-responses-shared-B_0Hvupy.js +10 -0
  43. package/dist/ui/assets/openai-responses-shared-CCp4pUoS.js +10 -0
  44. package/dist/ui/assets/{sql-wasm-D2ZVRXNf.js → sql-wasm-WyohJvyK.js} +1 -1
  45. package/dist/ui/assets/transform-messages-BkE2P08Y.js +1 -0
  46. package/dist/ui/assets/transform-messages-DqxXnsXK.js +1 -0
  47. package/dist/ui/index.html +1 -1
  48. package/dist/ui/packages/webapp/index.html +1 -1
  49. package/package.json +1 -1
  50. package/dist/ui/assets/index-DyNmsPks.js +0 -15079
@@ -1 +1 @@
1
- import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{g as r}from"./index-DyNmsPks.js";const a=r(e);export{a as r};
1
+ import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{k as r}from"./index-CYH9nDaE.js";const a=r(e);export{a as r};
@@ -0,0 +1,2 @@
1
+ import{A as v,g as C,a as x,b as k}from"./index-CYH9nDaE.js";import{p as b}from"./json-parse-zqPLE5kv.js";import{b as I,a as R,s as f,t as E}from"./transform-messages-BkE2P08Y.js";import{h as A,b as S}from"./github-copilot-headers-CrHPofPv.js";var j={};function B(t){return t||(typeof process<"u"&&j.PI_CACHE_RETENTION==="long"?"long":"short")}function M(t,i){const a=B(i);if(a==="none")return{retention:a};const n=a==="long"&&t.includes("api.anthropic.com")?"1h":void 0;return{retention:a,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}const P="2.1.75",L=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],U=new Map(L.map(t=>[t.toLowerCase(),t])),T=t=>U.get(t.toLowerCase())??t,W=(t,i)=>{if(i&&i.length>0){const a=t.toLowerCase(),n=i.find(e=>e.name.toLowerCase()===a);if(n)return n.name}return t};function w(t){if(!t.some(e=>e.type==="image"))return f(t.map(e=>e.text).join(`
2
+ `));const a=t.map(e=>e.type==="text"?{type:"text",text:f(e.text)}:{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}});return a.some(e=>e.type==="text")||a.unshift({type:"text",text:"(see attached image)"}),a}function y(...t){const i={};for(const a of t)a&&Object.assign(i,a);return i}const _=(t,i,a)=>{const n=new v;return(async()=>{const e={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,u;if(a?.client)o=a.client,u=!1;else{const s=a?.apiKey??C(t.provider)??"";let l;if(t.provider==="github-copilot"){const h=A(i.messages);l=S({messages:i.messages,hasImages:h})}const r=J(t,s,a?.interleavedThinking??!0,a?.headers,l);o=r.client,u=r.isOAuthToken}let d=H(t,i,u,a);const g=await a?.onPayload?.(d,t);g!==void 0&&(d=g);const c=o.messages.stream({...d,stream:!0},{signal:a?.signal});n.push({type:"start",partial:e});const p=e.content;for await(const s of c)if(s.type==="message_start")e.responseId=s.message.id,e.usage.input=s.message.usage.input_tokens||0,e.usage.output=s.message.usage.output_tokens||0,e.usage.cacheRead=s.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=s.message.usage.cache_creation_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,x(t,e.usage);else if(s.type==="content_block_start"){if(s.content_block.type==="text"){const l={type:"text",text:"",index:s.index};e.content.push(l),n.push({type:"text_start",contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type==="thinking"){const l={type:"thinking",thinking:"",thinkingSignature:"",index:s.index};e.content.push(l),n.push({type:"thinking_start",contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type==="redacted_thinking"){const l={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:s.content_block.data,redacted:!0,index:s.index};e.content.push(l),n.push({type:"thinking_start",contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type==="tool_use"){const l={type:"toolCall",id:s.content_block.id,name:u?W(s.content_block.name,i.tools):s.content_block.name,arguments:s.content_block.input??{},partialJson:"",index:s.index};e.content.push(l),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e})}}else if(s.type==="content_block_delta"){if(s.delta.type==="text_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="text"&&(r.text+=s.delta.text,n.push({type:"text_delta",contentIndex:l,delta:s.delta.text,partial:e}))}else if(s.delta.type==="thinking_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="thinking"&&(r.thinking+=s.delta.thinking,n.push({type:"thinking_delta",contentIndex:l,delta:s.delta.thinking,partial:e}))}else if(s.delta.type==="input_json_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="toolCall"&&(r.partialJson+=s.delta.partial_json,r.arguments=b(r.partialJson),n.push({type:"toolcall_delta",contentIndex:l,delta:s.delta.partial_json,partial:e}))}else if(s.delta.type==="signature_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="thinking"&&(r.thinkingSignature=r.thinkingSignature||"",r.thinkingSignature+=s.delta.signature)}}else if(s.type==="content_block_stop"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&(delete r.index,r.type==="text"?n.push({type:"text_end",contentIndex:l,content:r.text,partial:e}):r.type==="thinking"?n.push({type:"thinking_end",contentIndex:l,content:r.thinking,partial:e}):r.type==="toolCall"&&(r.arguments=b(r.partialJson),delete r.partialJson,n.push({type:"toolcall_end",contentIndex:l,toolCall:r,partial:e})))}else s.type==="message_delta"&&(s.delta.stop_reason&&(e.stopReason=$(s.delta.stop_reason)),s.usage.input_tokens!=null&&(e.usage.input=s.usage.input_tokens),s.usage.output_tokens!=null&&(e.usage.output=s.usage.output_tokens),s.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=s.usage.cache_read_input_tokens),s.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=s.usage.cache_creation_input_tokens),e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,x(t,e.usage));if(a?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="aborted"||e.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:e.stopReason,message:e}),n.end()}catch(o){for(const u of e.content)delete u.index;e.stopReason=a?.signal?.aborted?"aborted":"error",e.errorMessage=o instanceof Error?o.message:JSON.stringify(o),n.push({type:"error",reason:e.stopReason,error:e}),n.end()}})(),n};function m(t){return t.includes("opus-4-6")||t.includes("opus-4.6")||t.includes("sonnet-4-6")||t.includes("sonnet-4.6")}function O(t,i){switch(t){case"minimal":return"low";case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return i.includes("opus-4-6")||i.includes("opus-4.6")?"max":"high";default:return"high"}}const Q=(t,i,a)=>{const n=a?.apiKey||C(t.provider);if(!n)throw new Error(`No API key for provider: ${t.provider}`);const e=I(t,a,n);if(!a?.reasoning)return _(t,i,{...e,thinkingEnabled:!1});if(m(t.id)){const u=O(a.reasoning,t.id);return _(t,i,{...e,thinkingEnabled:!0,effort:u})}const o=R(e.maxTokens||0,t.maxTokens,a.reasoning,a.thinkingBudgets);return _(t,i,{...e,maxTokens:o.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:o.thinkingBudget})};function N(t){return t.includes("sk-ant-oat")}function J(t,i,a,n,e){const o=a&&!m(t.id);if(t.provider==="github-copilot"){const g=[];return o&&g.push("interleaved-thinking-2025-05-14"),{client:new k({apiKey:null,authToken:i,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:y({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...g.length>0?{"anthropic-beta":g.join(",")}:{}},t.headers,e,n)}),isOAuthToken:!1}}const u=["fine-grained-tool-streaming-2025-05-14"];return o&&u.push("interleaved-thinking-2025-05-14"),N(i)?{client:new k({apiKey:null,authToken:i,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:y({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":`claude-code-20250219,oauth-2025-04-20,${u.join(",")}`,"user-agent":`claude-cli/${P}`,"x-app":"cli"},t.headers,n)}),isOAuthToken:!0}:{client:new k({apiKey:i,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:y({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":u.join(",")},t.headers,n)}),isOAuthToken:!1}}function H(t,i,a,n){const{cacheControl:e}=M(t.baseUrl,n?.cacheRetention),o={model:t.id,messages:q(i.messages,t,a,e),max_tokens:n?.maxTokens||t.maxTokens/3|0,stream:!0};if(a?(o.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...e?{cache_control:e}:{}}],i.systemPrompt&&o.system.push({type:"text",text:f(i.systemPrompt),...e?{cache_control:e}:{}})):i.systemPrompt&&(o.system=[{type:"text",text:f(i.systemPrompt),...e?{cache_control:e}:{}}]),n?.temperature!==void 0&&!n?.thinkingEnabled&&(o.temperature=n.temperature),i.tools&&(o.tools=F(i.tools,a)),t.reasoning&&(n?.thinkingEnabled?m(t.id)?(o.thinking={type:"adaptive"},n.effort&&(o.output_config={effort:n.effort})):o.thinking={type:"enabled",budget_tokens:n.thinkingBudgetTokens||1024}:n?.thinkingEnabled===!1&&(o.thinking={type:"disabled"})),n?.metadata){const u=n.metadata.user_id;typeof u=="string"&&(o.metadata={user_id:u})}return n?.toolChoice&&(typeof n.toolChoice=="string"?o.tool_choice={type:n.toolChoice}:o.tool_choice=n.toolChoice),o}function K(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function q(t,i,a,n){const e=[],o=E(t,i,K);for(let u=0;u<o.length;u++){const d=o[u];if(d.role==="user")if(typeof d.content=="string")d.content.trim().length>0&&e.push({role:"user",content:f(d.content)});else{const g=d.content.map(p=>p.type==="text"?{type:"text",text:f(p.text)}:{type:"image",source:{type:"base64",media_type:p.mimeType,data:p.data}});let c=i?.input.includes("image")?g:g.filter(p=>p.type!=="image");if(c=c.filter(p=>p.type==="text"?p.text.trim().length>0:!0),c.length===0)continue;e.push({role:"user",content:c})}else if(d.role==="assistant"){const g=[];for(const c of d.content)if(c.type==="text"){if(c.text.trim().length===0)continue;g.push({type:"text",text:f(c.text)})}else if(c.type==="thinking"){if(c.redacted){g.push({type:"redacted_thinking",data:c.thinkingSignature});continue}if(c.thinking.trim().length===0)continue;!c.thinkingSignature||c.thinkingSignature.trim().length===0?g.push({type:"text",text:f(c.thinking)}):g.push({type:"thinking",thinking:f(c.thinking),signature:c.thinkingSignature})}else c.type==="toolCall"&&g.push({type:"tool_use",id:c.id,name:a?T(c.name):c.name,input:c.arguments??{}});if(g.length===0)continue;e.push({role:"assistant",content:g})}else if(d.role==="toolResult"){const g=[];g.push({type:"tool_result",tool_use_id:d.toolCallId,content:w(d.content),is_error:d.isError});let c=u+1;for(;c<o.length&&o[c].role==="toolResult";){const p=o[c];g.push({type:"tool_result",tool_use_id:p.toolCallId,content:w(p.content),is_error:p.isError}),c++}u=c-1,e.push({role:"user",content:g})}}if(n&&e.length>0){const u=e[e.length-1];if(u.role==="user")if(Array.isArray(u.content)){const d=u.content[u.content.length-1];d&&(d.type==="text"||d.type==="image"||d.type==="tool_result")&&(d.cache_control=n)}else typeof u.content=="string"&&(u.content=[{type:"text",text:u.content,cache_control:n}])}return e}function F(t,i){return t?t.map(a=>{const n=a.parameters;return{name:i?T(a.name):a.name,description:a.description,input_schema:{type:"object",properties:n.properties||{},required:n.required||[]}}}):[]}function $(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"tool_use":return"toolUse";case"refusal":return"error";case"pause_turn":return"stop";case"stop_sequence":return"stop";case"sensitive":return"error";default:throw new Error(`Unhandled stop reason: ${t}`)}}export{_ as streamAnthropic,Q as streamSimpleAnthropic};
@@ -0,0 +1,2 @@
1
+ import{f as v,h as C,i as x,b as k}from"./index-CYH9nDaE.js";import{p as b}from"./json-parse-BRxcI2Wj.js";import{b as I,a as R,s as f,t as E}from"./transform-messages-DqxXnsXK.js";import{h as A,b as S}from"./github-copilot-headers-Dz44zqGk.js";var j={};function B(t){return t||(typeof process<"u"&&j.PI_CACHE_RETENTION==="long"?"long":"short")}function M(t,i){const a=B(i);if(a==="none")return{retention:a};const n=a==="long"&&t.includes("api.anthropic.com")?"1h":void 0;return{retention:a,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}const P="2.1.75",L=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],U=new Map(L.map(t=>[t.toLowerCase(),t])),T=t=>U.get(t.toLowerCase())??t,W=(t,i)=>{if(i&&i.length>0){const a=t.toLowerCase(),n=i.find(e=>e.name.toLowerCase()===a);if(n)return n.name}return t};function w(t){if(!t.some(e=>e.type==="image"))return f(t.map(e=>e.text).join(`
2
+ `));const a=t.map(e=>e.type==="text"?{type:"text",text:f(e.text)}:{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}});return a.some(e=>e.type==="text")||a.unshift({type:"text",text:"(see attached image)"}),a}function y(...t){const i={};for(const a of t)a&&Object.assign(i,a);return i}const _=(t,i,a)=>{const n=new v;return(async()=>{const e={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,u;if(a?.client)o=a.client,u=!1;else{const s=a?.apiKey??C(t.provider)??"";let l;if(t.provider==="github-copilot"){const h=A(i.messages);l=S({messages:i.messages,hasImages:h})}const r=J(t,s,a?.interleavedThinking??!0,a?.headers,l);o=r.client,u=r.isOAuthToken}let d=H(t,i,u,a);const g=await a?.onPayload?.(d,t);g!==void 0&&(d=g);const c=o.messages.stream({...d,stream:!0},{signal:a?.signal});n.push({type:"start",partial:e});const p=e.content;for await(const s of c)if(s.type==="message_start")e.responseId=s.message.id,e.usage.input=s.message.usage.input_tokens||0,e.usage.output=s.message.usage.output_tokens||0,e.usage.cacheRead=s.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=s.message.usage.cache_creation_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,x(t,e.usage);else if(s.type==="content_block_start"){if(s.content_block.type==="text"){const l={type:"text",text:"",index:s.index};e.content.push(l),n.push({type:"text_start",contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type==="thinking"){const l={type:"thinking",thinking:"",thinkingSignature:"",index:s.index};e.content.push(l),n.push({type:"thinking_start",contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type==="redacted_thinking"){const l={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:s.content_block.data,redacted:!0,index:s.index};e.content.push(l),n.push({type:"thinking_start",contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type==="tool_use"){const l={type:"toolCall",id:s.content_block.id,name:u?W(s.content_block.name,i.tools):s.content_block.name,arguments:s.content_block.input??{},partialJson:"",index:s.index};e.content.push(l),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e})}}else if(s.type==="content_block_delta"){if(s.delta.type==="text_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="text"&&(r.text+=s.delta.text,n.push({type:"text_delta",contentIndex:l,delta:s.delta.text,partial:e}))}else if(s.delta.type==="thinking_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="thinking"&&(r.thinking+=s.delta.thinking,n.push({type:"thinking_delta",contentIndex:l,delta:s.delta.thinking,partial:e}))}else if(s.delta.type==="input_json_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="toolCall"&&(r.partialJson+=s.delta.partial_json,r.arguments=b(r.partialJson),n.push({type:"toolcall_delta",contentIndex:l,delta:s.delta.partial_json,partial:e}))}else if(s.delta.type==="signature_delta"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&r.type==="thinking"&&(r.thinkingSignature=r.thinkingSignature||"",r.thinkingSignature+=s.delta.signature)}}else if(s.type==="content_block_stop"){const l=p.findIndex(h=>h.index===s.index),r=p[l];r&&(delete r.index,r.type==="text"?n.push({type:"text_end",contentIndex:l,content:r.text,partial:e}):r.type==="thinking"?n.push({type:"thinking_end",contentIndex:l,content:r.thinking,partial:e}):r.type==="toolCall"&&(r.arguments=b(r.partialJson),delete r.partialJson,n.push({type:"toolcall_end",contentIndex:l,toolCall:r,partial:e})))}else s.type==="message_delta"&&(s.delta.stop_reason&&(e.stopReason=$(s.delta.stop_reason)),s.usage.input_tokens!=null&&(e.usage.input=s.usage.input_tokens),s.usage.output_tokens!=null&&(e.usage.output=s.usage.output_tokens),s.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=s.usage.cache_read_input_tokens),s.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=s.usage.cache_creation_input_tokens),e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,x(t,e.usage));if(a?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="aborted"||e.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:e.stopReason,message:e}),n.end()}catch(o){for(const u of e.content)delete u.index;e.stopReason=a?.signal?.aborted?"aborted":"error",e.errorMessage=o instanceof Error?o.message:JSON.stringify(o),n.push({type:"error",reason:e.stopReason,error:e}),n.end()}})(),n};function m(t){return t.includes("opus-4-6")||t.includes("opus-4.6")||t.includes("sonnet-4-6")||t.includes("sonnet-4.6")}function O(t,i){switch(t){case"minimal":return"low";case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return i.includes("opus-4-6")||i.includes("opus-4.6")?"max":"high";default:return"high"}}const Q=(t,i,a)=>{const n=a?.apiKey||C(t.provider);if(!n)throw new Error(`No API key for provider: ${t.provider}`);const e=I(t,a,n);if(!a?.reasoning)return _(t,i,{...e,thinkingEnabled:!1});if(m(t.id)){const u=O(a.reasoning,t.id);return _(t,i,{...e,thinkingEnabled:!0,effort:u})}const o=R(e.maxTokens||0,t.maxTokens,a.reasoning,a.thinkingBudgets);return _(t,i,{...e,maxTokens:o.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:o.thinkingBudget})};function N(t){return t.includes("sk-ant-oat")}function J(t,i,a,n,e){const o=a&&!m(t.id);if(t.provider==="github-copilot"){const g=[];return o&&g.push("interleaved-thinking-2025-05-14"),{client:new k({apiKey:null,authToken:i,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:y({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...g.length>0?{"anthropic-beta":g.join(",")}:{}},t.headers,e,n)}),isOAuthToken:!1}}const u=["fine-grained-tool-streaming-2025-05-14"];return o&&u.push("interleaved-thinking-2025-05-14"),N(i)?{client:new k({apiKey:null,authToken:i,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:y({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":`claude-code-20250219,oauth-2025-04-20,${u.join(",")}`,"user-agent":`claude-cli/${P}`,"x-app":"cli"},t.headers,n)}),isOAuthToken:!0}:{client:new k({apiKey:i,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:y({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":u.join(",")},t.headers,n)}),isOAuthToken:!1}}function H(t,i,a,n){const{cacheControl:e}=M(t.baseUrl,n?.cacheRetention),o={model:t.id,messages:q(i.messages,t,a,e),max_tokens:n?.maxTokens||t.maxTokens/3|0,stream:!0};if(a?(o.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...e?{cache_control:e}:{}}],i.systemPrompt&&o.system.push({type:"text",text:f(i.systemPrompt),...e?{cache_control:e}:{}})):i.systemPrompt&&(o.system=[{type:"text",text:f(i.systemPrompt),...e?{cache_control:e}:{}}]),n?.temperature!==void 0&&!n?.thinkingEnabled&&(o.temperature=n.temperature),i.tools&&(o.tools=F(i.tools,a)),t.reasoning&&(n?.thinkingEnabled?m(t.id)?(o.thinking={type:"adaptive"},n.effort&&(o.output_config={effort:n.effort})):o.thinking={type:"enabled",budget_tokens:n.thinkingBudgetTokens||1024}:n?.thinkingEnabled===!1&&(o.thinking={type:"disabled"})),n?.metadata){const u=n.metadata.user_id;typeof u=="string"&&(o.metadata={user_id:u})}return n?.toolChoice&&(typeof n.toolChoice=="string"?o.tool_choice={type:n.toolChoice}:o.tool_choice=n.toolChoice),o}function K(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function q(t,i,a,n){const e=[],o=E(t,i,K);for(let u=0;u<o.length;u++){const d=o[u];if(d.role==="user")if(typeof d.content=="string")d.content.trim().length>0&&e.push({role:"user",content:f(d.content)});else{const g=d.content.map(p=>p.type==="text"?{type:"text",text:f(p.text)}:{type:"image",source:{type:"base64",media_type:p.mimeType,data:p.data}});let c=i?.input.includes("image")?g:g.filter(p=>p.type!=="image");if(c=c.filter(p=>p.type==="text"?p.text.trim().length>0:!0),c.length===0)continue;e.push({role:"user",content:c})}else if(d.role==="assistant"){const g=[];for(const c of d.content)if(c.type==="text"){if(c.text.trim().length===0)continue;g.push({type:"text",text:f(c.text)})}else if(c.type==="thinking"){if(c.redacted){g.push({type:"redacted_thinking",data:c.thinkingSignature});continue}if(c.thinking.trim().length===0)continue;!c.thinkingSignature||c.thinkingSignature.trim().length===0?g.push({type:"text",text:f(c.thinking)}):g.push({type:"thinking",thinking:f(c.thinking),signature:c.thinkingSignature})}else c.type==="toolCall"&&g.push({type:"tool_use",id:c.id,name:a?T(c.name):c.name,input:c.arguments??{}});if(g.length===0)continue;e.push({role:"assistant",content:g})}else if(d.role==="toolResult"){const g=[];g.push({type:"tool_result",tool_use_id:d.toolCallId,content:w(d.content),is_error:d.isError});let c=u+1;for(;c<o.length&&o[c].role==="toolResult";){const p=o[c];g.push({type:"tool_result",tool_use_id:p.toolCallId,content:w(p.content),is_error:p.isError}),c++}u=c-1,e.push({role:"user",content:g})}}if(n&&e.length>0){const u=e[e.length-1];if(u.role==="user")if(Array.isArray(u.content)){const d=u.content[u.content.length-1];d&&(d.type==="text"||d.type==="image"||d.type==="tool_result")&&(d.cache_control=n)}else typeof u.content=="string"&&(u.content=[{type:"text",text:u.content,cache_control:n}])}return e}function F(t,i){return t?t.map(a=>{const n=a.parameters;return{name:i?T(a.name):a.name,description:a.description,input_schema:{type:"object",properties:n.properties||{},required:n.required||[]}}}):[]}function $(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"tool_use":return"toolUse";case"refusal":return"error";case"pause_turn":return"stop";case"stop_sequence":return"stop";case"sensitive":return"error";default:throw new Error(`Unhandled stop reason: ${t}`)}}export{_ as streamAnthropic,Q as streamSimpleAnthropic};
@@ -0,0 +1 @@
1
+ import{O as A,a as c,r as m,i as E,b as _}from"./client-CLc9DbbF.js";import{f as h,h as l,j as R}from"./index-CYH9nDaE.js";import{p as y,c as I,a as O}from"./openai-responses-shared-B_0Hvupy.js";import{b as N,c as b}from"./transform-messages-DqxXnsXK.js";import"./hash-k-C9KAKF.js";import"./json-parse-BRxcI2Wj.js";var g={};class v extends A{constructor({baseURL:r=m("OPENAI_BASE_URL"),apiKey:e=m("AZURE_OPENAI_API_KEY"),apiVersion:t=m("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:o,dangerouslyAllowBrowser:i,...u}={}){if(!t)throw new c("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"&&(i=!0),!o&&!e)throw new c("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&e)throw new c("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(u.defaultQuery={...u.defaultQuery,"api-version":t},r){if(n)throw new c("baseURL and endpoint are mutually exclusive")}else{if(n||(n=g.AZURE_OPENAI_ENDPOINT),!n)throw new c("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");r=`${n}/openai`}super({apiKey:o??e,baseURL:r,...u,...i!==void 0?{dangerouslyAllowBrowser:i}:{}}),this.apiVersion="",this.apiVersion=t,this.deploymentName=a}async buildRequest(r,e={}){if(P.has(r.path)&&r.method==="post"&&r.body!==void 0){if(!E(r.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||r.body.model||r.__metadata?.model;t!==void 0&&!this.baseURL.includes("/deployments")&&(r.path=`/deployments/${t}${r.path}`)}return super.buildRequest(r,e)}async authHeaders(r){return typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(r)}}const P=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var p={};const U="v1",w=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function S(s){const r=new Map;if(!s)return r;for(const e of s.split(",")){const t=e.trim();if(!t)continue;const[n,a]=t.split("=",2);!n||!a||r.set(n.trim(),a.trim())}return r}function z(s,r){return r?.azureDeploymentName?r.azureDeploymentName:S(p.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(s.id)||s.id}const Z=(s,r,e)=>{const t=new h;return(async()=>{const n=z(s,e),a={role:"assistant",content:[],api:"azure-openai-responses",provider:s.provider,model:s.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const o=e?.apiKey||l(s.provider)||"",i=L(s,o,e);let u=V(s,r,e,n);const d=await e?.onPayload?.(u,s);d!==void 0&&(u=d);const f=await i.responses.create(u,e?.signal?{signal:e.signal}:void 0);if(t.push({type:"start",partial:a}),await y(f,a,t,s),e?.signal?.aborted)throw new Error("Request was aborted");if(a.stopReason==="aborted"||a.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:a.stopReason,message:a}),t.end()}catch(o){for(const i of a.content)delete i.index;a.stopReason=e?.signal?.aborted?"aborted":"error",a.errorMessage=o instanceof Error?o.message:JSON.stringify(o),t.push({type:"error",reason:a.stopReason,error:a}),t.end()}})(),t},Y=(s,r,e)=>{const t=e?.apiKey||l(s.provider);if(!t)throw new Error(`No API key for provider: ${s.provider}`);const n=N(s,e,t),a=R(s)?e?.reasoning:b(e?.reasoning);return Z(s,r,{...n,reasoningEffort:a})};function M(s){return s.replace(/\/+$/,"")}function D(s){return`https://${s}.openai.azure.com/openai/v1`}function K(s,r){const e=r?.azureApiVersion||p.AZURE_OPENAI_API_VERSION||U,t=r?.azureBaseUrl?.trim()||p.AZURE_OPENAI_BASE_URL?.trim()||void 0,n=r?.azureResourceName||p.AZURE_OPENAI_RESOURCE_NAME;let a=t;if(!a&&n&&(a=D(n)),!a&&s.baseUrl&&(a=s.baseUrl),!a)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:M(a),apiVersion:e}}function L(s,r,e){if(!r){if(!p.AZURE_OPENAI_API_KEY)throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");r=p.AZURE_OPENAI_API_KEY}const t={...s.headers};e?.headers&&Object.assign(t,e.headers);const{baseUrl:n,apiVersion:a}=K(s,e);return new v({apiKey:r,apiVersion:a,dangerouslyAllowBrowser:!0,defaultHeaders:t,baseURL:n})}function V(s,r,e,t){const n=I(s,r,w),a={model:t,input:n,stream:!0,prompt_cache_key:e?.sessionId};return e?.maxTokens&&(a.max_output_tokens=e?.maxTokens),e?.temperature!==void 0&&(a.temperature=e?.temperature),r.tools&&(a.tools=O(r.tools)),s.reasoning&&(e?.reasoningEffort||e?.reasoningSummary?(a.reasoning={effort:e?.reasoningEffort||"medium",summary:e?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]):a.reasoning={effort:"none"}),a}export{Z as streamAzureOpenAIResponses,Y as streamSimpleAzureOpenAIResponses};
@@ -0,0 +1 @@
1
+ import{O as A,a as c,r as m,i as E,b as _}from"./client-DFw1b8C8.js";import{A as h,g as l,s as R}from"./index-CYH9nDaE.js";import{p as y,c as I,a as O}from"./openai-responses-shared-CCp4pUoS.js";import{b as N,c as g}from"./transform-messages-BkE2P08Y.js";import"./hash-DMDecQcg.js";import"./json-parse-zqPLE5kv.js";var b={};class v extends A{constructor({baseURL:r=m("OPENAI_BASE_URL"),apiKey:e=m("AZURE_OPENAI_API_KEY"),apiVersion:t=m("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:o,dangerouslyAllowBrowser:i,...u}={}){if(!t)throw new c("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"&&(i=!0),!o&&!e)throw new c("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&e)throw new c("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(u.defaultQuery={...u.defaultQuery,"api-version":t},r){if(n)throw new c("baseURL and endpoint are mutually exclusive")}else{if(n||(n=b.AZURE_OPENAI_ENDPOINT),!n)throw new c("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");r=`${n}/openai`}super({apiKey:o??e,baseURL:r,...u,...i!==void 0?{dangerouslyAllowBrowser:i}:{}}),this.apiVersion="",this.apiVersion=t,this.deploymentName=a}async buildRequest(r,e={}){if(P.has(r.path)&&r.method==="post"&&r.body!==void 0){if(!E(r.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||r.body.model||r.__metadata?.model;t!==void 0&&!this.baseURL.includes("/deployments")&&(r.path=`/deployments/${t}${r.path}`)}return super.buildRequest(r,e)}async authHeaders(r){return typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(r)}}const P=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var p={};const U="v1",w=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function S(s){const r=new Map;if(!s)return r;for(const e of s.split(",")){const t=e.trim();if(!t)continue;const[n,a]=t.split("=",2);!n||!a||r.set(n.trim(),a.trim())}return r}function z(s,r){return r?.azureDeploymentName?r.azureDeploymentName:S(p.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(s.id)||s.id}const Z=(s,r,e)=>{const t=new h;return(async()=>{const n=z(s,e),a={role:"assistant",content:[],api:"azure-openai-responses",provider:s.provider,model:s.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const o=e?.apiKey||l(s.provider)||"",i=L(s,o,e);let u=V(s,r,e,n);const d=await e?.onPayload?.(u,s);d!==void 0&&(u=d);const f=await i.responses.create(u,e?.signal?{signal:e.signal}:void 0);if(t.push({type:"start",partial:a}),await y(f,a,t,s),e?.signal?.aborted)throw new Error("Request was aborted");if(a.stopReason==="aborted"||a.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:a.stopReason,message:a}),t.end()}catch(o){for(const i of a.content)delete i.index;a.stopReason=e?.signal?.aborted?"aborted":"error",a.errorMessage=o instanceof Error?o.message:JSON.stringify(o),t.push({type:"error",reason:a.stopReason,error:a}),t.end()}})(),t},Y=(s,r,e)=>{const t=e?.apiKey||l(s.provider);if(!t)throw new Error(`No API key for provider: ${s.provider}`);const n=N(s,e,t),a=R(s)?e?.reasoning:g(e?.reasoning);return Z(s,r,{...n,reasoningEffort:a})};function M(s){return s.replace(/\/+$/,"")}function D(s){return`https://${s}.openai.azure.com/openai/v1`}function K(s,r){const e=r?.azureApiVersion||p.AZURE_OPENAI_API_VERSION||U,t=r?.azureBaseUrl?.trim()||p.AZURE_OPENAI_BASE_URL?.trim()||void 0,n=r?.azureResourceName||p.AZURE_OPENAI_RESOURCE_NAME;let a=t;if(!a&&n&&(a=D(n)),!a&&s.baseUrl&&(a=s.baseUrl),!a)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:M(a),apiVersion:e}}function L(s,r,e){if(!r){if(!p.AZURE_OPENAI_API_KEY)throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");r=p.AZURE_OPENAI_API_KEY}const t={...s.headers};e?.headers&&Object.assign(t,e.headers);const{baseUrl:n,apiVersion:a}=K(s,e);return new v({apiKey:r,apiVersion:a,dangerouslyAllowBrowser:!0,defaultHeaders:t,baseURL:n})}function V(s,r,e,t){const n=I(s,r,w),a={model:t,input:n,stream:!0,prompt_cache_key:e?.sessionId};return e?.maxTokens&&(a.max_output_tokens=e?.maxTokens),e?.temperature!==void 0&&(a.temperature=e?.temperature),r.tools&&(a.tools=O(r.tools)),s.reasoning&&(e?.reasoningEffort||e?.reasoningSummary?(a.reasoning={effort:e?.reasoningEffort||"medium",summary:e?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]):a.reasoning={effort:"none"}),a}export{Z as streamAzureOpenAIResponses,Y as streamSimpleAzureOpenAIResponses};
@@ -1,2 +1,2 @@
1
- import{c as u}from"./index-DyNmsPks.js";const l=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of l)await s.exists(r)&&await p(s,r,t,e);return t}async function p(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const i=g(n);if(!i)continue;const a=await s.readFile(n,{encoding:"utf-8"}),c=typeof a=="string"?a:new TextDecoder().decode(a),f=m(c);e.push({path:n,hostnamePattern:i,matchPatterns:f})}}function g(s){const t=s.split("/").pop()??"";if(!t.endsWith(".bsh"))return null;const e=t.slice(0,-4);return e?e.startsWith("-.")?"*"+e.slice(1):e:null}function m(s){const t=s.split(`
1
+ import{c as u}from"./index-CYH9nDaE.js";const l=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of l)await s.exists(r)&&await p(s,r,t,e);return t}async function p(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const i=g(n);if(!i)continue;const a=await s.readFile(n,{encoding:"utf-8"}),c=typeof a=="string"?a:new TextDecoder().decode(a),f=m(c);e.push({path:n,hostnamePattern:i,matchPatterns:f})}}function g(s){const t=s.split("/").pop()??"";if(!t.endsWith(".bsh"))return null;const e=t.slice(0,-4);return e?e.startsWith("-.")?"*"+e.slice(1):e:null}function m(s){const t=s.split(`
2
2
  `).slice(0,10),e=[];for(const r of t){const n=r.match(/^\s*\/\/\s*@match\s+(.+)$/);n&&e.push(n[1].trim())}return e}function h(s,t){if(t.startsWith("*.")){const e=t.slice(1);return s.endsWith(e)&&s.length>e.length}return s===t}function v(s,t){try{const e=new URL(s),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;const[,n,i,a]=r;return n!=="*"&&e.protocol.slice(0,-1)!==n||!h(e.hostname,i)?!1:a?x(e.pathname+e.search,a):!0}catch{return!1}}function x(s,t){const e="^"+t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$";return new RegExp(e).test(s)}function w(s,t){try{const e=new URL(t);return s.filter(r=>h(e.hostname,r.hostnamePattern)?r.matchPatterns.length>0?r.matchPatterns.some(n=>v(t,n)):!0:!1)}catch{return[]}}const o=u("bsh-watchdog");class S{transport;fs;execute;discoveryIntervalMs;entries=[];discoveryTimer=null;running=!1;executing=new Set;constructor(t){this.transport=t.transport,this.fs=t.fs,this.execute=t.execute,this.discoveryIntervalMs=t.discoveryIntervalMs??3e4}async start(){this.running||(this.running=!0,await this.discover(),this.discoveryTimer=setInterval(()=>{this.discover()},this.discoveryIntervalMs),this.transport.on("Page.frameNavigated",this.onFrameNavigated),o.info("BSH watchdog started",{scriptCount:this.entries.length}))}stop(){this.running&&(this.running=!1,this.transport.off("Page.frameNavigated",this.onFrameNavigated),this.discoveryTimer&&(clearInterval(this.discoveryTimer),this.discoveryTimer=null),this.entries=[],this.executing.clear(),o.info("BSH watchdog stopped"))}async discover(){try{this.entries=await d(this.fs),o.debug("BSH discovery complete",{count:this.entries.length})}catch(t){o.error("BSH discovery failed",{error:t instanceof Error?t.message:String(t)})}}getEntries(){return this.entries}onFrameNavigated=t=>{const e=t.frame;if(e?.parentId||!e?.url)return;const r=e.url;if(!r.startsWith("http://")&&!r.startsWith("https://")||this.entries.length===0)return;const n=w(this.entries,r);if(n.length!==0)for(const i of n){const a=`${i.path}::${r}`;this.executing.has(a)||(this.executing.add(a),o.info("BSH watchdog executing script",{script:i.path,url:r}),this.execute(i.path).then(c=>{c.exitCode!==0?o.warn("BSH script failed",{script:i.path,url:r,exitCode:c.exitCode,stderr:c.stderr.slice(0,200)}):o.info("BSH script completed",{script:i.path,url:r})}).catch(c=>{o.error("BSH script execution error",{script:i.path,url:r,error:c instanceof Error?c.message:String(c)})}).finally(()=>{this.executing.delete(a)}))}}}export{S as BshWatchdog};
@@ -0,0 +1,23 @@
1
+ function S(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function o(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let Bs=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Bs=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function Ct(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const $t=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class y extends Error{}class D extends y{constructor(e,t,s,r){super(`${D.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=t;const i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new it({message:s,cause:$t(t)});const i=t?.error;return e===400?new Ds(e,i,s,r):e===401?new Ws(e,i,s,r):e===403?new Us(e,i,s,r):e===404?new js(e,i,s,r):e===409?new qs(e,i,s,r):e===422?new Hs(e,i,s,r):e===429?new Js(e,i,s,r):e>=500?new Xs(e,i,s,r):new D(e,i,s,r)}}class K extends D{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class it extends D{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Dt extends it{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ds extends D{}class Ws extends D{}class Us extends D{}class js extends D{}class qs extends D{}class Hs extends D{}class Js extends D{}class Xs extends D{}class Ks extends y{constructor(){super("Could not parse response content as the length limit was reached")}}class Vs extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ge extends Error{constructor(e){super(e)}}const br=/^[a-z][a-z0-9+.-]*:/i,Sr=n=>br.test(n);let j=n=>(j=Array.isArray,j(n)),hs=j;function zs(n){return typeof n!="object"?{}:n??{}}function xr(n){if(!n)return!0;for(const e in n)return!1;return!0}function Ar(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function gt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const vr=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e},Cr=n=>{try{return JSON.parse(n)}catch{return}},Pe=n=>new Promise(e=>setTimeout(e,n)),ce="6.26.0",$r=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Rr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Ir=()=>{const n=Rr();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":fs(Deno.build.os),"X-Stainless-Arch":ds(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":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ds(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=kr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function kr(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,a=s[3]||0;return{browser:e,version:`${r}.${i}.${a}`}}}return null}const ds=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",fs=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let ps;const Er=()=>ps??(ps=Ir());function Or(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Qs(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function Gs(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Qs({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function Ys(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Pr(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const Tr=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Zs="RFC3986",en=n=>String(n),ms={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:en},Mr="RFC1738";let Rt=(n,e)=>(Rt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Rt(n,e));const z=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),wt=1024,Nr=(n,e,t,s,r)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<i.length;l+=wt){const d=i.length>=wt?i.slice(l,l+wt):i,f=[];for(let m=0;m<d.length;++m){let h=d.charCodeAt(m);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===Mr&&(h===40||h===41)){f[f.length]=d.charAt(m);continue}if(h<128){f[f.length]=z[h];continue}if(h<2048){f[f.length]=z[192|h>>6]+z[128|h&63];continue}if(h<55296||h>=57344){f[f.length]=z[224|h>>12]+z[128|h>>6&63]+z[128|h&63];continue}m+=1,h=65536+((h&1023)<<10|d.charCodeAt(m)&1023),f[f.length]=z[240|h>>18]+z[128|h>>12&63]+z[128|h>>6&63]+z[128|h&63]}a+=f.join("")}return a};function Fr(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function _s(n,e){if(j(n)){const t=[];for(let s=0;s<n.length;s+=1)t.push(e(n[s]));return t}return e(n)}const tn={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},sn=function(n,e){Array.prototype.push.apply(n,j(e)?e:[e])};let gs;const P={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Nr,encodeValuesOnly:!1,format:Zs,formatter:en,indices:!1,serializeDate(n){return(gs??(gs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Lr(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const yt={};function nn(n,e,t,s,r,i,a,l,d,f,m,h,g,u,A,b,I,v){let w=n,T=v,C=0,X=!1;for(;(T=T.get(yt))!==void 0&&!X;){const k=T.get(n);if(C+=1,typeof k<"u"){if(k===C)throw new RangeError("Cyclic object value");X=!0}typeof T.get(yt)>"u"&&(C=0)}if(typeof f=="function"?w=f(e,w):w instanceof Date?w=g?.(w):t==="comma"&&j(w)&&(w=_s(w,function(k){return k instanceof Date?g?.(k):k})),w===null){if(i)return d&&!b?d(e,P.encoder,I,"key",u):e;w=""}if(Lr(w)||Fr(w)){if(d){const k=b?e:d(e,P.encoder,I,"key",u);return[A?.(k)+"="+A?.(d(w,P.encoder,I,"value",u))]}return[A?.(e)+"="+A?.(String(w))]}const W=[];if(typeof w>"u")return W;let R;if(t==="comma"&&j(w))b&&d&&(w=_s(w,d)),R=[{value:w.length>0?w.join(",")||null:void 0}];else if(j(f))R=f;else{const k=Object.keys(w);R=m?k.sort(m):k}const F=l?String(e).replace(/\./g,"%2E"):String(e),M=s&&j(w)&&w.length===1?F+"[]":F;if(r&&j(w)&&w.length===0)return M+"[]";for(let k=0;k<R.length;++k){const E=R[k],cs=typeof E=="object"&&typeof E.value<"u"?E.value:w[E];if(a&&cs===null)continue;const _t=h&&l?E.replace(/\./g,"%2E"):E,yr=j(w)?typeof t=="function"?t(M,_t):M:M+(h?"."+_t:"["+_t+"]");v.set(n,C);const us=new WeakMap;us.set(yt,v),sn(W,nn(cs,yr,t,s,r,i,a,l,t==="comma"&&b&&j(w)?null:d,f,m,h,g,u,A,b,I,us))}return W}function Br(n=P){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||P.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Zs;if(typeof n.format<"u"){if(!Rt(ms,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const s=ms[t];let r=P.filter;(typeof n.filter=="function"||j(n.filter))&&(r=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in tn?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=P.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:P.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:P.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:P.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:P.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?P.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:P.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:P.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:P.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:P.encodeValuesOnly,filter:r,format:t,formatter:s,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:P.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:P.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:P.strictNullHandling}}function Dr(n,e={}){let t=n;const s=Br(e);let r,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):j(s.filter)&&(i=s.filter,r=i);const a=[];if(typeof t!="object"||t===null)return"";const l=tn[s.arrayFormat],d=l==="comma"&&s.commaRoundTrip;r||(r=Object.keys(t)),s.sort&&r.sort(s.sort);const f=new WeakMap;for(let g=0;g<r.length;++g){const u=r[g];s.skipNulls&&t[u]===null||sn(a,nn(t[u],u,l,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,f))}const m=a.join(s.delimiter);let h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),m.length>0?h+m:""}function Wr(n){return Dr(n,{arrayFormat:"brackets"})}function Ur(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let ws;function Wt(n){let e;return(ws??(e=new globalThis.TextEncoder,ws=e.encode.bind(e)))(n)}let ys;function bs(n){let e;return(ys??(e=new globalThis.TextDecoder,ys=e.decode.bind(e)))(n)}var q,H;class at{constructor(){q.set(this,void 0),H.set(this,void 0),S(this,q,new Uint8Array),S(this,H,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Wt(e):e;S(this,q,Ur([o(this,q,"f"),t]));const s=[];let r;for(;(r=jr(o(this,q,"f"),o(this,H,"f")))!=null;){if(r.carriage&&o(this,H,"f")==null){S(this,H,r.index);continue}if(o(this,H,"f")!=null&&(r.index!==o(this,H,"f")+1||r.carriage)){s.push(bs(o(this,q,"f").subarray(0,o(this,H,"f")-1))),S(this,q,o(this,q,"f").subarray(o(this,H,"f"))),S(this,H,null);continue}const i=o(this,H,"f")!==null?r.preceding-1:r.preceding,a=bs(o(this,q,"f").subarray(0,i));s.push(a),S(this,q,o(this,q,"f").subarray(r.index)),S(this,H,null)}return s}flush(){return o(this,q,"f").length?this.decode(`
2
+ `):[]}}q=new WeakMap,H=new WeakMap;at.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);at.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jr(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function qr(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}const Ge={off:0,error:200,warn:300,info:400,debug:500},Ss=(n,e,t)=>{if(n){if(Ar(Ge,n))return n;L(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function we(){}function Ne(n,e,t){return!e||Ge[n]>Ge[t]?we:e[n].bind(e)}const Hr={error:we,warn:we,info:we,debug:we};let xs=new WeakMap;function L(n){const e=n.logger,t=n.logLevel??"off";if(!e)return Hr;const s=xs.get(e);if(s&&s[0]===t)return s[1];const r={error:Ne("error",e,t),warn:Ne("warn",e,t),info:Ne("info",e,t),debug:Ne("debug",e,t)};return xs.set(e,[t,r]),r}const se=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var _e;class G{constructor(e,t,s){this.iterator=e,_e.set(this,void 0),this.controller=t,S(this,_e,s)}static fromSSEResponse(e,t,s,r){let i=!1;const a=s?L(s):console;async function*l(){if(i)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let d=!1;try{for await(const f of Jr(e,t))if(!d){if(f.data.startsWith("[DONE]")){d=!0;continue}if(f.event===null||!f.event.startsWith("thread.")){let m;try{m=JSON.parse(f.data)}catch(h){throw a.error("Could not parse message into JSON:",f.data),a.error("From chunk:",f.raw),h}if(m&&m.error)throw new D(void 0,m.error,void 0,e.headers);yield r?{event:f.event,data:m}:m}else{let m;try{m=JSON.parse(f.data)}catch(h){throw console.error("Could not parse message into JSON:",f.data),console.error("From chunk:",f.raw),h}if(f.event=="error")throw new D(void 0,m.error,m.message,void 0);yield{event:f.event,data:m}}}d=!0}catch(f){if(Ct(f))return;throw f}finally{d||t.abort()}}return new G(l,t,s)}static fromReadableStream(e,t,s){let r=!1;async function*i(){const l=new at,d=Ys(e);for await(const f of d)for(const m of l.decode(f))yield m;for(const f of l.flush())yield f}async function*a(){if(r)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const d of i())l||d&&(yield JSON.parse(d));l=!0}catch(d){if(Ct(d))return;throw d}finally{l||t.abort()}}return new G(a,t,s)}[(_e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const a=s.next();e.push(a),t.push(a)}return i.shift()}});return[new G(()=>r(e),this.controller,o(this,_e,"f")),new G(()=>r(t),this.controller,o(this,_e,"f"))]}toReadableStream(){const e=this;let t;return Qs({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await t.next();if(i)return s.close();const a=Wt(JSON.stringify(r)+`
4
+ `);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*Jr(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");const t=new Kr,s=new at,r=Ys(n.body);for await(const i of Xr(r))for(const a of s.decode(i)){const l=t.decode(a);l&&(yield l)}for(const i of s.flush()){const a=t.decode(i);a&&(yield a)}}async function*Xr(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Wt(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=qr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class Kr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=Vr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Vr(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function rn(n,e){const{response:t,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return L(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData):G.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const d=t.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;const g=await t.json();return an(g,t)}return await t.text()})();return L(n).debug(`[${s}] response parsed`,se({retryOfRequestLogID:r,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function an(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var ye;class ot extends Promise{constructor(e,t,s=rn){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=s,ye.set(this,void 0),S(this,ye,e)}_thenUnwrap(e){return new ot(o(this,ye,"f"),this.responsePromise,async(t,s)=>an(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,ye,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}ye=new WeakMap;var Fe;class Ut{constructor(e,t,s,r){Fe.set(this,void 0),S(this,Fe,e),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Fe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Fe=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class zr extends ot{constructor(e,t,s){super(e,t,async(r,i)=>new s(r,i.response,await rn(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class lt extends Ut{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class $ extends Ut{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...zs(this.options.query),after:t}}:null}}class ke extends Ut{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...zs(this.options.query),after:e}}:null}}const on=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function $e(n,e,t){return on(),new File(n,e??"unknown_file",t)}function je(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const jt=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Ee=async(n,e)=>It(n.body)?{...n,body:await ln(n.body,e)}:n,fe=async(n,e)=>({...n,body:await ln(n.body,e)}),As=new WeakMap;function Qr(n){const e=typeof n=="function"?n:n.fetch,t=As.get(e);if(t)return t;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return As.set(e,s),s}const ln=async(n,e)=>{if(!await Qr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([s,r])=>kt(t,s,r))),t},cn=n=>n instanceof Blob&&"name"in n,Gr=n=>typeof n=="object"&&n!==null&&(n instanceof Response||jt(n)||cn(n)),It=n=>{if(Gr(n))return!0;if(Array.isArray(n))return n.some(It);if(n&&typeof n=="object"){for(const e in n)if(It(n[e]))return!0}return!1},kt=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,$e([await t.blob()],je(t)));else if(jt(t))n.append(e,$e([await new Response(Gs(t)).blob()],je(t)));else if(cn(t))n.append(e,t,je(t));else if(Array.isArray(t))await Promise.all(t.map(s=>kt(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>kt(n,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},un=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Yr=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&un(n),Zr=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function ei(n,e,t){if(on(),n=await n,Yr(n))return n instanceof File?n:$e([await n.arrayBuffer()],n.name);if(Zr(n)){const r=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),$e(await Et(r),e,t)}const s=await Et(n);if(e||(e=je(n)),!t?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return $e(s,e,t)}async function Et(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(un(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(jt(n))for await(const t of n)e.push(...await Et(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${ti(n)}`)}return e}function ti(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class _{constructor(e){this._client=e}}function hn(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const vs=Object.freeze(Object.create(null)),si=(n=hn)=>function(t,...s){if(t.length===1)return t[0];let r=!1;const i=[],a=t.reduce((m,h,g)=>{/[?#]/.test(h)&&(r=!0);const u=s[g];let A=(r?encodeURIComponent:n)(""+u);return g!==s.length&&(u==null||typeof u=="object"&&u.toString===Object.getPrototypeOf(Object.getPrototypeOf(u.hasOwnProperty??vs)??vs)?.toString)&&(A=u+"",i.push({start:m.length+h.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(u).slice(8,-1)} is not a valid path parameter`})),m+h+(g===s.length?"":A)},""),l=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let f;for(;(f=d.exec(l))!==null;)i.push({start:f.index,length:f[0].length,error:`Value "${f[0]}" can't be safely passed as a path parameter`});if(i.sort((m,h)=>m.start-h.start),i.length>0){let m=0;const h=i.reduce((g,u)=>{const A=" ".repeat(u.start-m),b="^".repeat(u.length);return m=u.start+u.length,g+A+b},"");throw new y(`Path parameters result in path with invalid segments:
6
+ ${i.map(g=>g.error).join(`
7
+ `)}
8
+ ${a}
9
+ ${h}`)}return a},c=si(hn);let dn=class extends _{list(e,t={},s){return this._client.getAPIList(c`/chat/completions/${e}/messages`,$,{query:t,...s})}};function Ye(n){return n!==void 0&&"function"in n&&n.function!==void 0}function qt(n){return n?.$brand==="auto-parseable-response-format"}function Te(n){return n?.$brand==="auto-parseable-tool"}function ni(n,e){return!e||!fn(e)?{...n,choices:n.choices.map(t=>(pn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ht(n,e)}function Ht(n,e){const t=n.choices.map(s=>{if(s.finish_reason==="length")throw new Ks;if(s.finish_reason==="content_filter")throw new Vs;return pn(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>ii(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?ri(e,s.message.content):null}}});return{...n,choices:t}}function ri(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function ii(n,e){const t=n.tools?.find(s=>Ye(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Te(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function ai(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(s=>Ye(s)&&s.function?.name===e.function.name);return Ye(t)&&(Te(t)||t?.function.strict||!1)}function fn(n){return qt(n.response_format)?!0:n.tools?.some(e=>Te(e)||e.type==="function"&&e.function.strict===!0)??!1}function pn(n){for(const e of n||[])if(e.type!=="function")throw new y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function oi(n){for(const e of n??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Ze=n=>n?.role==="assistant",mn=n=>n?.role==="tool";var Ot,qe,He,be,Se,Je,xe,Z,Ae,et,tt,ue,_n;class Jt{constructor(){Ot.add(this),this.controller=new AbortController,qe.set(this,void 0),He.set(this,()=>{}),be.set(this,()=>{}),Se.set(this,void 0),Je.set(this,()=>{}),xe.set(this,()=>{}),Z.set(this,{}),Ae.set(this,!1),et.set(this,!1),tt.set(this,!1),ue.set(this,!1),S(this,qe,new Promise((e,t)=>{S(this,He,e,"f"),S(this,be,t,"f")})),S(this,Se,new Promise((e,t)=>{S(this,Je,e,"f"),S(this,xe,t,"f")})),o(this,qe,"f").catch(()=>{}),o(this,Se,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Ot,"m",_n).bind(this))},0)}_connected(){this.ended||(o(this,He,"f").call(this),this._emit("connect"))}get ended(){return o(this,Ae,"f")}get errored(){return o(this,et,"f")}get aborted(){return o(this,tt,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,Z,"f")[e]||(o(this,Z,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,Z,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(o(this,Z,"f")[e]||(o(this,Z,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{S(this,ue,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){S(this,ue,!0),await o(this,Se,"f")}_emit(e,...t){if(o(this,Ae,"f"))return;e==="end"&&(S(this,Ae,!0),o(this,Je,"f").call(this));const s=o(this,Z,"f")[e];if(s&&(o(this,Z,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!o(this,ue,"f")&&!s?.length&&Promise.reject(r),o(this,be,"f").call(this,r),o(this,xe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!o(this,ue,"f")&&!s?.length&&Promise.reject(r),o(this,be,"f").call(this,r),o(this,xe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}qe=new WeakMap,He=new WeakMap,be=new WeakMap,Se=new WeakMap,Je=new WeakMap,xe=new WeakMap,Z=new WeakMap,Ae=new WeakMap,et=new WeakMap,tt=new WeakMap,ue=new WeakMap,Ot=new WeakSet,_n=function(e){if(S(this,et,!0),e instanceof Error&&e.name==="AbortError"&&(e=new K),e instanceof K)return S(this,tt,!0),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){const t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};function li(n){return typeof n.parse=="function"}var U,Pt,st,Tt,Mt,Nt,gn,wn;const ci=10;class yn extends Jt{constructor(){super(...arguments),U.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),mn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ze(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,U,"m",Pt).call(this)}async finalMessage(){return await this.done(),o(this,U,"m",st).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,U,"m",Tt).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,U,"m",Mt).call(this)}async totalUsage(){return await this.done(),o(this,U,"m",Nt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,U,"m",st).call(this);t&&this._emit("finalMessage",t);const s=o(this,U,"m",Pt).call(this);s&&this._emit("finalContent",s);const r=o(this,U,"m",Tt).call(this);r&&this._emit("finalFunctionToolCall",r);const i=o(this,U,"m",Mt).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",o(this,U,"m",Nt).call(this))}async _createChatCompletion(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,U,"m",gn).call(this,t);const i=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ht(i,t))}async _runChatCompletion(e,t,s){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const r="tool",{tool_choice:i="auto",stream:a,...l}=t,d=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=ci}=s||{},m=t.tools.map(u=>{if(Te(u)){if(!u.$callback)throw new y("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}),h={};for(const u of m)u.type==="function"&&(h[u.function.name||u.function.function.name]=u.function);const g="tools"in t?m.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(const u of t.messages)this._addMessage(u,!1);for(let u=0;u<f;++u){const b=(await this._createChatCompletion(e,{...l,tool_choice:i,tools:g,messages:[...this.messages]},s)).choices[0]?.message;if(!b)throw new y("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(const I of b.tool_calls){if(I.type!=="function")continue;const v=I.id,{name:w,arguments:T}=I.function,C=h[w];if(C){if(d&&d!==w){const F=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:r,tool_call_id:v,content:F});continue}}else{const F=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(h).map(M=>JSON.stringify(M)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:v,content:F});continue}let X;try{X=li(C)?await C.parse(T):T}catch(F){const M=F instanceof Error?F.message:String(F);this._addMessage({role:r,tool_call_id:v,content:M});continue}const W=await C.function(X,this),R=o(this,U,"m",wn).call(this,W);if(this._addMessage({role:r,tool_call_id:v,content:R}),d)return}}}}U=new WeakSet,Pt=function(){return o(this,U,"m",st).call(this).content??null},st=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Ze(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},Tt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ze(t)&&t?.tool_calls?.length)return t.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},Mt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(mn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===t.tool_call_id)))return t.content}},Nt=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},gn=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},wn=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Xt extends yn{static runTools(e,t,s){const r=new Xt,i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}_addMessage(e,t=!0){super._addMessage(e,t),Ze(e)&&e.content&&this._emit("content",e.content)}}const bn=1,Sn=2,xn=4,An=8,vn=16,Cn=32,$n=64,Rn=128,In=256,kn=Rn|In,En=vn|Cn|kn|$n,On=bn|Sn|En,Pn=xn|An,ui=On|Pn,N={STR:bn,NUM:Sn,ARR:xn,OBJ:An,NULL:vn,BOOL:Cn,NAN:$n,INFINITY:Rn,MINUS_INFINITY:In,INF:kn,SPECIAL:En,ATOM:On,COLLECTION:Pn,ALL:ui};class hi extends Error{}class di extends Error{}function fi(n,e=N.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return pi(n.trim(),e)}const pi=(n,e)=>{const t=n.length;let s=0;const r=g=>{throw new hi(`${g} at position ${s}`)},i=g=>{throw new di(`${g} at position ${s}`)},a=()=>(h(),s>=t&&r("Unexpected end of input"),n[s]==='"'?l():n[s]==="{"?d():n[s]==="["?f():n.substring(s,s+4)==="null"||N.NULL&e&&t-s<4&&"null".startsWith(n.substring(s))?(s+=4,null):n.substring(s,s+4)==="true"||N.BOOL&e&&t-s<4&&"true".startsWith(n.substring(s))?(s+=4,!0):n.substring(s,s+5)==="false"||N.BOOL&e&&t-s<5&&"false".startsWith(n.substring(s))?(s+=5,!1):n.substring(s,s+8)==="Infinity"||N.INFINITY&e&&t-s<8&&"Infinity".startsWith(n.substring(s))?(s+=8,1/0):n.substring(s,s+9)==="-Infinity"||N.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(n.substring(s))?(s+=9,-1/0):n.substring(s,s+3)==="NaN"||N.NAN&e&&t-s<3&&"NaN".startsWith(n.substring(s))?(s+=3,NaN):m()),l=()=>{const g=s;let u=!1;for(s++;s<t&&(n[s]!=='"'||u&&n[s-1]==="\\");)u=n[s]==="\\"?!u:!1,s++;if(n.charAt(s)=='"')try{return JSON.parse(n.substring(g,++s-Number(u)))}catch(A){i(String(A))}else if(N.STR&e)try{return JSON.parse(n.substring(g,s-Number(u))+'"')}catch{return JSON.parse(n.substring(g,n.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},d=()=>{s++,h();const g={};try{for(;n[s]!=="}";){if(h(),s>=t&&N.OBJ&e)return g;const u=l();h(),s++;try{const A=a();Object.defineProperty(g,u,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(N.OBJ&e)return g;throw A}h(),n[s]===","&&s++}}catch{if(N.OBJ&e)return g;r("Expected '}' at end of object")}return s++,g},f=()=>{s++;const g=[];try{for(;n[s]!=="]";)g.push(a()),h(),n[s]===","&&s++}catch{if(N.ARR&e)return g;r("Expected ']' at end of array")}return s++,g},m=()=>{if(s===0){n==="-"&&N.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n)}catch(u){if(N.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}i(String(u))}}const g=s;for(n[s]==="-"&&s++;n[s]&&!",]}".includes(n[s]);)s++;s==t&&!(N.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(n.substring(g,s))}catch{n.substring(g,s)==="-"&&N.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n.substring(g,n.lastIndexOf("e")))}catch(A){i(String(A))}}},h=()=>{for(;s<t&&`
10
+ \r `.includes(n[s]);)s++};return a()},Cs=n=>fi(n,N.ALL^N.NUM);var O,Y,ae,ee,bt,Le,St,xt,At,Be,vt,$s;class Oe extends yn{constructor(e){super(),O.add(this),Y.set(this,void 0),ae.set(this,void 0),ee.set(this,void 0),S(this,Y,e),S(this,ae,[])}get currentChatCompletionSnapshot(){return o(this,ee,"f")}static fromReadableStream(e){const t=new Oe(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new Oe(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,O,"m",bt).call(this);const i=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const a of i)o(this,O,"m",St).call(this,a);if(i.controller.signal?.aborted)throw new K;return this._addChatCompletion(o(this,O,"m",Be).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),o(this,O,"m",bt).call(this),this._connected();const r=G.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(o(this,O,"m",Be).call(this)),o(this,O,"m",St).call(this,a),i=a.id;if(r.controller.signal?.aborted)throw new K;return this._addChatCompletion(o(this,O,"m",Be).call(this))}[(Y=new WeakMap,ae=new WeakMap,ee=new WeakMap,O=new WeakSet,bt=function(){this.ended||S(this,ee,void 0)},Le=function(t){let s=o(this,ae,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},o(this,ae,"f")[t.index]=s,s)},St=function(t){if(this.ended)return;const s=o(this,O,"m",$s).call(this,t);this._emit("chunk",t,s);for(const r of t.choices){const i=s.choices[r.index];r.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",r.delta.content,i.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),r.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:i.message.refusal}),r.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:i.logprobs?.content??[]}),r.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});const a=o(this,O,"m",Le).call(this,i);i.finish_reason&&(o(this,O,"m",At).call(this,i),a.current_tool_call_index!=null&&o(this,O,"m",xt).call(this,i,a.current_tool_call_index));for(const l of r.delta.tool_calls??[])a.current_tool_call_index!==l.index&&(o(this,O,"m",At).call(this,i),a.current_tool_call_index!=null&&o(this,O,"m",xt).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=l.index;for(const l of r.delta.tool_calls??[]){const d=i.message.tool_calls?.[l.index];d?.type&&(d?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:d.function?.name,index:l.index,arguments:d.function.arguments,parsed_arguments:d.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(d?.type,void 0))}}},xt=function(t,s){if(o(this,O,"m",Le).call(this,t).done_tool_calls.has(s))return;const i=t.message.tool_calls?.[s];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const a=o(this,Y,"f")?.tools?.find(l=>Ye(l)&&l.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:s,arguments:i.function.arguments,parsed_arguments:Te(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},At=function(t){const s=o(this,O,"m",Le).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const r=o(this,O,"m",vt).call(this);this._emit("content.done",{content:t.message.content,parsed:r?r.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Be=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");const t=o(this,ee,"f");if(!t)throw new y("request ended without sending any chunks");return S(this,ee,void 0),S(this,ae,[]),mi(t,o(this,Y,"f"))},vt=function(){const t=o(this,Y,"f")?.response_format;return qt(t)?t:null},$s=function(t){var s,r,i,a;let l=o(this,ee,"f");const{choices:d,...f}=t;l?Object.assign(l,f):l=S(this,ee,{...f,choices:[]});for(const{delta:m,finish_reason:h,index:g,logprobs:u=null,...A}of t.choices){let b=l.choices[g];if(b||(b=l.choices[g]={finish_reason:h,index:g,message:{},logprobs:u,...A}),u)if(!b.logprobs)b.logprobs=Object.assign({},u);else{const{content:W,refusal:R,...F}=u;Object.assign(b.logprobs,F),W&&((s=b.logprobs).content??(s.content=[]),b.logprobs.content.push(...W)),R&&((r=b.logprobs).refusal??(r.refusal=[]),b.logprobs.refusal.push(...R))}if(h&&(b.finish_reason=h,o(this,Y,"f")&&fn(o(this,Y,"f")))){if(h==="length")throw new Ks;if(h==="content_filter")throw new Vs}if(Object.assign(b,A),!m)continue;const{content:I,refusal:v,function_call:w,role:T,tool_calls:C,...X}=m;if(Object.assign(b.message,X),v&&(b.message.refusal=(b.message.refusal||"")+v),T&&(b.message.role=T),w&&(b.message.function_call?(w.name&&(b.message.function_call.name=w.name),w.arguments&&((i=b.message.function_call).arguments??(i.arguments=""),b.message.function_call.arguments+=w.arguments)):b.message.function_call=w),I&&(b.message.content=(b.message.content||"")+I,!b.message.refusal&&o(this,O,"m",vt).call(this)&&(b.message.parsed=Cs(b.message.content))),C){b.message.tool_calls||(b.message.tool_calls=[]);for(const{index:W,id:R,type:F,function:M,...k}of C){const E=(a=b.message.tool_calls)[W]??(a[W]={});Object.assign(E,k),R&&(E.id=R),F&&(E.type=F),M&&(E.function??(E.function={name:M.name??"",arguments:""})),M?.name&&(E.function.name=M.name),M?.arguments&&(E.function.arguments+=M.arguments,ai(o(this,Y,"f"),E)&&(E.function.parsed_arguments=Cs(E.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new G(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function mi(n,e){const{id:t,choices:s,created:r,model:i,system_fingerprint:a,...l}=n,d={...l,id:t,choices:s.map(({message:f,finish_reason:m,index:h,logprobs:g,...u})=>{if(!m)throw new y(`missing finish_reason for choice ${h}`);const{content:A=null,function_call:b,tool_calls:I,...v}=f,w=f.role;if(!w)throw new y(`missing role for choice ${h}`);if(b){const{arguments:T,name:C}=b;if(T==null)throw new y(`missing function_call.arguments for choice ${h}`);if(!C)throw new y(`missing function_call.name for choice ${h}`);return{...u,message:{content:A,function_call:{arguments:T,name:C},role:w,refusal:f.refusal??null},finish_reason:m,index:h,logprobs:g}}return I?{...u,index:h,finish_reason:m,logprobs:g,message:{...v,role:w,content:A,refusal:f.refusal??null,tool_calls:I.map((T,C)=>{const{function:X,type:W,id:R,...F}=T,{arguments:M,name:k,...E}=X||{};if(R==null)throw new y(`missing choices[${h}].tool_calls[${C}].id
11
+ ${De(n)}`);if(W==null)throw new y(`missing choices[${h}].tool_calls[${C}].type
12
+ ${De(n)}`);if(k==null)throw new y(`missing choices[${h}].tool_calls[${C}].function.name
13
+ ${De(n)}`);if(M==null)throw new y(`missing choices[${h}].tool_calls[${C}].function.arguments
14
+ ${De(n)}`);return{...F,id:R,type:W,function:{...E,name:k,arguments:M}}})}}:{...u,message:{...v,content:A,role:w,refusal:f.refusal??null},finish_reason:m,index:h,logprobs:g}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ni(d,e)}function De(n){return JSON.stringify(n)}class nt extends Oe{static fromReadableStream(e){const t=new nt(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const r=new nt(t),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}}let Kt=class extends _{constructor(){super(...arguments),this.messages=new dn(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(c`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(c`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",$,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return oi(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>Ht(s,e))}runTools(e,t){return e.stream?nt.runTools(this._client,e,t):Xt.runTools(this._client,e,t)}stream(e,t){return Oe.createChatCompletion(this._client,e,t)}};Kt.Messages=dn;class Vt extends _{constructor(){super(...arguments),this.completions=new Kt(this._client)}}Vt.Completions=Kt;const Tn=Symbol("brand.privateNullableHeaders");function*_i(n){if(!n)return;if(Tn in n){const{values:s,nulls:r}=n;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():hs(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let s of t){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=hs(s[1])?s[1]:[s[1]];let a=!1;for(const l of i)l!==void 0&&(e&&!a&&(a=!0,yield[r,null]),yield[r,l])}}const p=n=>{const e=new Headers,t=new Set;for(const s of n){const r=new Set;for(const[i,a]of _i(s)){const l=i.toLowerCase();r.has(l)||(e.delete(i),r.add(l)),a===null?(e.delete(i),t.add(l)):(e.append(i,a),t.delete(l))}}return{[Tn]:!0,values:e,nulls:t}};class Mn extends _{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Nn extends _{create(e,t){return this._client.post("/audio/transcriptions",fe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Fn extends _{create(e,t){return this._client.post("/audio/translations",fe({body:e,...t,__metadata:{model:e.model}},this._client))}}class Me extends _{constructor(){super(...arguments),this.transcriptions=new Nn(this._client),this.translations=new Fn(this._client),this.speech=new Mn(this._client)}}Me.Transcriptions=Nn;Me.Translations=Fn;Me.Speech=Mn;class Ln extends _{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",$,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}}class Bn extends _{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(c`/assistants/${e}`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",$,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Dn=class extends _{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class Wn extends _{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let ct=class extends _{constructor(){super(...arguments),this.sessions=new Dn(this._client),this.transcriptionSessions=new Wn(this._client)}};ct.Sessions=Dn;ct.TranscriptionSessions=Wn;class Un extends _{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let jn=class extends _{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",ke,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,ke,{query:t,...s,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class ut extends _{constructor(){super(...arguments),this.sessions=new Un(this._client),this.threads=new jn(this._client)}}ut.Sessions=Un;ut.Threads=jn;class qn extends _{create(e,t,s){return this._client.post(c`/threads/${e}/messages`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(c`/threads/${r}/messages/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(c`/threads/${r}/messages/${e}`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(c`/threads/${e}/messages`,$,{query:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:r}=t;return this._client.delete(c`/threads/${r}/messages/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Hn extends _{retrieve(e,t,s){const{thread_id:r,run_id:i,...a}=t;return this._client.get(c`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:r,...i}=t;return this._client.getAPIList(c`/threads/${r}/runs/${e}/steps`,$,{query:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const gi=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var wi={};const oe=n=>{if(typeof globalThis.process<"u")return wi?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var B,re,Ft,Q,Xe,V,ie,de,ne,rt,J,Ke,Ve,Re,ve,Ce,Rs,Is,ks,Es,Os,Ps,Ts;class Ie extends Jt{constructor(){super(...arguments),B.add(this),Ft.set(this,[]),Q.set(this,{}),Xe.set(this,{}),V.set(this,void 0),ie.set(this,void 0),de.set(this,void 0),ne.set(this,void 0),rt.set(this,void 0),J.set(this,void 0),Ke.set(this,void 0),Ve.set(this,void 0),Re.set(this,void 0)}[(Ft=new WeakMap,Q=new WeakMap,Xe=new WeakMap,V=new WeakMap,ie=new WeakMap,de=new WeakMap,ne=new WeakMap,rt=new WeakMap,J=new WeakMap,Ke=new WeakMap,Ve=new WeakMap,Re=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new re;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=G.fromReadableStream(e,this.controller);for await(const i of r)o(this,B,"m",ve).call(this,i);if(r.controller.signal?.aborted)throw new K;return this._addRun(o(this,B,"m",Ce).call(this))}toReadableStream(){return new G(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r){const i=new re;return i._run(()=>i._runToolAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(const d of l)o(this,B,"m",ve).call(this,d);if(l.controller.signal?.aborted)throw new K;return this._addRun(o(this,B,"m",Ce).call(this))}static createThreadAssistantStream(e,t,s){const r=new re;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const i=new re;return i._run(()=>i._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return o(this,Ke,"f")}currentRun(){return o(this,Ve,"f")}currentMessageSnapshot(){return o(this,V,"f")}currentRunStepSnapshot(){return o(this,Re,"f")}async finalRunSteps(){return await this.done(),Object.values(o(this,Q,"f"))}async finalMessages(){return await this.done(),Object.values(o(this,Xe,"f"))}async finalRun(){if(await this.done(),!o(this,ie,"f"))throw Error("Final run was not received.");return o(this,ie,"f")}async _createThreadAssistantStream(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},a=await e.createAndRun(i,{...s,signal:this.controller.signal});this._connected();for await(const l of a)o(this,B,"m",ve).call(this,l);if(a.controller.signal?.aborted)throw new K;return this._addRun(o(this,B,"m",Ce).call(this))}async _createAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(const d of l)o(this,B,"m",ve).call(this,d);if(l.controller.signal?.aborted)throw new K;return this._addRun(o(this,B,"m",Ce).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let i=e[s];if(i==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof i=="string"&&typeof r=="string")i+=r;else if(typeof i=="number"&&typeof r=="number")i+=r;else if(gt(i)&&gt(r))i=this.accumulateDelta(i,r);else if(Array.isArray(i)&&Array.isArray(r)){if(i.every(a=>typeof a=="string"||typeof a=="number")){i.push(...r);continue}for(const a of r){if(!gt(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const d=i[l];d==null?i.push(a):i[l]=this.accumulateDelta(d,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${i}`);e[s]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,r){return await this._createAssistantStream(t,e,s,r)}async _runToolAssistantStream(e,t,s,r){return await this._createToolAssistantStream(t,e,s,r)}}re=Ie,ve=function(e){if(!this.ended)switch(S(this,Ke,e),o(this,B,"m",ks).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":o(this,B,"m",Ts).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":o(this,B,"m",Is).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":o(this,B,"m",Rs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ce=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!o(this,ie,"f"))throw Error("Final run has not been received");return o(this,ie,"f")},Rs=function(e){const[t,s]=o(this,B,"m",Os).call(this,e,o(this,V,"f"));S(this,V,t),o(this,Xe,"f")[t.id]=t;for(const r of s){const i=t.content[r.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let i=r.text,a=t.content[r.index];if(a&&a.type=="text")this._emit("textDelta",i,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=o(this,de,"f")){if(o(this,ne,"f"))switch(o(this,ne,"f").type){case"text":this._emit("textDone",o(this,ne,"f").text,o(this,V,"f"));break;case"image_file":this._emit("imageFileDone",o(this,ne,"f").image_file,o(this,V,"f"));break}S(this,de,r.index)}S(this,ne,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(o(this,de,"f")!==void 0){const r=e.data.content[o(this,de,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,o(this,V,"f"));break;case"text":this._emit("textDone",r.text,o(this,V,"f"));break}}o(this,V,"f")&&this._emit("messageDone",e.data),S(this,V,void 0)}},Is=function(e){const t=o(this,B,"m",Es).call(this,e);switch(S(this,Re,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==o(this,rt,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(o(this,J,"f")&&this._emit("toolCallDone",o(this,J,"f")),S(this,rt,i.index),S(this,J,t.step_details.tool_calls[i.index]),o(this,J,"f")&&this._emit("toolCallCreated",o(this,J,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":S(this,Re,void 0),e.data.step_details.type=="tool_calls"&&o(this,J,"f")&&(this._emit("toolCallDone",o(this,J,"f")),S(this,J,void 0)),this._emit("runStepDone",e.data,t);break}},ks=function(e){o(this,Ft,"f").push(e),this._emit("event",e)},Es=function(e){switch(e.event){case"thread.run.step.created":return o(this,Q,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=o(this,Q,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=re.accumulateDelta(t,s.delta);o(this,Q,"f")[e.data.id]=r}return o(this,Q,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":o(this,Q,"f")[e.data.id]=e.data;break}if(o(this,Q,"f")[e.data.id])return o(this,Q,"f")[e.data.id];throw new Error("No snapshot available")},Os=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const i of r.delta.content)if(i.index in t.content){let a=t.content[i.index];t.content[i.index]=o(this,B,"m",Ps).call(this,i,a)}else t.content[i.index]=i,s.push(i);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ps=function(e,t){return re.accumulateDelta(t,e)},Ts=function(e){switch(S(this,Ve,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":S(this,ie,e.data),o(this,J,"f")&&(this._emit("toolCallDone",o(this,J,"f")),S(this,J,void 0));break}};let zt=class extends _{constructor(){super(...arguments),this.steps=new Hn(this._client)}create(e,t,s){const{include:r,...i}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:r},body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(c`/threads/${r}/runs/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(c`/threads/${r}/runs/${e}`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(c`/threads/${e}/runs`,$,{query:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:r}=t;return this._client.post(c`/threads/${r}/runs/${e}/cancel`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,t,s){return Ie.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r=p([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(l=f)}}await Pe(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return Ie.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:r,...i}=t;return this._client.post(c`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,s){const r=await this.submitToolOutputs(e,t,s);return await this.poll(r.id,t,s)}submitToolOutputsStream(e,t,s){return Ie.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};zt.Steps=Hn;class ht extends _{constructor(){super(...arguments),this.runs=new zt(this._client),this.messages=new qn(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(c`/threads/${e}`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Ie.createThreadAssistantStream(e,this._client.beta.threads,t)}}ht.Runs=zt;ht.Messages=qn;class pe extends _{constructor(){super(...arguments),this.realtime=new ct(this._client),this.chatkit=new ut(this._client),this.assistants=new Bn(this._client),this.threads=new ht(this._client)}}pe.Realtime=ct;pe.ChatKit=ut;pe.Assistants=Bn;pe.Threads=ht;class Jn extends _{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}let Xn=class extends _{retrieve(e,t,s){const{container_id:r}=t;return this._client.get(c`/containers/${r}/files/${e}/content`,{...s,headers:p([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}},Qt=class extends _{constructor(){super(...arguments),this.content=new Xn(this._client)}create(e,t,s){return this._client.post(c`/containers/${e}/files`,Ee({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:r}=t;return this._client.get(c`/containers/${r}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(c`/containers/${e}/files`,$,{query:t,...s})}delete(e,t,s){const{container_id:r}=t;return this._client.delete(c`/containers/${r}/files/${e}`,{...s,headers:p([{Accept:"*/*"},s?.headers])})}};Qt.Content=Xn;class Gt extends _{constructor(){super(...arguments),this.files=new Qt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",$,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}}Gt.Files=Qt;class Kn extends _{create(e,t,s){const{include:r,...i}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:r},body:i,...s})}retrieve(e,t,s){const{conversation_id:r,...i}=t;return this._client.get(c`/conversations/${r}/items/${e}`,{query:i,...s})}list(e,t={},s){return this._client.getAPIList(c`/conversations/${e}/items`,ke,{query:t,...s})}delete(e,t,s){const{conversation_id:r}=t;return this._client.delete(c`/conversations/${r}/items/${e}`,s)}}class Yt extends _{constructor(){super(...arguments),this.items=new Kn(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,s){return this._client.post(c`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}}Yt.Items=Kn;class Vn extends _{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&L(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return s?i:(L(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{const d=l.embedding;l.embedding=gi(d)}),a)))}}class zn extends _{retrieve(e,t,s){const{eval_id:r,run_id:i}=t;return this._client.get(c`/evals/${r}/runs/${i}/output_items/${e}`,s)}list(e,t,s){const{eval_id:r,...i}=t;return this._client.getAPIList(c`/evals/${r}/runs/${e}/output_items`,$,{query:i,...s})}}class Zt extends _{constructor(){super(...arguments),this.outputItems=new zn(this._client)}create(e,t,s){return this._client.post(c`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:r}=t;return this._client.get(c`/evals/${r}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(c`/evals/${e}/runs`,$,{query:t,...s})}delete(e,t,s){const{eval_id:r}=t;return this._client.delete(c`/evals/${r}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:r}=t;return this._client.post(c`/evals/${r}/runs/${e}`,s)}}Zt.OutputItems=zn;class es extends _{constructor(){super(...arguments),this.runs=new Zt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,s){return this._client.post(c`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",$,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}}es.Runs=Zt;let Qn=class extends _{create(e,t){return this._client.post("/files",fe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",$,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),i=Date.now();let a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Pe(t),a=await this.retrieve(e),Date.now()-i>s)throw new Dt({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class Gn extends _{}let Yn=class extends _{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 ts extends _{constructor(){super(...arguments),this.graders=new Yn(this._client)}}ts.Graders=Yn;class Zn extends _{create(e,t,s){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,lt,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}list(e,t={},s){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ke,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(c`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let ss=class extends _{constructor(){super(...arguments),this.permissions=new Zn(this._client)}};ss.Permissions=Zn;class er extends _{list(e,t={},s){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,$,{query:t,...s})}}class ns extends _{constructor(){super(...arguments),this.checkpoints=new er(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",$,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,$,{query:t,...s})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}}ns.Checkpoints=er;class me extends _{constructor(){super(...arguments),this.methods=new Gn(this._client),this.jobs=new ns(this._client),this.checkpoints=new ss(this._client),this.alpha=new ts(this._client)}}me.Methods=Gn;me.Jobs=ns;me.Checkpoints=ss;me.Alpha=ts;class tr extends _{}class rs extends _{constructor(){super(...arguments),this.graderModels=new tr(this._client)}}rs.GraderModels=tr;class sr extends _{createVariation(e,t){return this._client.post("/images/variations",fe({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",fe({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 nr extends _{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",lt,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}}class rr extends _{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class ir extends _{accept(e,t,s){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...s,headers:p([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...s,headers:p([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...s,headers:p([{Accept:"*/*"},s?.headers])})}}class ar extends _{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class dt extends _{constructor(){super(...arguments),this.clientSecrets=new ar(this._client),this.calls=new ir(this._client)}}dt.ClientSecrets=ar;dt.Calls=ir;function yi(n,e){return!e||!Si(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(s=>({...s,parsed:null}))}:t)}:or(n,e)}function or(n,e){const t=n.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:vi(e,r)};if(r.type==="message"){const i=r.content.map(a=>a.type==="output_text"?{...a,parsed:bi(e,a.text)}:a);return{...r,content:i}}return r}),s=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Lt(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const i of r.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),s}function bi(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Si(n){return!!qt(n.text?.format)}function xi(n){return n?.$brand==="auto-parseable-tool"}function Ai(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function vi(n,e){const t=Ai(n.tools??[],e.name);return{...e,...e,parsed_arguments:xi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Lt(n){const e=[];for(const t of n.output)if(t.type==="message")for(const s of t.content)s.type==="output_text"&&e.push(s.text);n.output_text=e.join("")}var le,We,te,Ue,Ms,Ns,Fs,Ls;class is extends Jt{constructor(e){super(),le.add(this),We.set(this,void 0),te.set(this,void 0),Ue.set(this,void 0),S(this,We,e)}static createResponse(e,t,s){const r=new is(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,le,"m",Ms).call(this);let i,a=null;"response_id"in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const l of i)o(this,le,"m",Ns).call(this,l,a);if(i.controller.signal?.aborted)throw new K;return o(this,le,"m",Fs).call(this)}[(We=new WeakMap,te=new WeakMap,Ue=new WeakMap,le=new WeakSet,Ms=function(){this.ended||S(this,te,void 0)},Ns=function(t,s){if(this.ended)return;const r=(a,l)=>{(s==null||l.sequence_number>s)&&this._emit(a,l)},i=o(this,le,"m",Ls).call(this,t);switch(r("event",t),t.type){case"response.output_text.delta":{const a=i.output[t.output_index];if(!a)throw new y(`missing output at index ${t.output_index}`);if(a.type==="message"){const l=a.content[t.content_index];if(!l)throw new y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new y(`expected content to be 'output_text', got ${l.type}`);r("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const a=i.output[t.output_index];if(!a)throw new y(`missing output at index ${t.output_index}`);a.type==="function_call"&&r("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:r(t.type,t);break}},Fs=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");const t=o(this,te,"f");if(!t)throw new y("request ended without sending any events");S(this,te,void 0);const s=Ci(t,o(this,We,"f"));return S(this,Ue,s),s},Ls=function(t){let s=o(this,te,"f");if(!s){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=S(this,te,t.response),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{const r=s.output[t.output_index];if(!r)throw new y(`missing output at index ${t.output_index}`);const i=r.type,a=t.part;i==="message"&&a.type!=="reasoning_text"?r.content.push(a):i==="reasoning"&&a.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(a));break}case"response.output_text.delta":{const r=s.output[t.output_index];if(!r)throw new y(`missing output at index ${t.output_index}`);if(r.type==="message"){const i=r.content[t.content_index];if(!i)throw new y(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new y(`expected content to be 'output_text', got ${i.type}`);i.text+=t.delta}break}case"response.function_call_arguments.delta":{const r=s.output[t.output_index];if(!r)throw new y(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.reasoning_text.delta":{const r=s.output[t.output_index];if(!r)throw new y(`missing output at index ${t.output_index}`);if(r.type==="reasoning"){const i=r.content?.[t.content_index];if(!i)throw new y(`missing content at index ${t.content_index}`);if(i.type!=="reasoning_text")throw new y(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=t.delta}break}case"response.completed":{S(this,te,t.response);break}}return s},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=o(this,Ue,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}}function Ci(n,e){return yi(n,e)}class lr extends _{list(e,t={},s){return this._client.getAPIList(c`/responses/${e}/input_items`,$,{query:t,...s})}}class cr extends _{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ft extends _{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(s=>("object"in s&&s.object==="response"&&Lt(s),s))}retrieve(e,t={},s){return this._client.get(c`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Lt(r),r))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>or(s,e))}stream(e,t){return is.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}ft.InputItems=lr;ft.InputTokens=cr;let ur=class extends _{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};class hr extends _{retrieve(e,t,s){const{skill_id:r}=t;return this._client.get(c`/skills/${r}/versions/${e}/content`,{...s,headers:p([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}class as extends _{constructor(){super(...arguments),this.content=new hr(this._client)}create(e,t={},s){return this._client.post(c`/skills/${e}/versions`,Ee({body:t,...s},this._client))}retrieve(e,t,s){const{skill_id:r}=t;return this._client.get(c`/skills/${r}/versions/${e}`,s)}list(e,t={},s){return this._client.getAPIList(c`/skills/${e}/versions`,$,{query:t,...s})}delete(e,t,s){const{skill_id:r}=t;return this._client.delete(c`/skills/${r}/versions/${e}`,s)}}as.Content=hr;class pt extends _{constructor(){super(...arguments),this.content=new ur(this._client),this.versions=new as(this._client)}create(e={},t){return this._client.post("/skills",Ee({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,s){return this._client.post(c`/skills/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/skills",$,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}}pt.Content=ur;pt.Versions=as;class dr extends _{create(e,t,s){return this._client.post(c`/uploads/${e}/parts`,fe({body:t,...s},this._client))}}class os extends _{constructor(){super(...arguments),this.parts=new dr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(c`/uploads/${e}/complete`,{body:t,...s})}}os.Parts=dr;const $i=async n=>{const e=await Promise.allSettled(n),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t)console.error(r.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class fr extends _{create(e,t,s){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(c`/vector_stores/${r}/file_batches/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:r}=t;return this._client.post(c`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t);return await this.poll(e,r.id,s)}listFiles(e,t,s){const{vector_store_id:r,...i}=t;return this._client.getAPIList(c`/vector_stores/${r}/file_batches/${e}/files`,$,{query:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const r=p([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse();switch(i.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(l=f)}}await Pe(l);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=r?.maxConcurrency??5,a=Math.min(i,t.length),l=this._client,d=t.values(),f=[...s];async function m(g){for(let u of g){const A=await l.files.create({file:u,purpose:"assistants"},r);f.push(A.id)}}const h=Array(a).fill(d).map(m);return await $i(h),await this.createAndPoll(e,{file_ids:f})}}class pr extends _{create(e,t,s){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(c`/vector_stores/${r}/files/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:r,...i}=t;return this._client.post(c`/vector_stores/${r}/files/${e}`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(c`/vector_stores/${e}/files`,$,{query:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:r}=t;return this._client.delete(c`/vector_stores/${r}/files/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}async poll(e,t,s){const r=p([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse(),a=i.data;switch(a.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(l=f)}}await Pe(l);break;case"failed":case"completed":return a}}}async upload(e,t,s){const r=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,t,s){const r=await this.upload(e,t,s);return await this.poll(e,r.id,s)}content(e,t,s){const{vector_store_id:r}=t;return this._client.getAPIList(c`/vector_stores/${r}/files/${e}/content`,lt,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class mt extends _{constructor(){super(...arguments),this.files=new pr(this._client),this.fileBatches=new fr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(c`/vector_stores/${e}`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",$,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(c`/vector_stores/${e}/search`,lt,{body:t,method:"post",...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}mt.Files=pr;mt.FileBatches=fr;class mr extends _{create(e,t){return this._client.post("/videos",Ee({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",ke,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},s){return this._client.get(c`/videos/${e}/content`,{query:t,...s,headers:p([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,t,s){return this._client.post(c`/videos/${e}/remix`,Ee({body:t,...s},this._client))}}var he,_r,ze;class gr extends _{constructor(){super(...arguments),he.add(this)}async unwrap(e,t,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,s,r),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");o(this,he,"m",_r).call(this,s);const i=p([t]).values,a=o(this,he,"m",ze).call(this,i,"webhook-signature"),l=o(this,he,"m",ze).call(this,i,"webhook-timestamp"),d=o(this,he,"m",ze).call(this,i,"webhook-id"),f=parseInt(l,10);if(isNaN(f))throw new ge("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-f>r)throw new ge("Webhook timestamp is too old");if(f>m+r)throw new ge("Webhook timestamp is too new");const h=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),g=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),u=d?`${d}.${l}.${e}`:`${l}.${e}`,A=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const b of h)try{const I=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",A,I,new TextEncoder().encode(u)))return}catch{continue}throw new ge("The given webhook signature does not match the expected signature")}}he=new WeakSet,_r=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},ze=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s};var Bt,ls,Qe,wr;class x{constructor({baseURL:e=oe("OPENAI_BASE_URL"),apiKey:t=oe("OPENAI_API_KEY"),organization:s=oe("OPENAI_ORG_ID")??null,project:r=oe("OPENAI_PROJECT_ID")??null,webhookSecret:i=oe("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Bt.add(this),Qe.set(this,void 0),this.completions=new Jn(this),this.chat=new Vt(this),this.embeddings=new Vn(this),this.files=new Qn(this),this.images=new sr(this),this.audio=new Me(this),this.moderations=new rr(this),this.models=new nr(this),this.fineTuning=new me(this),this.graders=new rs(this),this.vectorStores=new mt(this),this.webhooks=new gr(this),this.beta=new pe(this),this.batches=new Ln(this),this.uploads=new os(this),this.responses=new ft(this),this.realtime=new dt(this),this.conversations=new Yt(this),this.evals=new es(this),this.containers=new Gt(this),this.skills=new pt(this),this.videos=new mr(this),t===void 0)throw new y("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const l={apiKey:t,organization:s,project:r,webhookSecret:i,...a,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&$r())throw new y(`It looks like you're running in a browser-like environment.
15
+
16
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
17
+ If you understand the risks and have appropriate mitigations in place,
18
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
19
+
20
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
21
+
22
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??ls.DEFAULT_TIMEOUT,this.logger=l.logger??console;const d="warn";this.logLevel=d,this.logLevel=Ss(l.logLevel,"ClientOptions.logLevel",this)??Ss(oe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??d,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Or(),S(this,Qe,Tr),this._options=l,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=s,this.project=r,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return p([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Wr(e)}getUserAgent(){return`${this.constructor.name}/JS ${ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${Bs()}`}makeStatusError(e,t,s,r){return D.generate(e,t,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof y?s:new y(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new y(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const r=!o(this,Bt,"m",wr).call(this)&&s||this.baseURL,i=Sr(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return xr(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}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,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new ot(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:a,url:l,timeout:d}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:l,options:r});const f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(L(this).debug(`[${f}] sending request`,se({retryOfRequestLogID:s,method:r.method,url:l,options:r,headers:a.headers})),r.signal?.aborted)throw new K;const g=new AbortController,u=await this.fetchWithTimeout(l,a,d,g).catch($t),A=Date.now();if(u instanceof globalThis.Error){const v=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new K;const w=Ct(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return L(this).info(`[${f}] connection ${w?"timed out":"failed"} - ${v}`),L(this).debug(`[${f}] connection ${w?"timed out":"failed"} (${v})`,se({retryOfRequestLogID:s,url:l,durationMs:A-h,message:u.message})),this.retryRequest(r,t,s??f);throw L(this).info(`[${f}] connection ${w?"timed out":"failed"} - error; no more retries left`),L(this).debug(`[${f}] connection ${w?"timed out":"failed"} (error; no more retries left)`,se({retryOfRequestLogID:s,url:l,durationMs:A-h,message:u.message})),w?new Dt:new it({cause:u})}const b=[...u.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,w])=>", "+v+": "+JSON.stringify(w)).join(""),I=`[${f}${m}${b}] ${a.method} ${l} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${A-h}ms`;if(!u.ok){const v=await this.shouldRetry(u);if(t&&v){const R=`retrying, ${t} attempts remaining`;return await Pr(u.body),L(this).info(`${I} - ${R}`),L(this).debug(`[${f}] response error (${R})`,se({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:A-h})),this.retryRequest(r,t,s??f,u.headers)}const w=v?"error; no more retries left":"error; not retryable";L(this).info(`${I} - ${w}`);const T=await u.text().catch(R=>$t(R).message),C=Cr(T),X=C?void 0:T;throw L(this).debug(`[${f}] response error (${w})`,se({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:X,durationMs:Date.now()-h})),this.makeStatusError(u.status,C,X,u.headers)}return L(this).info(I),L(this).debug(`[${f}] response start`,se({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:A-h})),{response:u,options:r,controller:g,requestLogID:f,retryOfRequestLogID:s,startTime:h}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(r=>({method:"get",path:e,...r})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new zr(this,s,e)}async fetchWithTimeout(e,t,s,r){const{signal:i,method:a,...l}=t||{},d=this._makeAbort(r);i&&i.addEventListener("abort",d,{once:!0});const f=setTimeout(d,s),m=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,h={signal:r.signal,...m?{duplex:"half"}:{},method:"GET",...l};a&&(h.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(f)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,r){let i;const a=r?.get("retry-after-ms");if(a){const d=parseFloat(a);Number.isNaN(d)||(i=d)}const l=r?.get("retry-after");if(l&&!i){const d=parseFloat(l);Number.isNaN(d)?i=Date.parse(l)-Date.now():i=d*1e3}if(i===void 0){const d=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,d)}return await Pe(i),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:l}=s,d=this.buildURL(i,a,l);"timeout"in s&&vr("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:f,body:m}=this.buildBody({options:s}),h=await this.buildHeaders({options:e,method:r,bodyHeaders:f,retryCount:t});return{req:{method:r,headers:h,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...s.fetchOptions??{}},url:d,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=p([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Er(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=p([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Gs(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:o(this,Qe,"f").call(this,{body:e,headers:s})}}ls=x,Qe=new WeakMap,Bt=new WeakSet,wr=function(){return this.baseURL!=="https://api.openai.com/v1"};x.OpenAI=ls;x.DEFAULT_TIMEOUT=6e5;x.OpenAIError=y;x.APIError=D;x.APIConnectionError=it;x.APIConnectionTimeoutError=Dt;x.APIUserAbortError=K;x.NotFoundError=js;x.ConflictError=qs;x.RateLimitError=Js;x.BadRequestError=Ds;x.AuthenticationError=Ws;x.InternalServerError=Xs;x.PermissionDeniedError=Us;x.UnprocessableEntityError=Hs;x.InvalidWebhookSignatureError=ge;x.toFile=ei;x.Completions=Jn;x.Chat=Vt;x.Embeddings=Vn;x.Files=Qn;x.Images=sr;x.Audio=Me;x.Moderations=rr;x.Models=nr;x.FineTuning=me;x.Graders=rs;x.VectorStores=mt;x.Webhooks=gr;x.Beta=pe;x.Batches=Ln;x.Uploads=os;x.Responses=ft;x.Realtime=dt;x.Conversations=Yt;x.Evals=es;x.Containers=Gt;x.Skills=pt;x.Videos=mr;export{x as O,y as a,p as b,gt as i,oe as r};