@hintergrund/ui 0.3.11 → 0.3.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -55
- package/dist/BuilderAgentPane-CdXWwCOp.js +1 -0
- package/dist/IntegrationHealth-DlJvUzAy.js +1 -0
- package/dist/Mail-CO8ofiRH.js +1 -0
- package/dist/admin.js +2 -2
- package/dist/anthropic-messages-DcGbufuU.js +2 -0
- package/dist/builder.js +1 -1
- package/dist/config.types-D99vLLC0.js +1 -0
- package/dist/github-copilot-headers-EfqOaQ0F.js +1 -0
- package/dist/global-CGDFyqFU.js +2 -0
- package/dist/google-generative-ai-Ca9LVaIL.js +1 -0
- package/dist/invoice-pdf-BT1piHr5.js +5 -0
- package/dist/login.js +1 -1
- package/dist/mail.js +1 -1
- package/dist/node.browser-CEGF1Tgu.js +1 -0
- package/dist/node.browser-DVhXohSU.js +1 -0
- package/dist/openai-completions-8NGnMBOB.js +1 -0
- package/dist/openai-decisions-87kd_6iH.js +1 -0
- package/dist/openai-prompt-cache-C4mUbgCW.js +1 -0
- package/dist/openai-responses-BB76jCpT.js +1 -0
- package/dist/provider-retry-DNH2SSUZ.js +1 -0
- package/dist/rolldown-runtime-9urLBz53.js +1 -0
- package/dist/setup.js +1 -1
- package/dist/transform-messages-B-q6gABN.js +1 -0
- package/package.json +5 -4
- package/dist/BuilderAgentPane-Cf2EQd0U.js +0 -1
- package/dist/IntegrationHealth-CBFYmR_K.js +0 -1
- package/dist/anthropic-messages-CXPLHUpk.js +0 -1
- package/dist/assets/index-DI9TbuA9.js +0 -34669
- package/dist/config.types-CElC76m0.js +0 -1
- package/dist/deferred-tools-8QtAASke.js +0 -1
- package/dist/github-copilot-headers-n6Dqf6oj.js +0 -1
- package/dist/global-BmWXMWNY.js +0 -2
- package/dist/google-generative-ai-CNHCOvQN.js +0 -1
- package/dist/legacy-DcJfom53.js +0 -1
- package/dist/openai-completions-CSZJSCfj.js +0 -1
- package/dist/openai-prompt-cache-Mi5dPc0-.js +0 -1
- package/dist/openai-responses-BU24JgAs.js +0 -1
- package/dist/transform-messages-C1f-L9_8.js +0 -1
package/dist/legacy-DcJfom53.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(o){return Promise.resolve().then(o)}});import{lr as o}from"./global-BmWXMWNY.js";o();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{a as e,n as t,r as n,t as o}from"./github-copilot-headers-n6Dqf6oj.js";import{h as s,m as r,p as i}from"./BuilderAgentPane-Cf2EQd0U.js";import{c as a,d as l,f as p,h as c,i as u,l as g,m as f,n as d,o as m,p as h,s as y,t as k,u as _}from"./transform-messages-C1f-L9_8.js";import{n as R,t as v}from"./error-body-B13t5xBI.js";import{n as x,r as T,t as A}from"./openai-prompt-cache-Mi5dPc0-.js";function w(e,t){if(!e)return!1;const n=t.toLowerCase();for(const[o,s]of Object.entries(e))if(o.toLowerCase()===n&&null!==s&&s.trim().length>0)return!0;return!1}function M(e,t,n){if(t)return t;if(w(n,"authorization")||w(n,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function E(e,t){if(!e)return[];const n=new Map(e.map(e=>[e.name,e]));return Array.from(t).map(e=>n.get(e)).filter(e=>void 0!==e)}function I(e){return"text"===e.type}function b(e){return"thinking"===e.type}function S(e){return"toolCall"===e.type}function F(e){return"image"===e.type}function C(e){if("object"!=typeof e||null===e)return!1;const t=e;return"reasoning.encrypted"===t.type&&"string"==typeof t.id&&t.id.length>0&&"string"==typeof t.data&&t.data.length>0}function L(e,t){return e||("long"===n("PI_CACHE_RETENTION",t)?"long":"short")}var q=(n,r,i)=>{const l=new s;return(async()=>{const s={role:"assistant",content:[],api:n.api,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const p=M(n.provider,i?.apiKey,i?.headers),u=D(n),g=a(r.tools,u.supportsOpenAIGrammarTools),h=L(i?.cacheRetention,i?.env),k="none"===h?void 0:i?.sessionId,_=function(e,n,s,r,i,a,l=D(e)){const p={...e.headers};if("github-copilot"===e.provider){const e=t(n.messages),s=o({messages:n.messages,hasImages:e});Object.assign(p,s)}return a&&l.sendSessionAffinityHeaders&&("openrouter"===l.sessionAffinityFormat?p["x-session-id"]=a:("openai"===l.sessionAffinityFormat&&(p.session_id=a),p["x-client-request-id"]=a,p["x-session-affinity"]=a)),r&&Object.assign(p,r),new T({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:p})}(n,r,p,i?.headers,i?.fetch,k,u);let R=function(e,t,n,o=D(e),s=L(n?.cacheRetention,n?.env),r=a(t.tools,o.supportsOpenAIGrammarTools)){const i=G(e,t,o,{grammarToolInputProperties:r}),l=function(e,t){if("anthropic"!==e.cacheControlFormat||"none"===t)return;const n="long"===t&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...n?{ttl:n}:{}}}(o,s),p={model:e.id,messages:i,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&"none"!==s||"long"===s&&o.supportsLongCacheRetention?A(n?.sessionId):void 0,prompt_cache_retention:"long"===s&&o.supportsLongCacheRetention?"24h":void 0};!1!==o.supportsUsageInStreaming&&(p.stream_options={include_usage:!0}),o.supportsStore&&(p.store=!1),n?.maxTokens&&("max_tokens"===o.maxTokensField?p.max_tokens=n.maxTokens:p.max_completion_tokens=n.maxTokens),void 0!==n?.temperature&&(p.temperature=n.temperature);const c="kimi"===o.deferredToolsMode?function(e){const t=/* @__PURE__ */new Set;for(const n of e)if("toolResult"===n.role)for(const e of n.addedToolNames??[])t.add(e);return t}(t.messages):/* @__PURE__ */new Set,u=t.tools?.filter(e=>!c.has(e.name));if(u&&u.length>0?(p.tools=$(u,o),o.zaiToolStream&&(p.tool_stream=!0)):function(e){for(const t of e){if("toolResult"===t.role)return!0;if("assistant"===t.role&&t.content.some(e=>"toolCall"===e.type))return!0}return!1}(t.messages)&&(p.tools=[]),l&&function(e,t,n){(function(e,t){for(const n of e)if("system"===n.role||"developer"===n.role)return void N(n,t)})(e,n),function(e,t){if(!e||0===e.length)return;e[e.length-1].cache_control=t}(t,n),function(e,t){for(let n=e.length-1;n>=0;n--){const o=e[n];if(("user"===o.role||"assistant"===o.role||"tool"===o.role)&&P(o,t))return}}(e,n)}(i,p.tools,l),n?.toolChoice&&(p.tool_choice=n.toolChoice),"zai"===o.thinkingFormat&&e.reasoning){const t=p;if(t.thinking=n?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},n?.reasoningEffort&&o.supportsReasoningEffort){const o=e.thinkingLevelMap?.[n.reasoningEffort],s=void 0===o?n.reasoningEffort:o;"string"==typeof s&&(t.reasoning_effort=s)}}else if("qwen"===o.thinkingFormat&&e.reasoning){if(p.enable_thinking=!!n?.reasoningEffort,n?.reasoningEffort&&o.supportsReasoningEffort){const t=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;"string"==typeof t&&(p.reasoning_effort=t)}}else if("qwen-chat-template"===o.thinkingFormat&&e.reasoning)p.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if("chat-template"===o.thinkingFormat&&e.reasoning){const t=j(e,n,o.chatTemplateKwargs);t&&(p.chat_template_kwargs=t)}else if("baseten"===o.thinkingFormat&&e.reasoning){const t=p,s=j(e,n,o.chatTemplateArgs);if(s&&(t.chat_template_args=s),o.supportsReasoningEffort){const o=n?.reasoningEffort,s=o?e.thinkingLevelMap?.[o]:e.thinkingLevelMap?.off,r=void 0===s?o:s;"string"==typeof r&&(t.reasoning_effort=r)}}else if("deepseek"===o.thinkingFormat&&e.reasoning)n?.reasoningEffort?p.thinking={type:"enabled"}:null!==e.thinkingLevelMap?.off&&(p.thinking={type:"disabled"}),n?.reasoningEffort&&o.supportsReasoningEffort&&(p.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if("openrouter"===o.thinkingFormat&&e.reasoning){const t=p;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:null!==e.thinkingLevelMap?.off&&(t.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if("ant-ling"===o.thinkingFormat&&e.reasoning&&n?.reasoningEffort){const t=e.thinkingLevelMap?.[n.reasoningEffort];"string"==typeof t&&(p.reasoning={effort:t})}else if("together"===o.thinkingFormat&&e.reasoning){const t=p;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&o.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if("string-thinking"===o.thinkingFormat&&e.reasoning){const t=p;n?.reasoningEffort?t.thinking=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:null!==e.thinkingLevelMap?.off&&(t.thinking=e.thinkingLevelMap?.off??"none")}else if(n?.reasoningEffort&&e.reasoning&&o.supportsReasoningEffort)p.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&o.supportsReasoningEffort){const t=e.thinkingLevelMap?.off;"string"==typeof t&&(p.reasoning_effort=t)}if(o.supportsThinkingTokenBudget&&n?.reasoningEffort&&e.reasoning){const t=m(n.reasoningEffort),o={minimal:1024,low:2048,medium:8192,high:16384,...n.thinkingBudgets},s=p.max_tokens??p.max_completion_tokens??e.maxTokens,r=Math.min(o[t],Math.max(0,s-d));r>0&&(p.thinking_token_budget=r)}if(e.compat?.openRouterRouting&&(p.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){const t=e.compat.vercelGatewayRouting;if(t.only||t.order){const e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),p.providerOptions={gateway:e}}}return n?.samplingParams&&Object.assign(p,n.samplingParams),p}(n,r,i,u,h,g);const v=await(i?.onPayload?.(R,n));void 0!==v&&(R=v);const x={...i?.signal?{signal:i.signal}:{},...void 0!==i?.timeoutMs?{timeout:i.timeoutMs}:{},maxRetries:0},{data:w,response:E}=await f(()=>_.chat.completions.create(R,x).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await(i?.onResponse?.({status:E.status,headers:c(E.headers)},n)),l.push({type:"start",partial:s});let I=null,b=null,S=!1;const F=/* @__PURE__ */new Map,q=/* @__PURE__ */new Map,O=/* @__PURE__ */new Map,z=s.content,B=e=>z.indexOf(e),W=e=>{const t=e.customInput?.property;if(void 0===t)return"";const n=e.arguments[t];return"string"==typeof n?n:""},H=(e,t,n)=>{const o=e.customInput;if(!o)return;const s=y(o.jsonBuffer,o.property,t,n);return e.arguments={[o.property]:t},s},J=t=>{const n=B(t);if(-1!==n)if("text"===t.type)l.push({type:"text_end",contentIndex:n,content:t.text,partial:s});else if("thinking"===t.type)l.push({type:"thinking_end",contentIndex:n,content:t.thinking,partial:s});else if("toolCall"===t.type){if(t.customInput){const e=H(t,W(t),!0);void 0!==e&&l.push({type:"toolcall_delta",contentIndex:n,delta:e,partial:s})}else t.arguments=e(t.partialArgs);delete t.partialArgs,delete t.customInput,delete t.streamIndex,l.push({type:"toolcall_end",contentIndex:n,toolCall:t,partial:s})}},Z=()=>(I||(I={type:"text",text:""},z.push(I),l.push({type:"text_start",contentIndex:B(I),partial:s})),I),Q=e=>(b||(b={type:"thinking",thinking:"",thinkingSignature:e},z.push(b),l.push({type:"thinking_start",contentIndex:B(b),partial:s})),b),V=e=>{if(!e.id)return;const t=O.get(e.id);t&&(e.thoughtSignature=t,O.delete(e.id))},X=e=>{const t="number"==typeof e.index?e.index:void 0,n=e.function?.name??e.custom?.name??"";let o=void 0!==t?F.get(t):void 0;if(!o&&e.id&&(o=q.get(e.id)),!o){const r=e.custom&&!e.function?g.get(n)??"input":void 0,i=void 0!==r;o={type:"toolCall",id:e.id||"",name:n,arguments:i?{[r]:""}:{},partialArgs:i?void 0:"",customInput:i?{property:r,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:t},void 0!==t&&F.set(t,o),e.id&&q.set(e.id,o),z.push(o),l.push({type:"toolcall_start",contentIndex:B(o),partial:s})}if(void 0!==t&&void 0===o.streamIndex&&(o.streamIndex=t,F.set(t,o)),e.id&&q.set(e.id,o),!o.name&&n&&(o.name=n),e.custom&&!e.function&&!o.customInput){const e=g.get(o.name)??"input";o.arguments={[e]:""},o.customInput={property:e,jsonBuffer:{input:"",started:!1,closed:!1}},delete o.partialArgs}return V(o),o};for await(const t of w){if(!t||"object"!=typeof t)continue;s.responseId||=t.id,"string"==typeof t.model&&t.model.length>0&&t.model!==n.id&&(s.responseModel||=t.model),t.usage&&(s.usage=U(t.usage,n));const o=Array.isArray(t.choices)?t.choices[0]:void 0;if(o){if(!t.usage&&o.usage&&(s.usage=U(o.usage,n)),o.finish_reason){s.rawStopReason=o.finish_reason;const e=K(o.finish_reason);s.stopReason=e.stopReason,e.errorMessage&&(s.errorMessage=e.errorMessage),S=!0}if(o.delta){if(null!==o.delta.content&&void 0!==o.delta.content&&o.delta.content.length>0){const e=Z();e.text+=o.delta.content,l.push({type:"text_delta",contentIndex:B(e),delta:o.delta.content,partial:s})}const t=["reasoning_content","reasoning","reasoning_text"],r=o.delta;let i=null;for(const e of t){const t=r[e];if("string"==typeof t&&t.length>0){i=e;break}}if(i){const e=r[i];if("string"==typeof e&&e.length>0){const t=Q("opencode-go"===n.provider&&"reasoning"===i?"reasoning_content":i);t.thinking+=e,l.push({type:"thinking_delta",contentIndex:B(t),delta:e,partial:s})}}if(o?.delta?.tool_calls)for(const n of o.delta.tool_calls){const t=X(n);!t.id&&n.id&&(t.id=n.id,q.set(n.id,t));const o=n.function?.name??n.custom?.name;!t.name&&o&&(t.name=o);let r="";n.function?.arguments?(r=n.function.arguments,t.partialArgs=(t.partialArgs??"")+n.function.arguments,t.arguments=e(t.partialArgs)):n.custom?.input&&(r=H(t,W(t)+n.custom.input,!1)??""),l.push({type:"toolcall_delta",contentIndex:B(t),delta:r,partial:s})}const a=o.delta.reasoning_details;if(Array.isArray(a))for(const e of a)if(C(e)){const t=JSON.stringify(e),n=q.get(e.id);n?n.thoughtSignature=t:O.set(e.id,t)}}}}for(const e of z)J(e);if(i?.signal?.aborted)throw new Error("Request was aborted");if("aborted"===s.stopReason)throw new Error("Request was aborted");if(S||u.supportsFinishReason||(s.stopReason=s.content.some(e=>"toolCall"===e.type)?"toolUse":"stop"),"error"===s.stopReason)throw new Error(s.errorMessage||"Provider returned an error stop reason");if(u.supportsFinishReason&&!S||"pending"===s.stopReason)throw new Error("Stream ended without finish_reason");l.push({type:"done",reason:s.stopReason,message:s}),l.end()}catch(p){for(const t of s.content)delete t.index,delete t.partialArgs,delete t.customInput,delete t.streamIndex;s.stopReason=i?.signal?.aborted?"aborted":"error",s.errorMessage=v(R(p));const e=p?.error?.metadata?.raw;e&&!s.errorMessage.includes(String(e))&&(s.errorMessage+=`\n${e}`),l.push({type:"error",reason:s.stopReason,error:s}),l.end()}})(),l},O=(e,t,n)=>{M(e.provider,n?.apiKey,n?.headers);const o=u(e,t,n,n?.apiKey),s=n?.reasoning?r(e,n.reasoning):void 0,i="off"===s?void 0:s,a=n?.toolChoice;return q(e,t,{...o,reasoningEffort:i,toolChoice:a,thinkingBudgets:n?.thinkingBudgets})};function j(e,t,n){const o={};for(const[s,r]of Object.entries(n)){const n=z(e,t,r);void 0!==n&&(o[s]=n)}return Object.keys(o).length>0?o:void 0}function z(e,t,n){if("object"!=typeof n||null===n)return n;const o=t?.reasoningEffort;if(!o&&n.omitWhenOff)return;if("thinking.enabled"===n.$var)return!!o;const s=o?e.thinkingLevelMap?.[o]:e.thinkingLevelMap?.off;return void 0===s?o:"string"==typeof s?s:void 0}function N(e,t){return B(e,t)}function P(e,t){return("user"===e.role||"assistant"===e.role||"tool"===e.role)&&B(e,t)}function B(e,t){const n=e.content;if("string"==typeof n)return 0!==n.length&&(e.content=[{type:"text",text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let o=n.length-1;o>=0;o--){const e=n[o];if("text"===e?.type)return e.cache_control=t,!0}return!1}function G(e,t,n,o){const s=[],r=k(t.messages,e,t=>(t=>{if(t.includes("|")){const e=t.indexOf("|"),n=t.slice(0,e).replace(/[^a-zA-Z0-9_-]/g,"_"),o=t.slice(e+1).replace(/[^a-zA-Z0-9_-]/g,"_"),s=o.length>0?`${n}_${o}`:n;if(s.length<=40)return s;const r=x(t).slice(0,8);return`${n.slice(0,Math.max(1,40-r.length-1))}_${r}`}return"openai"===e.provider&&t.length>40?t.slice(0,40):t})(t));if(t.systemPrompt){const o=e.reasoning&&n.supportsDeveloperRole?"developer":"system";s.push({role:o,content:h(t.systemPrompt)})}let i=null;for(let a=0;a<r.length;a++){const l=r[a];if(n.requiresAssistantAfterToolResult&&"toolResult"===i&&"user"===l.role&&s.push({role:"assistant",content:"I have processed the tool results."}),"user"===l.role)if("string"==typeof l.content)s.push({role:"user",content:h(l.content)});else{const e=l.content.map(e=>"text"===e.type?{type:"text",text:h(e.text)}:{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(0===e.length)continue;s.push({role:"user",content:e})}else if("assistant"===l.role){const t={role:"assistant",content:n.requiresAssistantAfterToolResult?"":null},r=l.content.filter(I).filter(e=>e.text.trim().length>0).map(e=>({type:"text",text:h(e.text)})),i=r.map(e=>e.text).join(""),a=l.content.filter(b).filter(e=>e.thinking.trim().length>0);if(a.length>0)if(n.requiresThinkingAsText)t.content=[{type:"text",text:a.map(e=>h(e.thinking)).join("\n\n")},...r];else{i.length>0&&(t.content=i);let n=a[0].thinkingSignature;"opencode-go"===e.provider&&"reasoning"===n&&(n="reasoning_content"),n&&n.length>0&&(t[n]=a.map(e=>e.thinking).join("\n"))}else i.length>0&&(t.content=i);const p=l.content.filter(S);if(p.length>0){t.tool_calls=p.map(e=>{const t=o?.grammarToolInputProperties?.get(e.name);return void 0!==t?{id:e.id,type:"custom",custom:{name:e.name,input:h(g(e.name,e.arguments,t))}}:{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}});const e=p.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&void 0===t.reasoning_content&&(t.reasoning_content="");const c=t.content;if(!(null!=c&&c.length>0||t.tool_calls))continue;s.push(t)}else if("toolResult"===l.role){const o=[],l=/* @__PURE__ */new Set;let p=a;for(;p<r.length&&"toolResult"===r[p].role;p++){const t=r[p],i=t.content.filter(I).map(e=>e.text).join("\n"),a=t.content.some(e=>"image"===e.type),c=i.length>0?i:a?"(see attached image)":"(no tool output)",u={role:"tool",content:h(c),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(u.name=t.toolName),s.push(u),"kimi"===n.deferredToolsMode)for(const e of t.addedToolNames??[])l.add(e);if(a&&e.input.includes("image"))for(const e of t.content)F(e)&&o.push({type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}if(a=p-1,o.length>0?(n.requiresAssistantAfterToolResult&&s.push({role:"assistant",content:"I have processed the tool results."}),s.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...o]}),i="user"):i="toolResult",l.size>0){const e=E(t.tools,l);if(e.length>0){const t={role:"system",tools:$(e,n)};s.push(t)}}continue}i=l.role}return s}function $(e,t){return e.map(e=>{const n=l(e,t.supportsOpenAIGrammarTools);if(n)return{type:"custom",custom:{name:e.name,description:e.description,format:{type:"grammar",grammar:{syntax:n.format,definition:n.definition}}}};const o=p(e,!1!==t.supportsStrictMode);return{type:"function",function:{name:e.name,description:e.description,parameters:_(e,o),...!1!==t.supportsStrictMode&&{strict:o??!1}}}})}function U(e,t){const n=e.prompt_tokens||0,o=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,s=e.prompt_tokens_details?.cache_write_tokens||0,r=Math.max(0,n-o-s),a=e.completion_tokens||0,l={input:r,output:a,cacheRead:o,cacheWrite:s,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:r+a+o+s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return i(t,l),l}function K(e){if(null===e)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function D(e){const t=function(e){const t=e.provider,n=e.baseUrl,o="zai"===t||"zai-coding-cn"===t||n.includes("api.z.ai")||n.includes("open.bigmodel.cn"),s="together"===t||n.includes("api.together.ai")||n.includes("api.together.xyz"),r="moonshotai"===t||"moonshotai-cn"===t||n.includes("api.moonshot."),i="openrouter"===t||n.includes("openrouter.ai"),a="cloudflare-workers-ai"===t||n.includes("api.cloudflare.com"),l="cloudflare-ai-gateway"===t||n.includes("gateway.ai.cloudflare.com"),p="nvidia"===t||n.includes("integrate.api.nvidia.com"),c="ant-ling"===t||n.includes("api.ant-ling.com"),u="deepseek"===t||n.toLowerCase().includes("deepseek.com"),g=p||"cerebras"===t||n.includes("cerebras.ai")||"xai"===t||n.includes("api.x.ai")||s||n.includes("chutes.ai")||u||o||r||"opencode"===t||n.includes("opencode.ai")||a||l||c,f=n.includes("chutes.ai")||u||r||l||s||p||c||o,d="xai"===t||n.includes("api.x.ai");return{supportsStore:!g,supportsDeveloperRole:i&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/"))||!g&&!i,supportsReasoningEffort:!(d||o||r||s||l||p||c),supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:f?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:u,thinkingFormat:u?"deepseek":o?"zai":s?"together":c?"ant-ling":i?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,supportsStrictMode:!(r||s||l||p),supportsOpenAIGrammarTools:!1,cacheControlFormat:"openrouter"===t&&e.id.startsWith("anthropic/")?"anthropic":void 0,sendSessionAffinityHeaders:!1,deferredToolsMode:void 0,sessionAffinityFormat:i?"openrouter":"openai",supportsLongCacheRetention:!(s||a||l||p||c)}}(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??t.supportsFinishReason,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??t.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??t.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??t.supportsThinkingTokenBudget,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??t.supportsOpenAIGrammarTools,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,deferredToolsMode:e.compat.deferredToolsMode??t.deferredToolsMode,sessionAffinityFormat:e.compat.sessionAffinityFormat??t.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{G as convertMessages,q as stream,O as streamSimple};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t,s,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,s):n?n.value=s:t.set(e,s),s}function t(e,t,s,r){if("a"===s&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?r:"a"===s?r.call(e):r?r.value:t.get(e)}void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});var s=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return s=e.randomUUID.bind(e),e.randomUUID();const t=/* @__PURE__ */new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^r()&15>>+e/4).toString(16))};function r(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var n=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)},i=class extends Error{},a=class e extends i{constructor(t,s,r,n){super(`${e.makeMessage(t,s,r)}`),this.status=t,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=s;const i=s;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,s){const r=t?.message?"string"==typeof t.message?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(t,s,r,i){if(!t||!i)return new c({message:r,cause:n(s)});const a=s?.error;return 400===t?new u(t,a,r,i):401===t?new h(t,a,r,i):403===t?new d(t,a,r,i):404===t?new p(t,a,r,i):409===t?new _(t,a,r,i):422===t?new f(t,a,r,i):429===t?new y(t,a,r,i):t>=500?new m(t,a,r,i):new e(t,a,r,i)}},o=class extends a{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},c=class extends a{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},l=class extends c{constructor({message:e}={}){super({message:e??"Request timed out."})}},u=class extends a{},h=class extends a{},d=class extends a{},p=class extends a{},_=class extends a{},f=class extends a{},y=class extends a{},m=class extends a{},g=class extends i{constructor(){super("Could not parse response content as the length limit was reached")}},b=class extends i{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},w=class extends Error{constructor(e){super(e)}},A=class extends a{constructor(e,t,s){let r,n="OAuth2 authentication error";if(t&&"object"==typeof t){const e=t;r=e.error;const s=e.error_description;s&&"string"==typeof s?n=s:r&&(n=r)}super(e,t,n,s),this.error_code=r}},v=class extends i{constructor(e,t,s){super(e),this.provider=t,this.cause=s}},I=/^[a-z][a-z0-9+.-]*:/i,$=e=>($=Array.isArray)(e),x=$;function P(e){return"object"!=typeof e?{}:e??{}}function S(e){if(!e)return!0;for(const t in e)return!1;return!0}function k(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}var O,R=e=>new Promise(t=>setTimeout(t,e)),j="6.40.0",E=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":T(Deno.build.os),"X-Stainless-Arch":K(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":T(globalThis.process.platform??"unknown"),"X-Stainless-Arch":K(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;for(const{key:e,pattern:t}of[{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/}]){const s=t.exec(navigator.userAgent);if(s)return{browser:e,version:`${s[1]||0}.${s[2]||0}.${s[3]||0}`}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},K=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",T=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";function C(){if("undefined"!=typeof fetch)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 q(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function L(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return q({start(){},async pull(e){const{done:s,value:r}=await t.next();s?e.close():e.enqueue(r)},async cancel(){await(t.return?.())}})}function z(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function M(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void(await(e[Symbol.asyncIterator]().return?.()));const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}var D=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),N="RFC3986",B=e=>String(e),W={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:B},U=(e,t)=>(U=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),F=/* @__PURE__ */(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),H=1024;function X(e,t){if($(e)){const s=[];for(let r=0;r<e.length;r+=1)s.push(t(e[r]));return s}return t(e)}var J,V,G,Q,Y,Z={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},ee=function(e,t){Array.prototype.push.apply(e,$(t)?t:[t])},te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,r,n)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===s)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let a="";for(let o=0;o<i.length;o+=H){const e=i.length>=H?i.slice(o,o+H):i,t=[];for(let s=0;s<e.length;++s){let r=e.charCodeAt(s);45===r||46===r||95===r||126===r||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||"RFC1738"===n&&(40===r||41===r)?t[t.length]=e.charAt(s):r<128?t[t.length]=F[r]:r<2048?t[t.length]=F[192|r>>6]+F[128|63&r]:r<55296||r>=57344?t[t.length]=F[224|r>>12]+F[128|r>>6&63]+F[128|63&r]:(s+=1,r=65536+((1023&r)<<10|1023&e.charCodeAt(s)),t[t.length]=F[240|r>>18]+F[128|r>>12&63]+F[128|r>>6&63]+F[128|63&r])}a+=t.join("")}return a},encodeValuesOnly:!1,format:N,formatter:B,indices:!1,serializeDate:e=>(J??(J=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},se={};function re(e,t,s,r,n,i,a,o,c,l,u,h,d,p,_,f,y,m){let g=e,b=m,w=0,A=!1;for(;void 0!==(b=b.get(se))&&!A;){const t=b.get(e);if(w+=1,void 0!==t){if(t===w)throw new RangeError("Cyclic object value");A=!0}void 0===b.get(se)&&(w=0)}if("function"==typeof l?g=l(t,g):g instanceof Date?g=d?.(g):"comma"===s&&$(g)&&(g=X(g,function(e){return e instanceof Date?d?.(e):e})),null===g){if(i)return c&&!f?c(t,te.encoder,y,"key",p):t;g=""}if("string"==typeof(v=g)||"number"==typeof v||"boolean"==typeof v||"symbol"==typeof v||"bigint"==typeof v||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(g)){if(c){const e=f?t:c(t,te.encoder,y,"key",p);return[_?.(e)+"="+_?.(c(g,te.encoder,y,"value",p))]}return[_?.(t)+"="+_?.(String(g))]}var v;const I=[];if(void 0===g)return I;let x;if("comma"===s&&$(g))f&&c&&(g=X(g,c)),x=[{value:g.length>0?g.join(",")||null:void 0}];else if($(l))x=l;else{const e=Object.keys(g);x=u?e.sort(u):e}const P=o?String(t).replace(/\./g,"%2E"):String(t),S=r&&$(g)&&1===g.length?P+"[]":P;if(n&&$(g)&&0===g.length)return S+"[]";for(let k=0;k<x.length;++k){const t=x[k],b="object"==typeof t&&void 0!==t.value?t.value:g[t];if(a&&null===b)continue;const A=h&&o?t.replace(/\./g,"%2E"):t,v=$(g)?"function"==typeof s?s(S,A):S:S+(h?"."+A:"["+A+"]");m.set(e,w);const P=/* @__PURE__ */new WeakMap;P.set(se,m),ee(I,re(b,v,s,r,n,i,a,o,"comma"===s&&f&&$(g)?null:c,l,u,h,d,p,_,f,y,P))}return I}function ne(e){let t;return(V??(t=new globalThis.TextEncoder,V=t.encode.bind(t)))(e)}function ie(e){let t;return(G??(t=new globalThis.TextDecoder,G=t.decode.bind(t)))(e)}var ae=class{constructor(){Q.set(this,void 0),Y.set(this,void 0),e(this,Q,/* @__PURE__ */new Uint8Array,"f"),e(this,Y,null,"f")}decode(s){if(null==s)return[];const r=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?ne(s):s;e(this,Q,function(e){let t=0;for(const n of e)t+=n.length;const s=new Uint8Array(t);let r=0;for(const n of e)s.set(n,r),r+=n.length;return s}([t(this,Q,"f"),r]),"f");const n=[];let i;for(;null!=(i=oe(t(this,Q,"f"),t(this,Y,"f")));){if(i.carriage&&null==t(this,Y,"f")){e(this,Y,i.index,"f");continue}if(null!=t(this,Y,"f")&&(i.index!==t(this,Y,"f")+1||i.carriage)){n.push(ie(t(this,Q,"f").subarray(0,t(this,Y,"f")-1))),e(this,Q,t(this,Q,"f").subarray(t(this,Y,"f")),"f"),e(this,Y,null,"f");continue}const s=null!==t(this,Y,"f")?i.preceding-1:i.preceding,r=ie(t(this,Q,"f").subarray(0,s));n.push(r),e(this,Q,t(this,Q,"f").subarray(i.index),"f"),e(this,Y,null,"f")}return n}flush(){return t(this,Q,"f").length?this.decode("\n"):[]}};function oe(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}function ce(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}Q=/* @__PURE__ */new WeakMap,Y=/* @__PURE__ */new WeakMap,ae.NEWLINE_CHARS=/* @__PURE__ */new Set(["\n","\r"]),ae.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var le={off:0,error:200,warn:300,info:400,debug:500},ue=(e,t,s)=>{var r,n;if(e)return r=le,n=e,Object.prototype.hasOwnProperty.call(r,n)?e:void fe(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(le))}`)};function he(){}function de(e,t,s){return!t||le[e]>le[s]?he:t[e].bind(t)}var pe={error:he,warn:he,info:he,debug:he},_e=/* @__PURE__ */new WeakMap;function fe(e){const t=e.logger,s=e.logLevel??"off";if(!t)return pe;const r=_e.get(t);if(r&&r[0]===s)return r[1];const n={error:de("error",t,s),warn:de("warn",t,s),info:de("info",t,s),debug:de("debug",t,s)};return _e.set(t,[s,n]),n}var ye,me,ge=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"api-key"===e.toLowerCase()||"x-api-key"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),be=class s{constructor(t,s,r){this.iterator=t,ye.set(this,void 0),this.controller=s,e(this,ye,r,"f")}static fromSSEResponse(e,t,n,o){let c=!1;const l=n?fe(n):console;return new s(async function*(){if(c)throw new i("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let s=!1;try{for await(const r of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new i("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new i("Attempted to iterate over a response with no body")}const s=new we,r=new ae,n=z(e.body);for await(const i of async function*(e){let t=/* @__PURE__ */new Uint8Array;for await(const s of e){if(null==s)continue;const e=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?ne(s):s;let r,n=new Uint8Array(t.length+e.length);for(n.set(t),n.set(e,t.length),t=n;-1!==(r=ce(t));)yield t.slice(0,r),t=t.slice(r)}t.length>0&&(yield t)}(n))for(const e of r.decode(i)){const t=s.decode(e);t&&(yield t)}for(const i of r.flush()){const e=s.decode(i);e&&(yield e)}}(e,t))if(!s)if(r.data.startsWith("[DONE]"))s=!0;else if(null!==r.event&&r.event.startsWith("thread.")){let e;try{e=JSON.parse(r.data)}catch(n){throw n}if("error"==r.event)throw new a(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}else{let t;try{t=JSON.parse(r.data)}catch(n){throw l.error("Could not parse message into JSON:",r.data),l.error("From chunk:",r.raw),n}if(t&&t.error)throw new a(void 0,t.error,void 0,e.headers);yield o?{event:r.event,data:t}:t}s=!0}catch(n){if(r(n))return;throw n}finally{s||t.abort()}},t,n)}static fromReadableStream(e,t,n){let a=!1;return new s(async function*(){if(a)throw new i("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let s=!1;try{for await(const t of async function*(){const t=new ae,s=z(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(n){if(r(n))return;throw n}finally{s||t.abort()}},t,n)}[(ye=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],r=[],n=this.iterator(),i=t=>({next:()=>{if(0===t.length){const t=n.next();e.push(t),r.push(t)}return t.shift()}});return[new s(()=>i(e),this.controller,t(this,ye,"f")),new s(()=>i(r),this.controller,t(this,ye,"f"))]}toReadableStream(){const e=this;let t;return q({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const n=ne(JSON.stringify(s)+"\n");e.enqueue(n)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}},we=class{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=function(e){const t=e.indexOf(":");return-1!==t?[e.substring(0,t),":",e.substring(t+1)]:[e,"",""]}(e);return r.startsWith(" ")&&(r=r.substring(1)),"event"===t?this.event=r:"data"===t&&this.data.push(r),null}};async function Ae(e,t){const{response:s,requestLogID:r,retryOfRequestLogID:n,startTime:i}=t,a=await(async()=>{if(t.options.stream)return fe(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e,t.options.__synthesizeEventData):be.fromSSEResponse(s,t.controller,e,t.options.__synthesizeEventData);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const r=s.headers.get("content-type")?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){if("0"===s.headers.get("content-length"))return;return ve(await s.json(),s)}return await s.text()})();return fe(e).debug(`[${r}] response parsed`,ge({retryOfRequestLogID:n,url:s.url,status:s.status,body:a,durationMs:Date.now()-i})),a}function ve(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Ie,$e=class s extends Promise{constructor(t,s,r=Ae){super(e=>{e(null)}),this.responsePromise=s,this.parseResponse=r,me.set(this,void 0),e(this,me,t,"f")}_thenUnwrap(e){return new s(t(this,me,"f"),this.responsePromise,async(t,s)=>ve(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(t(this,me,"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)}};me=/* @__PURE__ */new WeakMap;var xe=class{constructor(t,s,r,n){Ie.set(this,void 0),e(this,Ie,t,"f"),this.options=n,this.response=s,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new i("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,Ie,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ie=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}},Pe=class extends $e{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await Ae(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}},Se=class extends xe{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}},ke=class extends xe{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!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...P(this.options.query),after:t}}:null}},Oe=class extends xe{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!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...P(this.options.query),after:e}}:null}},Re=class extends xe{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.next=s.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.next;return e?{...this.options,query:{...P(this.options.query),after:e}}:null}},je={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Ee=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??C()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){const e={grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:await this.config.provider.getToken(),subject_token_type:je[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);const t=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const e=await t.text();let s;try{s=JSON.parse(e)}catch{}if(400===t.status||401===t.status||403===t.status)throw new A(t.status,s,t.headers);throw a.generate(t.status,s,`Token exchange failed with status ${t.status}`,t.headers)}const s=await t.json(),r=s.expires_in||3600,n=Date.now()+1e3*r;return this.cachedToken={token:s.access_token,expiresAt:n},s.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){const t=1e3*(this.config.refreshBufferSeconds??1200);return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},Ke=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Te(e,t,s){return Ke(),new File(e,t??"unknown_file",s)}function Ce(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var qe=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Le=async(e,t)=>Be(e.body)?{...e,body:await De(e.body,t)}:e,ze=async(e,t)=>({...e,body:await De(e.body,t)}),Me=/* @__PURE__ */new WeakMap,De=async(e,t)=>{if(!(await function(e){const t="function"==typeof e?e:e.fetch,s=Me.get(t);if(s)return s;const r=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new e(s).text()}catch{return!0}})();return Me.set(t,r),r}(t)))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>We(s,e,t))),s},Ne=e=>e instanceof Blob&&"name"in e,Be=e=>{if((e=>"object"==typeof e&&null!==e&&(e instanceof Response||qe(e)||Ne(e)))(e))return!0;if(Array.isArray(e))return e.some(Be);if(e&&"object"==typeof e)for(const t in e)if(Be(e[t]))return!0;return!1},We=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response)e.append(t,Te([await s.blob()],Ce(s)));else if(qe(s))e.append(t,Te([await new Response(L(s)).blob()],Ce(s)));else if(Ne(s))e.append(t,s,Ce(s));else if(Array.isArray(s))await Promise.all(s.map(s=>We(e,t+"[]",s)));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map(([s,r])=>We(e,`${t}[${s}]`,r)))}}},Ue=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Fe(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ue(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!qe(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){return"object"!=typeof e||null===e?"":`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await Fe(s))}return t}var He=class{constructor(e){this._client=e}};function Xe(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Je=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.create(null)),Ve=(e=Xe)=>function(t,...s){if(1===t.length)return t[0];let r=!1;const n=[],a=t.reduce((t,i,a)=>{/[?#]/.test(i)&&(r=!0);const o=s[a];let c=(r?encodeURIComponent:e)(""+o);return a!==s.length&&(null==o||"object"==typeof o&&o.toString===Object.getPrototypeOf(Object.getPrototypeOf(o.hasOwnProperty??Je)??Je)?.toString)&&(c=o+"",n.push({start:t.length+i.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(o).slice(8,-1)} is not a valid path parameter`})),t+i+(a===s.length?"":c)},""),o=a.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let l;for(;null!==(l=c.exec(o));)n.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(n.sort((e,t)=>e.start-t.start),n.length>0){let e=0;const t=n.reduce((t,s)=>{const r=" ".repeat(s.start-e),n="^".repeat(s.length);return e=s.start+s.length,t+r+n},"");throw new i(`Path parameters result in path with invalid segments:\n${n.map(e=>e.error).join("\n")}\n${a}\n${t}`)}return a},Ge=/* @__PURE__ */Ve(Xe),Qe=class extends He{list(e,t={},s){return this._client.getAPIList(Ge`/chat/completions/${e}/messages`,ke,{query:t,...s,__security:{bearerAuth:!0}})}};function Ye(e){return void 0!==e&&"function"in e&&void 0!==e.function}function Ze(e){return"auto-parseable-response-format"===e?.$brand}function et(e){return"auto-parseable-tool"===e?.$brand}function tt(e,t){const s=e.choices.map(e=>{if("length"===e.finish_reason)throw new g;if("content_filter"===e.finish_reason)throw new b;return it(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const s=e.tools?.find(e=>Ye(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:et(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?st(t,e.message.content):null}}});return{...e,choices:s}}function st(e,t){return"json_schema"!==e.response_format?.type?null:"json_schema"===e.response_format?.type?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function rt(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const s=e.tools?.find(e=>Ye(e)&&e.function?.name===t.function.name);return Ye(s)&&(et(s)||s?.function.strict||!1)}function nt(e){return!!Ze(e.response_format)||(e.tools?.some(e=>et(e)||"function"===e.type&&!0===e.function.strict)??!1)}function it(e){for(const t of e||[])if("function"!==t.type)throw new i(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}var at,ot,ct,lt,ut,ht,dt,pt,_t,ft,yt,mt,gt,bt,wt,At,vt,It,$t,xt,Pt,St=e=>"assistant"===e?.role,kt=e=>"tool"===e?.role,Ot=class{constructor(){at.add(this),this.controller=new AbortController,ot.set(this,void 0),ct.set(this,()=>{}),lt.set(this,()=>{}),ut.set(this,void 0),ht.set(this,()=>{}),dt.set(this,()=>{}),pt.set(this,{}),_t.set(this,!1),ft.set(this,!1),yt.set(this,!1),mt.set(this,!1),e(this,ot,new Promise((t,s)=>{e(this,ct,t,"f"),e(this,lt,s,"f")}),"f"),e(this,ut,new Promise((t,s)=>{e(this,ht,t,"f"),e(this,dt,s,"f")}),"f"),t(this,ot,"f").catch(()=>{}),t(this,ut,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},t(this,at,"m",gt).bind(this))},0)}_connected(){this.ended||(t(this,ct,"f").call(this),this._emit("connect"))}get ended(){return t(this,_t,"f")}get errored(){return t(this,ft,"f")}get aborted(){return t(this,yt,"f")}abort(){this.controller.abort()}on(e,s){return(t(this,pt,"f")[e]||(t(this,pt,"f")[e]=[])).push({listener:s}),this}off(e,s){const r=t(this,pt,"f")[e];if(!r)return this;const n=r.findIndex(e=>e.listener===s);return n>=0&&r.splice(n,1),this}once(e,s){return(t(this,pt,"f")[e]||(t(this,pt,"f")[e]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,r)=>{e(this,mt,!0,"f"),"error"!==t&&this.once("error",r),this.once(t,s)})}async done(){e(this,mt,!0,"f"),await t(this,ut,"f")}_emit(s,...r){if(t(this,_t,"f"))return;"end"===s&&(e(this,_t,!0,"f"),t(this,ht,"f").call(this));const n=t(this,pt,"f")[s];if(n&&(t(this,pt,"f")[s]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...r))),"abort"===s){const e=r[0];return t(this,mt,"f")||n?.length||Promise.reject(e),t(this,lt,"f").call(this,e),t(this,dt,"f").call(this,e),void this._emit("end")}if("error"===s){const e=r[0];t(this,mt,"f")||n?.length||Promise.reject(e),t(this,lt,"f").call(this,e),t(this,dt,"f").call(this,e),this._emit("end")}}_emitFinal(){}};function Rt(e){return"function"==typeof e.parse}ot=/* @__PURE__ */new WeakMap,ct=/* @__PURE__ */new WeakMap,lt=/* @__PURE__ */new WeakMap,ut=/* @__PURE__ */new WeakMap,ht=/* @__PURE__ */new WeakMap,dt=/* @__PURE__ */new WeakMap,pt=/* @__PURE__ */new WeakMap,_t=/* @__PURE__ */new WeakMap,ft=/* @__PURE__ */new WeakMap,yt=/* @__PURE__ */new WeakMap,mt=/* @__PURE__ */new WeakMap,at=/* @__PURE__ */new WeakSet,gt=function(t){if(e(this,ft,!0,"f"),t instanceof Error&&"AbortError"===t.name&&(t=new o),t instanceof o)return e(this,yt,!0,"f"),this._emit("abort",t);if(t instanceof i)return this._emit("error",t);if(t instanceof Error){const e=new i(t.message);return e.cause=t,this._emit("error",e)}return this._emit("error",new i(String(t)))};var jt=10,Et=class extends Ot{constructor(){super(...arguments),bt.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),kt(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(St(e)&&e.tool_calls)for(const s of e.tool_calls)"function"===s.type&&this._emit("functionToolCall",s.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new i("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),t(this,bt,"m",wt).call(this)}async finalMessage(){return await this.done(),t(this,bt,"m",At).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,bt,"m",vt).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,bt,"m",It).call(this)}async totalUsage(){return await this.done(),t(this,bt,"m",$t).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const s=t(this,bt,"m",At).call(this);s&&this._emit("finalMessage",s);const r=t(this,bt,"m",wt).call(this);r&&this._emit("finalContent",r);const n=t(this,bt,"m",vt).call(this);n&&this._emit("finalFunctionToolCall",n);const i=t(this,bt,"m",It).call(this);null!=i&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",t(this,bt,"m",$t).call(this))}async _createChatCompletion(e,s,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),t(this,bt,"m",xt).call(this,s);const i=await e.chat.completions.create({...s,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(tt(i,s))}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,s,r){const n="tool",{tool_choice:a="auto",stream:o,...c}=s,l="string"!=typeof a&&"function"===a.type&&a?.function?.name,{maxChatCompletions:u=jt}=r||{},h=s.tools.map(e=>{if(et(e)){if(!e.$callback)throw new i("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),d={};for(const t of h)"function"===t.type&&(d[t.function.name||t.function.function.name]=t.function);const p="tools"in s?h.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const t of s.messages)this._addMessage(t,!1);for(let f=0;f<u;++f){const s=(await this._createChatCompletion(e,{...c,tool_choice:a,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!s)throw new i("missing message in ChatCompletion response");if(!s.tool_calls?.length)return;for(const e of s.tool_calls){if("function"!==e.type)continue;const s=e.id,{name:r,arguments:i}=e.function,a=d[r];if(!a){const e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(d).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:s,content:e});continue}if(l&&l!==r){const e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:n,tool_call_id:s,content:e});continue}let o;try{o=Rt(a)?await a.parse(i):i}catch(_){const e=_ instanceof Error?_.message:String(_);this._addMessage({role:n,tool_call_id:s,content:e});continue}const c=await a.function(o,this),u=t(this,bt,"m",Pt).call(this,c);if(this._addMessage({role:n,tool_call_id:s,content:u}),l)return}}}};bt=/* @__PURE__ */new WeakSet,wt=function(){return t(this,bt,"m",At).call(this).content??null},At=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(St(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new i("stream ended without producing a ChatCompletionMessage with role=assistant")},vt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(St(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},It=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(kt(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},$t=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},xt=function(e){if(null!=e.n&&e.n>1)throw new i("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Pt=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};var Kt,Tt,Ct,qt,Lt,zt,Mt,Dt,Nt,Bt,Wt,Ut,Ft=class e extends Et{static runTools(t,s,r){const n=new e,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(t,s,i)),n}_addMessage(e,t=!0){super._addMessage(e,t),St(e)&&e.content&&this._emit("content",e.content)}},Ht=class extends Error{},Xt=class extends Error{},Jt=e=>function(e,t=511){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return((e,t)=>{const s=e.length;let r=0;const n=e=>{throw new Ht(`${e} at position ${r}`)},i=e=>{throw new Xt(`${e} at position ${r}`)},a=()=>(h(),r>=s&&n("Unexpected end of input"),'"'===e[r]?o():"{"===e[r]?c():"["===e[r]?l():"null"===e.substring(r,r+4)||16&t&&s-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):"true"===e.substring(r,r+4)||32&t&&s-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):"false"===e.substring(r,r+5)||32&t&&s-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):"Infinity"===e.substring(r,r+8)||128&t&&s-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):"-Infinity"===e.substring(r,r+9)||256&t&&1<s-r&&s-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):"NaN"===e.substring(r,r+3)||64&t&&s-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):u()),o=()=>{const a=r;let o=!1;for(r++;r<s&&('"'!==e[r]||o&&"\\"===e[r-1]);)o="\\"===e[r]&&!o,r++;if('"'==e.charAt(r))try{return JSON.parse(e.substring(a,++r-Number(o)))}catch(c){i(String(c))}else if(1&t)try{return JSON.parse(e.substring(a,r-Number(o))+'"')}catch(c){return JSON.parse(e.substring(a,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{r++,h();const i={};try{for(;"}"!==e[r];){if(h(),r>=s&&8&t)return i;const n=o();h(),r++;try{const e=a();Object.defineProperty(i,n,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(c){if(8&t)return i;throw c}h(),","===e[r]&&r++}}catch(c){if(8&t)return i;n("Expected '}' at end of object")}return r++,i},l=()=>{r++;const s=[];try{for(;"]"!==e[r];)s.push(a()),h(),","===e[r]&&r++}catch(i){if(4&t)return s;n("Expected ']' at end of array")}return r++,s},u=()=>{if(0===r){"-"===e&&2&t&&n("Not sure what '-' is");try{return JSON.parse(e)}catch(o){if(2&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(o){}i(String(o))}}const a=r;for("-"===e[r]&&r++;e[r]&&!",]}".includes(e[r]);)r++;r!=s||2&t||n("Unterminated number literal");try{return JSON.parse(e.substring(a,r))}catch(o){"-"===e.substring(a,r)&&2&t&&n("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(o){i(String(o))}}},h=()=>{for(;r<s&&" \n\r\t".includes(e[r]);)r++};return a()})(e.trim(),t)}(e,509),Vt=class s extends Et{constructor(t){super(),Kt.add(this),Tt.set(this,void 0),Ct.set(this,void 0),qt.set(this,void 0),e(this,Tt,t,"f"),e(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return t(this,qt,"f")}static fromReadableStream(e){const t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,s,r){super._createChatCompletion;const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),t(this,Kt,"m",Lt).call(this);const i=await e.chat.completions.create({...s,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const a of i)t(this,Kt,"m",Mt).call(this,a);if(i.controller.signal?.aborted)throw new o;return this._addChatCompletion(t(this,Kt,"m",Bt).call(this))}async _fromReadableStream(e,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),t(this,Kt,"m",Lt).call(this),this._connected();const n=be.fromReadableStream(e,this.controller);let i;for await(const a of n)i&&i!==a.id&&this._addChatCompletion(t(this,Kt,"m",Bt).call(this)),t(this,Kt,"m",Mt).call(this,a),i=a.id;if(n.controller.signal?.aborted)throw new o;return this._addChatCompletion(t(this,Kt,"m",Bt).call(this))}[(Tt=/* @__PURE__ */new WeakMap,Ct=/* @__PURE__ */new WeakMap,qt=/* @__PURE__ */new WeakMap,Kt=/* @__PURE__ */new WeakSet,Lt=function(){this.ended||e(this,qt,void 0,"f")},zt=function(e){let s=t(this,Ct,"f")[e.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:/* @__PURE__ */new Set,current_tool_call_index:null},t(this,Ct,"f")[e.index]=s,s)},Mt=function(e){if(this.ended)return;const s=t(this,Kt,"m",Ut).call(this,e);this._emit("chunk",e,s);for(const r of e.choices){const e=s.choices[r.index];null!=r.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),null!=r.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=r.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=t(this,Kt,"m",zt).call(this,e);e.finish_reason&&(t(this,Kt,"m",Nt).call(this,e),null!=n.current_tool_call_index&&t(this,Kt,"m",Dt).call(this,e,n.current_tool_call_index));for(const s of r.delta.tool_calls??[])n.current_tool_call_index!==s.index&&(t(this,Kt,"m",Nt).call(this,e),null!=n.current_tool_call_index&&t(this,Kt,"m",Dt).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=s.index;for(const t of r.delta.tool_calls??[]){const s=e.message.tool_calls?.[t.index];s?.type&&"function"===s?.type&&this._emit("tool_calls.function.arguments.delta",{name:s.function?.name,index:t.index,arguments:s.function.arguments,parsed_arguments:s.function.parsed_arguments,arguments_delta:t.function?.arguments??""})}}},Dt=function(e,s){if(t(this,Kt,"m",zt).call(this,e).done_tool_calls.has(s))return;const r=e.message.tool_calls?.[s];if(!r)throw new Error("no tool call snapshot");if(!r.type)throw new Error("tool call snapshot missing `type`");if("function"===r.type){const e=t(this,Tt,"f")?.tools?.find(e=>Ye(e)&&e.function.name===r.function.name);this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:s,arguments:r.function.arguments,parsed_arguments:et(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Nt=function(e){const s=t(this,Kt,"m",zt).call(this,e);if(e.message.content&&!s.content_done){s.content_done=!0;const r=t(this,Kt,"m",Wt).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Bt=function(){if(this.ended)throw new i("stream has ended, this shouldn't happen");const s=t(this,qt,"f");if(!s)throw new i("request ended without sending any chunks");return e(this,qt,void 0,"f"),e(this,Ct,[],"f"),function(e,t){const{id:s,choices:r,created:n,model:a,system_fingerprint:o,...c}=e,l={...c,id:s,choices:r.map(({message:t,finish_reason:s,index:r,logprobs:n,...a})=>{if(!s)throw new i(`missing finish_reason for choice ${r}`);const{content:o=null,function_call:c,tool_calls:l,...u}=t,h=t.role;if(!h)throw new i(`missing role for choice ${r}`);if(c){const{arguments:e,name:l}=c;if(null==e)throw new i(`missing function_call.arguments for choice ${r}`);if(!l)throw new i(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:l},role:h,refusal:t.refusal??null},finish_reason:s,index:r,logprobs:n}}return l?{...a,index:r,finish_reason:s,logprobs:n,message:{...u,role:h,content:o,refusal:t.refusal??null,tool_calls:l.map((t,s)=>{const{function:n,type:a,id:o,...c}=t,{arguments:l,name:u,...h}=n||{};if(null==o)throw new i(`missing choices[${r}].tool_calls[${s}].id\n${Gt(e)}`);if(null==a)throw new i(`missing choices[${r}].tool_calls[${s}].type\n${Gt(e)}`);if(null==u)throw new i(`missing choices[${r}].tool_calls[${s}].function.name\n${Gt(e)}`);if(null==l)throw new i(`missing choices[${r}].tool_calls[${s}].function.arguments\n${Gt(e)}`);return{...c,id:o,type:a,function:{...h,name:u,arguments:l}}})}}:{...a,message:{...u,content:o,role:h,refusal:t.refusal??null},finish_reason:s,index:r,logprobs:n}}),created:n,model:a,object:"chat.completion",...o?{system_fingerprint:o}:{}};return function(e,t){return t&&nt(t)?tt(e,t):{...e,choices:e.choices.map(e=>(it(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(l,t)}(s,t(this,Tt,"f"))},Wt=function(){const e=t(this,Tt,"f")?.response_format;return Ze(e)?e:null},Ut=function(s){var r,n,i,a;let o=t(this,qt,"f");const{choices:c,...l}=s;o?Object.assign(o,l):o=e(this,qt,{...l,choices:[]},"f");for(const{delta:e,finish_reason:u,index:h,logprobs:d=null,...p}of s.choices){let s=o.choices[h];if(s||(s=o.choices[h]={finish_reason:u,index:h,message:{},logprobs:d,...p}),d)if(s.logprobs){const{content:e,refusal:t,...i}=d;Object.assign(s.logprobs,i),e&&((r=s.logprobs).content??(r.content=[]),s.logprobs.content.push(...e)),t&&((n=s.logprobs).refusal??(n.refusal=[]),s.logprobs.refusal.push(...t))}else s.logprobs=Object.assign({},d);if(u&&(s.finish_reason=u,t(this,Tt,"f")&&nt(t(this,Tt,"f")))){if("length"===u)throw new g;if("content_filter"===u)throw new b}if(Object.assign(s,p),!e)continue;const{content:c,refusal:l,function_call:_,role:f,tool_calls:y,...m}=e;if(Object.assign(s.message,m),l&&(s.message.refusal=(s.message.refusal||"")+l),f&&(s.message.role=f),_&&(s.message.function_call?(_.name&&(s.message.function_call.name=_.name),_.arguments&&((i=s.message.function_call).arguments??(i.arguments=""),s.message.function_call.arguments+=_.arguments)):s.message.function_call=_),c&&(s.message.content=(s.message.content||"")+c,!s.message.refusal&&t(this,Kt,"m",Wt).call(this)&&(s.message.parsed=Jt(s.message.content))),y){s.message.tool_calls||(s.message.tool_calls=[]);for(const{index:e,id:r,type:n,function:i,...o}of y){const c=(a=s.message.tool_calls)[e]??(a[e]={});Object.assign(c,o),r&&(c.id=r),n&&(c.type=n),i&&(c.function??(c.function={name:i.name??"",arguments:""})),i?.name&&(c.function.name=i.name),i?.arguments&&(c.function.arguments+=i.arguments,rt(t(this,Tt,"f"),c)&&(c.function.parsed_arguments=Jt(c.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",s=>{const r=t.shift();r?r.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new be(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Gt(e){return JSON.stringify(e)}var Qt=class e extends Vt{static fromReadableStream(t){const s=new e(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,r){const n=new e(s),i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(t,s,i)),n}},Yt=class extends He{constructor(){super(...arguments),this.messages=new Qe(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/chat/completions/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",ke,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new i(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new i(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>tt(t,e))}runTools(e,t){return e.stream?Qt.runTools(this._client,e,t):Ft.runTools(this._client,e,t)}stream(e,t){return Vt.createChatCompletion(this._client,e,t)}};Yt.Messages=Qe;var Zt=class extends He{constructor(){super(...arguments),this.completions=new Yt(this._client)}};Zt.Completions=Yt;var es=class extends He{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",ke,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},ts=class extends He{list(e={},t){return this._client.getAPIList("/organization/audit_logs",Oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},ss=class extends He{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},s){return this._client.get(Ge`/organization/certificates/${e}`,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/certificates/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",Oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",Se,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",Se,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}},rs=class extends He{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},ns=class extends He{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",Oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},is=class extends He{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/roles/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",Re,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},as=class extends He{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/spend_alerts/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",Oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},os=class extends He{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},cs=class extends He{create(e,t,s){return this._client.post(Ge`/organization/groups/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{group_id:r}=t;return this._client.get(Ge`/organization/groups/${r}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/groups/${e}/roles`,Re,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{group_id:r}=t;return this._client.delete(Ge`/organization/groups/${r}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},ls=class extends He{create(e,t,s){return this._client.post(Ge`/organization/groups/${e}/users`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{group_id:r}=t;return this._client.get(Ge`/organization/groups/${r}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/groups/${e}/users`,Re,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{group_id:r}=t;return this._client.delete(Ge`/organization/groups/${r}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},us=class extends He{constructor(){super(...arguments),this.users=new ls(this._client),this.roles=new cs(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/groups/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",Re,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};us.Users=ls,us.Roles=cs;var hs=class extends He{retrieve(e,t,s){const{project_id:r}=t;return this._client.get(Ge`/organization/projects/${r}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/api_keys`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r}=t;return this._client.delete(Ge`/organization/projects/${r}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},ds=class extends He{list(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/certificates`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}activate(e,t,s){return this._client.getAPIList(Ge`/organization/projects/${e}/certificates/activate`,Se,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,s){return this._client.getAPIList(Ge`/organization/projects/${e}/certificates/deactivate`,Se,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}},ps=class extends He{retrieve(e,t){return this._client.get(Ge`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/projects/${e}/data_retention`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}},_s=class extends He{retrieve(e,t){return this._client.get(Ge`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}},fs=class extends He{retrieve(e,t){return this._client.get(Ge`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/projects/${e}/model_permissions`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},ys=class extends He{listRateLimits(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/rate_limits`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/organization/projects/${r}/rate_limits/${e}`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}},ms=class extends He{create(e,t,s){return this._client.post(Ge`/projects/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:r}=t;return this._client.get(Ge`/projects/${r}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/projects/${r}/roles/${e}`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/projects/${e}/roles`,Re,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r}=t;return this._client.delete(Ge`/projects/${r}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},gs=class extends He{create(e,t,s){return this._client.post(Ge`/organization/projects/${e}/service_accounts`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:r}=t;return this._client.get(Ge`/organization/projects/${r}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/organization/projects/${r}/service_accounts/${e}`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/service_accounts`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r}=t;return this._client.delete(Ge`/organization/projects/${r}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},bs=class extends He{create(e,t,s){return this._client.post(Ge`/organization/projects/${e}/spend_alerts`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/organization/projects/${r}/spend_alerts/${e}`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/spend_alerts`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r}=t;return this._client.delete(Ge`/organization/projects/${r}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},ws=class extends He{create(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/projects/${r}/groups/${e}/roles`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:r,group_id:n}=t;return this._client.get(Ge`/projects/${r}/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t,s){const{project_id:r,...n}=t;return this._client.getAPIList(Ge`/projects/${r}/groups/${e}/roles`,Re,{query:n,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r,group_id:n}=t;return this._client.delete(Ge`/projects/${r}/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},As=class extends He{constructor(){super(...arguments),this.roles=new ws(this._client)}create(e,t,s){return this._client.post(Ge`/organization/projects/${e}/groups`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:r,...n}=t;return this._client.get(Ge`/organization/projects/${r}/groups/${e}`,{query:n,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/groups`,Re,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r}=t;return this._client.delete(Ge`/organization/projects/${r}/groups/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};As.Roles=ws;var vs=class extends He{create(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/projects/${r}/users/${e}/roles`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:r,user_id:n}=t;return this._client.get(Ge`/projects/${r}/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t,s){const{project_id:r,...n}=t;return this._client.getAPIList(Ge`/projects/${r}/users/${e}/roles`,Re,{query:n,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r,user_id:n}=t;return this._client.delete(Ge`/projects/${r}/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},Is=class extends He{constructor(){super(...arguments),this.roles=new vs(this._client)}create(e,t,s){return this._client.post(Ge`/organization/projects/${e}/users`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:r}=t;return this._client.get(Ge`/organization/projects/${r}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:r,...n}=t;return this._client.post(Ge`/organization/projects/${r}/users/${e}`,{body:n,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/projects/${e}/users`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:r}=t;return this._client.delete(Ge`/organization/projects/${r}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};Is.Roles=vs;var $s=class extends He{constructor(){super(...arguments),this.users=new Is(this._client),this.serviceAccounts=new gs(this._client),this.apiKeys=new hs(this._client),this.rateLimits=new ys(this._client),this.modelPermissions=new fs(this._client),this.hostedToolPermissions=new _s(this._client),this.groups=new As(this._client),this.roles=new ms(this._client),this.dataRetention=new ps(this._client),this.spendAlerts=new bs(this._client),this.certificates=new ds(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/projects/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",Oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(Ge`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};$s.Users=Is,$s.ServiceAccounts=gs,$s.APIKeys=hs,$s.RateLimits=ys,$s.ModelPermissions=fs,$s.HostedToolPermissions=_s,$s.Groups=As,$s.Roles=ms,$s.DataRetention=ps,$s.SpendAlerts=bs,$s.Certificates=ds;var xs=class extends He{create(e,t,s){return this._client.post(Ge`/organization/users/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{user_id:r}=t;return this._client.get(Ge`/organization/users/${r}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/organization/users/${e}/roles`,Re,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{user_id:r}=t;return this._client.delete(Ge`/organization/users/${r}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},Ps=class extends He{constructor(){super(...arguments),this.roles=new xs(this._client)}retrieve(e,t){return this._client.get(Ge`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(Ge`/organization/users/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",Oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Ge`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Ps.Roles=xs;var Ss=class extends He{constructor(){super(...arguments),this.auditLogs=new ts(this._client),this.adminAPIKeys=new es(this._client),this.usage=new os(this._client),this.invites=new ns(this._client),this.users=new Ps(this._client),this.groups=new us(this._client),this.roles=new is(this._client),this.dataRetention=new rs(this._client),this.spendAlerts=new as(this._client),this.certificates=new ss(this._client),this.projects=new $s(this._client)}};Ss.AuditLogs=ts,Ss.AdminAPIKeys=es,Ss.Usage=os,Ss.Invites=ns,Ss.Users=Ps,Ss.Groups=us,Ss.Roles=is,Ss.DataRetention=rs,Ss.SpendAlerts=as,Ss.Certificates=ss,Ss.Projects=$s;var ks=class extends He{constructor(){super(...arguments),this.organization=new Ss(this._client)}};ks.Organization=Ss;var Os=/* @__PURE__ */Symbol("brand.privateNullableHeaders");function*Rs(e){if(!e)return;if(Os in e){const{values:t,nulls:s}=e;yield*t.entries();for(const e of s)yield[e,null];return}let t,s=!1;e instanceof Headers?t=e.entries():x(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let r of t){const e=r[0];if("string"!=typeof e)throw new TypeError("expected header name to be a string");const t=x(r[1])?r[1]:[r[1]];let n=!1;for(const r of t)void 0!==r&&(s&&!n&&(n=!0,yield[e,null]),yield[e,r])}}var js=e=>{const t=new Headers,s=/* @__PURE__ */new Set;for(const r of e){const e=/* @__PURE__ */new Set;for(const[n,i]of Rs(r)){const r=n.toLowerCase();e.has(r)||(t.delete(n),e.add(r)),null===i?(t.delete(n),s.add(r)):(t.append(n,i),s.delete(r))}}return{[Os]:!0,values:t,nulls:s}},Es=class extends He{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:js([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Ks=class extends He{create(e,t){return this._client.post("/audio/transcriptions",ze({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Ts=class extends He{create(e,t){return this._client.post("/audio/translations",ze({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Cs=class extends He{constructor(){super(...arguments),this.transcriptions=new Ks(this._client),this.translations=new Ts(this._client),this.speech=new Es(this._client)}};Cs.Transcriptions=Ks,Cs.Translations=Ts,Cs.Speech=Es;var qs=class extends He{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",ke,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Ge`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},Ls=class extends He{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/assistants/${e}`,{...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/assistants/${e}`,{body:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",ke,{query:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/assistants/${e}`,{...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}},zs=class extends He{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}},Ms=class extends He{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}},Ds=class extends He{constructor(){super(...arguments),this.sessions=new zs(this._client),this.transcriptionSessions=new Ms(this._client)}};Ds.Sessions=zs,Ds.TranscriptionSessions=Ms;var Ns=class extends He{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:js([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Ge`/chatkit/sessions/${e}/cancel`,{...t,headers:js([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}},Bs=class extends He{retrieve(e,t){return this._client.get(Ge`/chatkit/threads/${e}`,{...t,headers:js([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Oe,{query:e,...t,headers:js([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/chatkit/threads/${e}`,{...t,headers:js([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},s){return this._client.getAPIList(Ge`/chatkit/threads/${e}/items`,Oe,{query:t,...s,headers:js([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers]),__security:{bearerAuth:!0}})}},Ws=class extends He{constructor(){super(...arguments),this.sessions=new Ns(this._client),this.threads=new Bs(this._client)}};Ws.Sessions=Ns,Ws.Threads=Bs;var Us,Fs,Hs,Xs,Js,Vs,Gs,Qs,Ys,Zs,er,tr,sr,rr,nr,ir,ar,or,cr,lr,ur,hr,dr,pr=class extends He{create(e,t,s){return this._client.post(Ge`/threads/${e}/messages`,{body:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(Ge`/threads/${r}/messages/${e}`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){const{thread_id:r,...n}=t;return this._client.post(Ge`/threads/${r}/messages/${e}`,{body:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/threads/${e}/messages`,ke,{query:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t,s){const{thread_id:r}=t;return this._client.delete(Ge`/threads/${r}/messages/${e}`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}},_r=class extends He{retrieve(e,t,s){const{thread_id:r,run_id:n,...i}=t;return this._client.get(Ge`/threads/${r}/runs/${n}/steps/${e}`,{query:i,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t,s){const{thread_id:r,...n}=t;return this._client.getAPIList(Ge`/threads/${r}/runs/${e}/steps`,ke,{query:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}},fr=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()||void 0:void 0!==globalThis.Deno&&globalThis.Deno.env?.get?.(e)?.trim()||void 0,yr=class extends Ot{constructor(){super(...arguments),Us.add(this),Hs.set(this,[]),Xs.set(this,{}),Js.set(this,{}),Vs.set(this,void 0),Gs.set(this,void 0),Qs.set(this,void 0),Ys.set(this,void 0),Zs.set(this,void 0),er.set(this,void 0),tr.set(this,void 0),sr.set(this,void 0),rr.set(this,void 0)}[(Hs=/* @__PURE__ */new WeakMap,Xs=/* @__PURE__ */new WeakMap,Js=/* @__PURE__ */new WeakMap,Vs=/* @__PURE__ */new WeakMap,Gs=/* @__PURE__ */new WeakMap,Qs=/* @__PURE__ */new WeakMap,Ys=/* @__PURE__ */new WeakMap,Zs=/* @__PURE__ */new WeakMap,er=/* @__PURE__ */new WeakMap,tr=/* @__PURE__ */new WeakMap,sr=/* @__PURE__ */new WeakMap,rr=/* @__PURE__ */new WeakMap,Us=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",s=>{const r=t.shift();r?r.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Fs;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const n=be.fromReadableStream(e,this.controller);for await(const i of n)t(this,Us,"m",nr).call(this,i);if(n.controller.signal?.aborted)throw new o;return this._addRun(t(this,Us,"m",ir).call(this))}toReadableStream(){return new be(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r){const n=new Fs;return n._run(()=>n._runToolAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,s,r,n){const i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},c=await e.submitToolOutputs(s,a,{...n,signal:this.controller.signal});this._connected();for await(const o of c)t(this,Us,"m",nr).call(this,o);if(c.controller.signal?.aborted)throw new o;return this._addRun(t(this,Us,"m",ir).call(this))}static createThreadAssistantStream(e,t,s){const r=new Fs;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const n=new Fs;return n._run(()=>n._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return t(this,tr,"f")}currentRun(){return t(this,sr,"f")}currentMessageSnapshot(){return t(this,Vs,"f")}currentRunStepSnapshot(){return t(this,rr,"f")}async finalRunSteps(){return await this.done(),Object.values(t(this,Xs,"f"))}async finalMessages(){return await this.done(),Object.values(t(this,Js,"f"))}async finalRun(){if(await this.done(),!t(this,Gs,"f"))throw Error("Final run was not received.");return t(this,Gs,"f")}async _createThreadAssistantStream(e,s,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},a=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(const o of a)t(this,Us,"m",nr).call(this,o);if(a.controller.signal?.aborted)throw new o;return this._addRun(t(this,Us,"m",ir).call(this))}async _createAssistantStream(e,s,r,n){const i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},c=await e.create(s,a,{...n,signal:this.controller.signal});this._connected();for await(const o of c)t(this,Us,"m",nr).call(this,o);if(c.controller.signal?.aborted)throw new o;return this._addRun(t(this,Us,"m",ir).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let t=e[s];if(null!=t)if("index"!==s&&"type"!==s){if("string"==typeof t&&"string"==typeof r)t+=r;else if("number"==typeof t&&"number"==typeof r)t+=r;else{if(!k(t)||!k(r)){if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...r);continue}for(const e of r){if(!k(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const s=e.index;if(null==s)throw new Error("Expected array delta entry to have an `index` property");if("number"!=typeof s)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);const r=t[s];null==r?t.push(e):t[s]=this.accumulateDelta(r,e)}continue}throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${t}`)}t=this.accumulateDelta(t,r)}e[s]=t}else e[s]=r;else e[s]=r}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)}};Fs=yr,nr=function(s){if(!this.ended)switch(e(this,tr,s,"f"),t(this,Us,"m",cr).call(this,s),s.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":t(this,Us,"m",dr).call(this,s);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":t(this,Us,"m",or).call(this,s);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":t(this,Us,"m",ar).call(this,s);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},ir=function(){if(this.ended)throw new i("stream has ended, this shouldn't happen");if(!t(this,Gs,"f"))throw Error("Final run has not been received");return t(this,Gs,"f")},ar=function(s){const[r,n]=t(this,Us,"m",ur).call(this,s,t(this,Vs,"f"));e(this,Vs,r,"f"),t(this,Js,"f")[r.id]=r;for(const e of n){const t=r.content[e.index];"text"==t?.type&&this._emit("textCreated",t.text)}switch(s.event){case"thread.message.created":this._emit("messageCreated",s.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",s.data.delta,r),s.data.delta.content)for(const n of s.data.delta.content){if("text"==n.type&&n.text){let e=n.text,t=r.content[n.index];if(!t||"text"!=t.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,t.text)}if(n.index!=t(this,Qs,"f")){if(t(this,Ys,"f"))switch(t(this,Ys,"f").type){case"text":this._emit("textDone",t(this,Ys,"f").text,t(this,Vs,"f"));break;case"image_file":this._emit("imageFileDone",t(this,Ys,"f").image_file,t(this,Vs,"f"))}e(this,Qs,n.index,"f")}e(this,Ys,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==t(this,Qs,"f")){const e=s.data.content[t(this,Qs,"f")];if(e)switch(e.type){case"image_file":this._emit("imageFileDone",e.image_file,t(this,Vs,"f"));break;case"text":this._emit("textDone",e.text,t(this,Vs,"f"))}}t(this,Vs,"f")&&this._emit("messageDone",s.data),e(this,Vs,void 0,"f")}},or=function(s){const r=t(this,Us,"m",lr).call(this,s);switch(e(this,rr,r,"f"),s.event){case"thread.run.step.created":this._emit("runStepCreated",s.data);break;case"thread.run.step.delta":const n=s.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==r.step_details.type)for(const s of n.step_details.tool_calls)s.index==t(this,Zs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(t(this,er,"f")&&this._emit("toolCallDone",t(this,er,"f")),e(this,Zs,s.index,"f"),e(this,er,r.step_details.tool_calls[s.index],"f"),t(this,er,"f")&&this._emit("toolCallCreated",t(this,er,"f")));this._emit("runStepDelta",s.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":e(this,rr,void 0,"f"),"tool_calls"==s.data.step_details.type&&t(this,er,"f")&&(this._emit("toolCallDone",t(this,er,"f")),e(this,er,void 0,"f")),this._emit("runStepDone",s.data,r)}},cr=function(e){t(this,Hs,"f").push(e),this._emit("event",e)},lr=function(e){switch(e.event){case"thread.run.step.created":return t(this,Xs,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let s=t(this,Xs,"f")[e.data.id];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const n=Fs.accumulateDelta(s,r.delta);t(this,Xs,"f")[e.data.id]=n}return t(this,Xs,"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":t(this,Xs,"f")[e.data.id]=e.data}if(t(this,Xs,"f")[e.data.id])return t(this,Xs,"f")[e.data.id];throw new Error("No snapshot available")},ur=function(e,s){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!s)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in s.content){let r=s.content[e.index];s.content[e.index]=t(this,Us,"m",hr).call(this,e,r)}else s.content[e.index]=e,r.push(e);return[s,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(s)return[s,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},hr=function(e,t){return Fs.accumulateDelta(t,e)},dr=function(s){switch(e(this,sr,s.data,"f"),s.event){case"thread.run.created":case"thread.run.queued":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":e(this,Gs,s.data,"f"),t(this,er,"f")&&(this._emit("toolCallDone",t(this,er,"f")),e(this,er,void 0,"f"))}};var mr=class extends He{constructor(){super(...arguments),this.steps=new _r(this._client)}create(e,t,s){const{include:r,...n}=t;return this._client.post(Ge`/threads/${e}/runs`,{query:{include:r},body:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(Ge`/threads/${r}/runs/${e}`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){const{thread_id:r,...n}=t;return this._client.post(Ge`/threads/${r}/runs/${e}`,{body:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/threads/${e}/runs`,ke,{query:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,s){const{thread_id:r}=t;return this._client.post(Ge`/threads/${r}/runs/${e}/cancel`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}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 yr.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r=js([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:n,response:i}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...r}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await R(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,s){return yr.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:r,...n}=t;return this._client.post(Ge`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!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 yr.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};mr.Steps=_r;var gr=class extends He{constructor(){super(...arguments),this.runs=new mr(this._client),this.messages=new pr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/threads/${e}`,{...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/threads/${e}`,{body:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/threads/${e}`,{...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!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 yr.createThreadAssistantStream(e,this._client.beta.threads,t)}};gr.Runs=mr,gr.Messages=pr;var br=class extends He{constructor(){super(...arguments),this.realtime=new Ds(this._client),this.chatkit=new Ws(this._client),this.assistants=new Ls(this._client),this.threads=new gr(this._client)}};br.Realtime=Ds,br.ChatKit=Ws,br.Assistants=Ls,br.Threads=gr;var wr=class extends He{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Ar=class extends He{retrieve(e,t,s){const{container_id:r}=t;return this._client.get(Ge`/containers/${r}/files/${e}/content`,{...s,headers:js([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},vr=class extends He{constructor(){super(...arguments),this.content=new Ar(this._client)}create(e,t,s){return this._client.post(Ge`/containers/${e}/files`,Le({body:t,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,s){const{container_id:r}=t;return this._client.get(Ge`/containers/${r}/files/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/containers/${e}/files`,ke,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{container_id:r}=t;return this._client.delete(Ge`/containers/${r}/files/${e}`,{...s,headers:js([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};vr.Content=Ar;var Ir=class extends He{constructor(){super(...arguments),this.files=new vr(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",ke,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/containers/${e}`,{...t,headers:js([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Ir.Files=vr;var $r=class extends He{create(e,t,s){const{include:r,...n}=t;return this._client.post(Ge`/conversations/${e}/items`,{query:{include:r},body:n,...s,__security:{bearerAuth:!0}})}retrieve(e,t,s){const{conversation_id:r,...n}=t;return this._client.get(Ge`/conversations/${r}/items/${e}`,{query:n,...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/conversations/${e}/items`,Oe,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{conversation_id:r}=t;return this._client.delete(Ge`/conversations/${r}/items/${e}`,{...s,__security:{bearerAuth:!0}})}},xr=class extends He{constructor(){super(...arguments),this.items=new $r(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/conversations/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};xr.Items=$r;var Pr=class extends He{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&fe(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const n=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return s?n:(fe(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),s=t.length,r=new Uint8Array(s);for(let e=0;e<s;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}})(t)}),e)))}},Sr=class extends He{retrieve(e,t,s){const{eval_id:r,run_id:n}=t;return this._client.get(Ge`/evals/${r}/runs/${n}/output_items/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t,s){const{eval_id:r,...n}=t;return this._client.getAPIList(Ge`/evals/${r}/runs/${e}/output_items`,ke,{query:n,...s,__security:{bearerAuth:!0}})}},kr=class extends He{constructor(){super(...arguments),this.outputItems=new Sr(this._client)}create(e,t,s){return this._client.post(Ge`/evals/${e}/runs`,{body:t,...s,__security:{bearerAuth:!0}})}retrieve(e,t,s){const{eval_id:r}=t;return this._client.get(Ge`/evals/${r}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/evals/${e}/runs`,ke,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{eval_id:r}=t;return this._client.delete(Ge`/evals/${r}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}cancel(e,t,s){const{eval_id:r}=t;return this._client.post(Ge`/evals/${r}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}};kr.OutputItems=Sr;var Or=class extends He{constructor(){super(...arguments),this.runs=new kr(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/evals/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",ke,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Or.Runs=kr;var Rr=class extends He{create(e,t){return this._client.post("/files",ze({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(Ge`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",ke,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(Ge`/files/${e}/content`,{...t,headers:js([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const r=/* @__PURE__ */new Set(["processed","error","deleted"]),n=Date.now();let i=await this.retrieve(e);for(;!i.status||!r.has(i.status);)if(await R(t),i=await this.retrieve(e),Date.now()-n>s)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}},jr=class extends He{},Er=class extends He{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}},Kr=class extends He{constructor(){super(...arguments),this.graders=new Er(this._client)}};Kr.Graders=Er;var Tr=class extends He{create(e,t,s){return this._client.getAPIList(Ge`/fine_tuning/checkpoints/${e}/permissions`,Se,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},s){return this._client.get(Ge`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/fine_tuning/checkpoints/${e}/permissions`,Oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(Ge`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},Cr=class extends He{constructor(){super(...arguments),this.permissions=new Tr(this._client)}};Cr.Permissions=Tr;var qr=class extends He{list(e,t={},s){return this._client.getAPIList(Ge`/fine_tuning/jobs/${e}/checkpoints`,ke,{query:t,...s,__security:{bearerAuth:!0}})}},Lr=class extends He{constructor(){super(...arguments),this.checkpoints=new qr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",ke,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Ge`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},s){return this._client.getAPIList(Ge`/fine_tuning/jobs/${e}/events`,ke,{query:t,...s,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(Ge`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(Ge`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};Lr.Checkpoints=qr;var zr=class extends He{constructor(){super(...arguments),this.methods=new jr(this._client),this.jobs=new Lr(this._client),this.checkpoints=new Cr(this._client),this.alpha=new Kr(this._client)}};zr.Methods=jr,zr.Jobs=Lr,zr.Checkpoints=Cr,zr.Alpha=Kr;var Mr=class extends He{},Dr=class extends He{constructor(){super(...arguments),this.graderModels=new Mr(this._client)}};Dr.GraderModels=Mr;var Nr,Br,Wr,Ur,Fr,Hr,Xr,Jr,Vr=class extends He{createVariation(e,t){return this._client.post("/images/variations",ze({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",ze({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Gr=class extends He{retrieve(e,t){return this._client.get(Ge`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Se,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},Qr=class extends He{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}},Yr=class extends He{accept(e,t,s){return this._client.post(Ge`/realtime/calls/${e}/accept`,{body:t,...s,headers:js([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(Ge`/realtime/calls/${e}/hangup`,{...t,headers:js([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,s){return this._client.post(Ge`/realtime/calls/${e}/refer`,{body:t,...s,headers:js([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},s){return this._client.post(Ge`/realtime/calls/${e}/reject`,{body:t,...s,headers:js([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}},Zr=class extends He{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}},en=class extends He{constructor(){super(...arguments),this.clientSecrets=new Zr(this._client),this.calls=new Yr(this._client)}};function tn(e,t){const s=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:rn(t,e)};if("message"===e.type){const s=e.content.map(e=>"output_text"===e.type?{...e,parsed:sn(t,e.text)}:e);return{...e,content:s}}return e}),r=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||nn(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const e of r.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),r}function sn(e,t){return"json_schema"!==e.text?.format?.type?null:"$parseRaw"in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t)}function rn(e,t){const s=(r=e.tools??[],n=t.name,r.find(e=>"function"===e.type&&e.name===n));var r,n,i;return{...t,...t,parsed_arguments:(i=s,"auto-parseable-tool"===i?.$brand?s.$parseRaw(t.arguments):s?.strict?JSON.parse(t.arguments):null)}}function nn(e){const t=[];for(const s of e.output)if("message"===s.type)for(const e of s.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}en.ClientSecrets=Zr,en.Calls=Yr;var an=class s extends Ot{constructor(t){super(),Nr.add(this),Br.set(this,void 0),Wr.set(this,void 0),Ur.set(this,void 0),e(this,Br,t,"f")}static createResponse(e,t,r){const n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,s,r){const n=r?.signal;let i;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),t(this,Nr,"m",Fr).call(this);let a=null;"response_id"in s?(i=await e.responses.retrieve(s.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=s.starting_after??null):i=await e.responses.create({...s,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of i)t(this,Nr,"m",Hr).call(this,o,a);if(i.controller.signal?.aborted)throw new o;return t(this,Nr,"m",Xr).call(this)}[(Br=/* @__PURE__ */new WeakMap,Wr=/* @__PURE__ */new WeakMap,Ur=/* @__PURE__ */new WeakMap,Nr=/* @__PURE__ */new WeakSet,Fr=function(){this.ended||e(this,Wr,void 0,"f")},Hr=function(e,s){if(this.ended)return;const r=(e,t)=>{(null==s||t.sequence_number>s)&&this._emit(e,t)},n=t(this,Nr,"m",Jr).call(this,e);switch(r("event",e),e.type){case"response.output_text.delta":{const t=n.output[e.output_index];if(!t)throw new i(`missing output at index ${e.output_index}`);if("message"===t.type){const s=t.content[e.content_index];if(!s)throw new i(`missing content at index ${e.content_index}`);if("output_text"!==s.type)throw new i(`expected content to be 'output_text', got ${s.type}`);r("response.output_text.delta",{...e,snapshot:s.text})}break}case"response.function_call_arguments.delta":{const t=n.output[e.output_index];if(!t)throw new i(`missing output at index ${e.output_index}`);"function_call"===t.type&&r("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:r(e.type,e)}},Xr=function(){if(this.ended)throw new i("stream has ended, this shouldn't happen");const s=t(this,Wr,"f");if(!s)throw new i("request ended without sending any events");e(this,Wr,void 0,"f");const r=function(e,t){return function(e,t){return t&&function(e){return!!Ze(e.text?.format)}(t)?tn(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}(e,t)}(s,t(this,Br,"f"));return e(this,Ur,r,"f"),r},Jr=function(s){let r=t(this,Wr,"f");if(!r){if("response.created"!==s.type)throw new i(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return r=e(this,Wr,s.response,"f"),r}switch(s.type){case"response.output_item.added":r.output.push(s.item);break;case"response.content_part.added":{const e=r.output[s.output_index];if(!e)throw new i(`missing output at index ${s.output_index}`);const t=e.type,n=s.part;"message"===t&&"reasoning_text"!==n.type?e.content.push(n):"reasoning"===t&&"reasoning_text"===n.type&&(e.content||(e.content=[]),e.content.push(n));break}case"response.output_text.delta":{const e=r.output[s.output_index];if(!e)throw new i(`missing output at index ${s.output_index}`);if("message"===e.type){const t=e.content[s.content_index];if(!t)throw new i(`missing content at index ${s.content_index}`);if("output_text"!==t.type)throw new i(`expected content to be 'output_text', got ${t.type}`);t.text+=s.delta}break}case"response.function_call_arguments.delta":{const e=r.output[s.output_index];if(!e)throw new i(`missing output at index ${s.output_index}`);"function_call"===e.type&&(e.arguments+=s.delta);break}case"response.reasoning_text.delta":{const e=r.output[s.output_index];if(!e)throw new i(`missing output at index ${s.output_index}`);if("reasoning"===e.type){const t=e.content?.[s.content_index];if(!t)throw new i(`missing content at index ${s.content_index}`);if("reasoning_text"!==t.type)throw new i(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=s.delta}break}case"response.completed":e(this,Wr,s.response,"f")}return r},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",s=>{const r=t.shift();r?r.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=t(this,Ur,"f");if(!e)throw new i("stream ended without producing a ChatCompletion");return e}},on=class extends He{list(e,t={},s){return this._client.getAPIList(Ge`/responses/${e}/input_items`,ke,{query:t,...s,__security:{bearerAuth:!0}})}},cn=class extends He{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}},ln=class extends He{constructor(){super(...arguments),this.inputItems=new on(this._client),this.inputTokens=new cn(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>("object"in e&&"response"===e.object&&nn(e),e))}retrieve(e,t={},s){return this._client.get(Ge`/responses/${e}`,{query:t,...s,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>("object"in e&&"response"===e.object&&nn(e),e))}delete(e,t){return this._client.delete(Ge`/responses/${e}`,{...t,headers:js([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>tn(t,e))}stream(e,t){return an.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Ge`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};ln.InputItems=on,ln.InputTokens=cn;var un=class extends He{retrieve(e,t){return this._client.get(Ge`/skills/${e}/content`,{...t,headers:js([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},hn=class extends He{retrieve(e,t,s){const{skill_id:r}=t;return this._client.get(Ge`/skills/${r}/versions/${e}/content`,{...s,headers:js([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},dn=class extends He{constructor(){super(...arguments),this.content=new hn(this._client)}create(e,t={},s){return this._client.post(Ge`/skills/${e}/versions`,Le({body:t,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,s){const{skill_id:r}=t;return this._client.get(Ge`/skills/${r}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/skills/${e}/versions`,ke,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{skill_id:r}=t;return this._client.delete(Ge`/skills/${r}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}};dn.Content=hn;var pn=class extends He{constructor(){super(...arguments),this.content=new un(this._client),this.versions=new dn(this._client)}create(e={},t){return this._client.post("/skills",Le({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(Ge`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/skills/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",ke,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};pn.Content=un,pn.Versions=dn;var _n=class extends He{create(e,t,s){return this._client.post(Ge`/uploads/${e}/parts`,ze({body:t,...s,__security:{bearerAuth:!0}},this._client))}},fn=class extends He{constructor(){super(...arguments),this.parts=new _n(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Ge`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,s){return this._client.post(Ge`/uploads/${e}/complete`,{body:t,...s,__security:{bearerAuth:!0}})}};fn.Parts=_n;var yn=class extends He{create(e,t,s){return this._client.post(Ge`/vector_stores/${e}/file_batches`,{body:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(Ge`/vector_stores/${r}/file_batches/${e}`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,s){const{vector_store_id:r}=t;return this._client.post(Ge`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}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,...n}=t;return this._client.getAPIList(Ge`/vector_stores/${r}/file_batches/${e}/files`,ke,{query:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,s){const r=js([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:n,response:i}=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse();switch(n.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await R(e);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},r){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const n=r?.maxConcurrency??5,i=Math.min(n,t.length),a=this._client,o=t.values(),c=[...s],l=Array(i).fill(o).map(async function(e){for(let t of e){const e=await a.files.create({file:t,purpose:"assistants"},r);c.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),s=t.filter(e=>"rejected"===e.status);if(s.length){for(const e of s);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const r=[];for(const n of t)"fulfilled"===n.status&&r.push(n.value);return r})(l),await this.createAndPoll(e,{file_ids:c})}},mn=class extends He{create(e,t,s){return this._client.post(Ge`/vector_stores/${e}/files`,{body:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(Ge`/vector_stores/${r}/files/${e}`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){const{vector_store_id:r,...n}=t;return this._client.post(Ge`/vector_stores/${r}/files/${e}`,{body:n,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(Ge`/vector_stores/${e}/files`,ke,{query:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t,s){const{vector_store_id:r}=t;return this._client.delete(Ge`/vector_stores/${r}/files/${e}`,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}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=js([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const n=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse(),i=n.data;switch(i.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=n.response.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await R(e);break;case"failed":case"completed":return i}}}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(Ge`/vector_stores/${r}/files/${e}/content`,Se,{...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}},gn=class extends He{constructor(){super(...arguments),this.files=new mn(this._client),this.fileBatches=new yn(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Ge`/vector_stores/${e}`,{...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(Ge`/vector_stores/${e}`,{body:t,...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",ke,{query:e,...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/vector_stores/${e}`,{...t,headers:js([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,s){return this._client.getAPIList(Ge`/vector_stores/${e}/search`,Se,{body:t,method:"post",...s,headers:js([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};gn.Files=mn,gn.FileBatches=yn;var bn,wn,An,vn,In,$n,xn,Pn=class extends He{create(e,t){return this._client.post("/videos",ze({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(Ge`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",Oe,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Ge`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",ze({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},s){return this._client.get(Ge`/videos/${e}/content`,{query:t,...s,headers:js([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",ze({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",ze({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(Ge`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,s){return this._client.post(Ge`/videos/${e}/remix`,Le({body:t,...s,__security:{bearerAuth:!0}},this._client))}},Sn=class extends He{constructor(){super(...arguments),bn.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,s,r=this._client.webhookSecret,n=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");t(this,bn,"m",wn).call(this,r);const i=js([s]).values,a=t(this,bn,"m",An).call(this,i,"webhook-signature"),o=t(this,bn,"m",An).call(this,i,"webhook-timestamp"),c=t(this,bn,"m",An).call(this,i,"webhook-id"),l=parseInt(o,10);if(isNaN(l))throw new w("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-l>n)throw new w("Webhook timestamp is too old");if(l>u+n)throw new w("Webhook timestamp is too new");const h=a.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),d=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),p=c?`${c}.${o}.${e}`:`${o}.${e}`,_=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const t of h)try{const e=Buffer.from(t,"base64");if(await crypto.subtle.verify("HMAC",_,e,(new TextEncoder).encode(p)))return}catch{continue}throw new w("The given webhook signature does not match the expected signature")}};bn=/* @__PURE__ */new WeakSet,wn=function(e){if("string"!=typeof e||0===e.length)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")},An=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(null==s)throw new Error(`Missing required header: ${t}`);return s};var kn=class{constructor({baseURL:t=fr("OPENAI_BASE_URL"),apiKey:s=fr("OPENAI_API_KEY")??null,adminAPIKey:r=fr("OPENAI_ADMIN_KEY")??null,organization:n=fr("OPENAI_ORG_ID")??null,project:a=fr("OPENAI_PROJECT_ID")??null,webhookSecret:o=fr("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:c,...l}={}){vn.add(this),$n.set(this,void 0),this.completions=new wr(this),this.chat=new Zt(this),this.embeddings=new Pr(this),this.files=new Rr(this),this.images=new Vr(this),this.audio=new Cs(this),this.moderations=new Qr(this),this.models=new Gr(this),this.fineTuning=new zr(this),this.graders=new Dr(this),this.vectorStores=new gn(this),this.webhooks=new Sn(this),this.beta=new br(this),this.batches=new qs(this),this.uploads=new fn(this),this.admin=new ks(this),this.responses=new ln(this),this.realtime=new en(this),this.conversations=new xr(this),this.evals=new Or(this),this.containers=new Ir(this),this.skills=new pn(this),this.videos=new Pn(this);const u={apiKey:s,adminAPIKey:r,organization:n,project:a,webhookSecret:o,workloadIdentity:c,...l,baseURL:t||"https://api.openai.com/v1"};if(s&&c)throw new i("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!s&&!r&&!c)throw new i("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!u.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new i("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");this.baseURL=u.baseURL,this.timeout=u.timeout??In.DEFAULT_TIMEOUT,this.logger=u.logger??console;const h="warn";this.logLevel=h,this.logLevel=ue(u.logLevel,"ClientOptions.logLevel",this)??ue(fr("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??h,this.fetchOptions=u.fetchOptions,this.maxRetries=u.maxRetries??2,this.fetch=u.fetch??C(),e(this,$n,D,"f");const d=fr("OPENAI_CUSTOM_HEADERS");if(d){const e={};for(const t of d.split("\n")){const s=t.indexOf(":");s>=0&&(e[t.substring(0,s).trim()]=t.substring(s+1).trim())}u.defaultHeaders=js([e,u.defaultHeaders])}this._options=u,c&&(this._workloadIdentityAuth=new Ee(c,this.fetch)),this.apiKey="string"==typeof s?s:null,this.adminAPIKey=r,this.organization=n,this.project=a,this.webhookSecret=o}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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!e.get("authorization")&&!e.get("api-key")&&!(t.has("authorization")||t.has("api-key")||this._workloadIdentityAuth&&s.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return js([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){return this._workloadIdentityAuth?js([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]):null!=this.apiKey?js([{Authorization:`Bearer ${this.apiKey}`}]):void 0}async adminAPIKeyAuth(e){if(null!=this.adminAPIKey)return js([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return function(e){return function(e,t={}){let s=e;const r=function(e=te){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||te.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=N;if(void 0!==e.format){if(!U(W,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const r=W[s];let n,i=te.filter;if(("function"==typeof e.filter||$(e.filter))&&(i=e.filter),n=e.arrayFormat&&e.arrayFormat in Z?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":te.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=void 0===e.allowDots?1==!!e.encodeDotInKeys||te.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:te.addQueryPrefix,allowDots:a,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:te.allowEmptyArrays,arrayFormat:n,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:te.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?te.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:te.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:te.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:te.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:te.encodeValuesOnly,filter:i,format:s,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:te.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:te.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:te.strictNullHandling}}(t);let n,i;"function"==typeof r.filter?(i=r.filter,s=i("",s)):$(r.filter)&&(i=r.filter,n=i);const a=[];if("object"!=typeof s||null===s)return"";const o=Z[r.arrayFormat],c="comma"===o&&r.commaRoundTrip;n||(n=Object.keys(s)),r.sort&&n.sort(r.sort);const l=/* @__PURE__ */new WeakMap;for(let d=0;d<n.length;++d){const e=n[d];r.skipNulls&&null===s[e]||ee(a,re(s[e],e,o,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}const u=a.join(r.delimiter);let h=!0===r.addQueryPrefix?"?":"";return r.charsetSentinel&&("iso-8859-1"===r.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}(e,{arrayFormat:"brackets"})}(e)}getUserAgent(){return`${this.constructor.name}/JS ${j}`}defaultIdempotencyKey(){return`stainless-node-retry-${s()}`}makeStatusError(e,t,s,r){return a.generate(e,t,s,r)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(s){if(s instanceof i)throw s;throw new i(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if("string"!=typeof t||!t)throw new i(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,s,r){const n=!t(this,vn,"m",xn).call(this)&&r||this.baseURL,i=(e=>I.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return S(a)&&S(o)||(s={...o,...a,...s}),"object"==typeof s&&s&&!Array.isArray(s)&&(i.search=this.stringifyQuery(s)),i.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&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(s=>({method:e,path:t,...s})))}request(e,t=null){return new $e(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const i=await e,a=i.maxRetries??this.maxRetries;null==t&&(t=a),await this.prepareOptions(i);const{req:u,url:h,timeout:d}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(u,{url:h,options:i});const p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=void 0===s?"":`, retryOf: ${s}`,f=Date.now();if(fe(this).debug(`[${p}] sending request`,ge({retryOfRequestLogID:s,method:i.method,url:h,options:i,headers:u.headers})),i.signal?.aborted)throw new o;const y=i.__security??{bearerAuth:!0},m=new AbortController,g=await this.fetchWithAuth(h,u,d,m,y).catch(n),b=Date.now();if(g instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new o;const n=r(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(t)return fe(this).info(`[${p}] connection ${n?"timed out":"failed"} - ${e}`),fe(this).debug(`[${p}] connection ${n?"timed out":"failed"} (${e})`,ge({retryOfRequestLogID:s,url:h,durationMs:b-f,message:g.message})),this.retryRequest(i,t,s??p);if(fe(this).info(`[${p}] connection ${n?"timed out":"failed"} - error; no more retries left`),fe(this).debug(`[${p}] connection ${n?"timed out":"failed"} (error; no more retries left)`,ge({retryOfRequestLogID:s,url:h,durationMs:b-f,message:g.message})),g instanceof A||g instanceof v)throw g;if(n)throw new l;throw new c({message:On(g),cause:g})}const w=`[${p}${_}${[...g.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${u.method} ${h} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${b-f}ms`;if(!g.ok){if(401===g.status&&this._workloadIdentityAuth&&y.bearerAuth&&!i.__metadata?.hasStreamingBody&&!i.__metadata?.workloadIdentityTokenRefreshed)return await M(g.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...i,__metadata:{...i.__metadata,workloadIdentityTokenRefreshed:!0}},t,s??p);const e=await this.shouldRetry(g);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await M(g.body),fe(this).info(`${w} - ${e}`),fe(this).debug(`[${p}] response error (${e})`,ge({retryOfRequestLogID:s,url:g.url,status:g.status,headers:g.headers,durationMs:b-f})),this.retryRequest(i,t,s??p,g.headers)}const r=e?"error; no more retries left":"error; not retryable";fe(this).info(`${w} - ${r}`);const a=await g.text().catch(e=>n(e).message),o=(e=>{try{return JSON.parse(e)}catch(t){return}})(a),c=o?void 0:a;throw fe(this).debug(`[${p}] response error (${r})`,ge({retryOfRequestLogID:s,url:g.url,status:g.status,headers:g.headers,message:c,durationMs:Date.now()-f})),this.makeStatusError(g.status,o,c,g.headers)}return fe(this).info(w),fe(this).debug(`[${p}] response start`,ge({retryOfRequestLogID:s,url:g.url,status:g.status,headers:g.headers,durationMs:b-f})),{response:g,options:i,controller:m,requestLogID:p,retryOfRequestLogID:s,startTime:f}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(t=>({method:"get",path:e,...t})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Pe(this,s,e)}async fetchWithAuth(e,t,s,r,n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&n.bearerAuth){const e=t.headers,s=e.get("Authorization");if(!s||"Bearer workload-identity-auth"===s){const t=await this._workloadIdentityAuth.getToken();e.set("Authorization",`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,s,r)}async fetchWithTimeout(e,t,s,r){const{signal:n,method:i,...a}=t||{},o=this._makeAbort(r);n&&n.addEventListener("abort",o,{once:!0});const c=setTimeout(o,s),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,u={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(u.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,s,r){let n;const i=r?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(n=e)}const a=r?.get("retry-after");if(a&&!n){const e=parseFloat(a);n=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(void 0===n){const s=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,s)}return await R(n),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:r,path:n,query:a,defaultBaseURL:o}=s,c=this.buildURL(n,a,o);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new i(`${e} must be an integer`);if(t<0)throw new i(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:u,isStreamingBody:h}=this.buildBody({options:s});return h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:t}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:r}){let n={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),n[this.idempotencyHeader]=e.idempotencyKey);const i=js([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...O??(O=E()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:s}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const r=js([s]),n=void 0!==globalThis.ReadableStream&&e instanceof globalThis.ReadableStream,i=!n&&("string"==typeof e||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||void 0!==globalThis.Blob&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||n?{bodyHeaders:void 0,body:e,isStreamingBody:!i}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:L(e),isStreamingBody:!0}:"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...t(this,$n,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}};function On(e){if(function(e){let t=e;for(let s=0;s<8&&t&&"object"==typeof t;s++){const e=t;if("UND_ERR_INVALID_ARG"===e.code&&"string"==typeof e.message&&e.message.includes("invalid onRequestStart method"))return!0;t=e.cause}return!1}(e))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function Rn(e){let t=3735928559,s=1103547991;for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(s>>>0).toString(36)+(t>>>0).toString(36)}function jn(e){if(void 0===e)return;const t=Array.from(e);return t.length<=64?e:t.slice(0,64).join("")}In=kn,$n=/* @__PURE__ */new WeakMap,vn=/* @__PURE__ */new WeakSet,xn=function(){return"https://api.openai.com/v1"!==this.baseURL},kn.OpenAI=In,kn.DEFAULT_TIMEOUT=6e5,kn.OpenAIError=i,kn.APIError=a,kn.APIConnectionError=c,kn.APIConnectionTimeoutError=l,kn.APIUserAbortError=o,kn.NotFoundError=p,kn.ConflictError=_,kn.RateLimitError=y,kn.BadRequestError=u,kn.AuthenticationError=h,kn.InternalServerError=m,kn.PermissionDeniedError=d,kn.UnprocessableEntityError=f,kn.InvalidWebhookSignatureError=w,kn.toFile=async function(e,t,s){if(Ke(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Ue(e))(e=await e))return e instanceof File?e:Te([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Te(await Fe(r),t,s)}const r=await Fe(e);if(t||(t=Ce(e)),!s?.type){const e=r.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(s={...s,type:e})}return Te(r,t,s)},kn.Completions=wr,kn.Chat=Zt,kn.Embeddings=Pr,kn.Files=Rr,kn.Images=Vr,kn.Audio=Cs,kn.Moderations=Qr,kn.Models=Gr,kn.FineTuning=zr,kn.Graders=Dr,kn.VectorStores=gn,kn.Webhooks=Sn,kn.Beta=br,kn.Batches=qs,kn.Uploads=fn,kn.Admin=ks,kn.Responses=ln,kn.Realtime=en,kn.Conversations=xr,kn.Evals=Or,kn.Containers=Ir,kn.Skills=pn,kn.Videos=Pn;export{Rn as n,kn as r,jn as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{a as e,n as t,r as o,t as n}from"./github-copilot-headers-n6Dqf6oj.js";import{h as s,m as r,p as a}from"./BuilderAgentPane-Cf2EQd0U.js";import{t as i}from"./deferred-tools-8QtAASke.js";import{c as p,d as c,f as l,h as u,i as d,l as m,m as f,p as g,s as h,t as _,u as y}from"./transform-messages-C1f-L9_8.js";import{n as x,t as k}from"./error-body-B13t5xBI.js";import{n as v,r as I,t as b}from"./openai-prompt-cache-Mi5dPc0-.js";function w(e,t){const o={v:1,id:e};return t&&(o.phase=t),JSON.stringify(o)}function T(e){if(e){if(e.startsWith("{"))try{const t=JSON.parse(e);if(1===t.v&&"string"==typeof t.id)return"commentary"===t.phase||"final_answer"===t.phase?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function R(e,t){const o=t.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=t.filter(e=>"image"===e.type),s=o.length>0;if(0===n.length||!e.input.includes("image"))return g(s?o:n.length>0?"(see attached image)":"(no tool output)");const r=[];s&&r.push({type:"input_text",text:g(o)});for(const a of n)r.push({type:"input_image",detail:"auto",image_url:`data:${a.mimeType};base64,${a.data}`});return r}function S(e,t){const o=void 0!==t?.strict&&t.strict,n=t?.supportsStrictMode??!0,s=t?.supportsOpenAIGrammarTools??!1;return e.map(e=>{const r=c(e,s);if(r)return{type:"custom",name:e.name,description:e.description,format:{type:"grammar",syntax:r.format,definition:r.definition},...t?.deferLoading?{defer_loading:!0}:{}};const a=l(e,n)??o,i={type:"function",name:e.name,description:e.description,parameters:y(e,!0===a),...t?.deferLoading?{defer_loading:!0}:{}};return n&&(i.strict=a),i})}function $(e){const t=e.customInput?.property;if(void 0===t)return"";const o=e.arguments[t];return"string"==typeof o?o:""}function C(e,t,o){const n=e.customInput;if(!n)return;const s=h(n.jsonBuffer,n.property,t,o);return e.arguments={[n.property]:t},s}var M=/* @__PURE__ */new Set(["openai","openai-codex","opencode"]);function O(e,t){if(!e)return!1;const o=t.toLowerCase();for(const[n,s]of Object.entries(e))if(n.toLowerCase()===o&&null!==s&&s.trim().length>0)return!0;return!1}function A(e,t,o){if(t)return t;if(O(o,"authorization")||O(o,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function P(e){return"openrouter"===e.provider||e.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function E(e,t){return e||("long"===o("PI_CACHE_RETENTION",t)?"long":"short")}function J(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,sessionAffinityFormat:e.compat?.sessionAffinityFormat??P(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1}}function j(e,t){return"long"===t&&e.supportsLongCacheRetention?"24h":void 0}var L=(o,r,c)=>{const l=new s;return(async()=>{const s={role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const d=A(o.provider,c?.apiKey,c?.headers),h="none"===E(c?.cacheRetention,c?.env)?void 0:c?.sessionId,y=J(o),x=p(r.tools,y.supportsOpenAIGrammarTools),k=function(e,o,s,r,a,i){const p=J(e),c={...e.headers};if("github-copilot"===e.provider){const e=t(o.messages),s=n({messages:o.messages,hasImages:e});Object.assign(c,s)}return i&&("openrouter"===p.sessionAffinityFormat?c["x-session-id"]=i:("openai"===p.sessionAffinityFormat&&(c.session_id=i),c["x-client-request-id"]=i)),r&&Object.assign(c,r),new I({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:c})}(o,r,d,c?.headers,c?.fetch,h);let O=function(e,t,o,n=J(e),s=p(t.tools,n.supportsOpenAIGrammarTools)){const r=n.supportsAdditionalTools?"additional-tools":n.supportsToolSearch?"tool-search":void 0,a=i(t,void 0!==r),c=function(e,t,o,n){const s=[],r=/* @__PURE__ */new Set,a=e=>{const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return(t.length>64?t.slice(0,64):t).replace(/_+$/,"")},i=_(t.messages,e,(t,n,s)=>{if(!o.has(e.provider))return a(t);if(!t.includes("|"))return a(t);const[r,i]=t.split("|"),p=a(r);let c=s.provider!==e.provider||s.api!==e.api?(e=>{const t=`fc_${v(e)}`;return t.length>64?t.slice(0,64):t})(i):a(i);return c.startsWith("fc_")||(c=a(`fc_${c}`)),`${p}|${c}`});if((n?.includeSystemPrompt??!0)&&t.systemPrompt){const o=e.compat,n=e.reasoning&&!1!==o?.supportsDeveloperRole?"developer":"system";s.push({role:n,content:g(t.systemPrompt)})}let p=0;for(const c of i){if("user"===c.role)if("string"==typeof c.content)s.push({role:"user",content:[{type:"input_text",text:g(c.content)}]});else{const e=c.content.map(e=>"text"===e.type?{type:"input_text",text:g(e.text)}:{type:"input_image",detail:"auto",image_url:`data:${e.mimeType};base64,${e.data}`});if(0===e.length)continue;s.push({role:"user",content:e})}else if("assistant"===c.role){const t=[],o=c,r=o.provider===e.provider&&o.api===e.api,a=r&&o.model===e.id,i=r&&o.model!==e.id;let l=0;for(const e of c.content)if("thinking"===e.type){if(e.thinkingSignature){const o=JSON.parse(e.thinkingSignature);t.push(o)}}else if("text"===e.type){const o=e,n=T(o.textSignature),s=0===l?`msg_pi_${p}`:`msg_pi_${p}_${l}`;l++;let r=n?.id;r?r.length>64&&(r=`msg_${v(r)}`):r=s,t.push({type:"message",role:"assistant",content:[{type:"output_text",text:g(o.text),annotations:[]}],status:"completed",id:r,phase:n?.phase})}else if("toolCall"===e.type){const o=e,[s,r]=o.id.split("|"),p=n?.grammarToolInputProperties?.get(o.name);let c=r;(i&&c?.startsWith("fc_")||void 0===p&&!c?.startsWith("fc_"))&&(c=void 0);const l=a||!0===n?.deferredTools?.has(o.name);void 0!==p?t.push({type:"custom_tool_call",id:c,call_id:s,name:o.name,input:g(m(o.name,o.arguments,p)),...l&&void 0!==o.namespace?{namespace:o.namespace}:{}}):t.push({type:"function_call",id:c,call_id:s,name:o.name,arguments:JSON.stringify(o.arguments),...l&&void 0!==o.namespace?{namespace:o.namespace}:{}})}if(0===t.length)continue;s.push(...t)}else if("toolResult"===c.role){const[t]=c.toolCallId.split("|"),o=R(e,c.content);n?.grammarToolInputProperties?.has(c.toolName)?s.push({type:"custom_tool_call_output",call_id:t,output:o}):s.push({type:"function_call_output",call_id:t,output:o});const a=[];for(const e of c.addedToolNames??[]){const t=n?.deferredTools?.get(e);t&&!r.has(e)&&(r.add(e),a.push(t))}if(a.length>0&&"additional-tools"===n?.deferredToolsMode)s.push({type:"additional_tools",role:"developer",tools:S(a,n.toolOptions)});else if(a.length>0&&"tool-search"===n?.deferredToolsMode){const e=a.map(e=>e.name),t=`pi_tool_load_${v(`${c.toolCallId}:${e.join(",")}`)}`;s.push({type:"tool_search_call",call_id:t,execution:"client",status:"completed",arguments:{query:e.join(" "),limit:e.length}}),s.push({type:"tool_search_output",call_id:t,execution:"client",status:"completed",tools:S(a,{...n.toolOptions,deferLoading:!0})})}}p++}return s}(e,t,M,{grammarToolInputProperties:s,deferredTools:a.deferred,deferredToolsMode:r,toolOptions:{supportsStrictMode:n.supportsStrictMode,supportsOpenAIGrammarTools:n.supportsOpenAIGrammarTools}}),l=E(o?.cacheRetention,o?.env),u="none"===l&&n.supportsExplicitPromptCacheMode,d={model:e.id,input:c,stream:!0,prompt_cache_key:"none"===l?void 0:b(o?.sessionId),prompt_cache_retention:j(n,l),prompt_cache_options:u?{mode:"explicit"}:void 0,store:!1};return o?.maxTokens&&(d.max_output_tokens=Math.max(o.maxTokens,16)),void 0!==o?.temperature&&(d.temperature=o?.temperature),void 0!==o?.serviceTier&&(d.service_tier=o.serviceTier),a.immediate.length>0&&(d.tools=S(a.immediate,{supportsStrictMode:n.supportsStrictMode,supportsOpenAIGrammarTools:n.supportsOpenAIGrammarTools})),void 0!==o?.toolChoice&&(d.tool_choice=o.toolChoice),e.reasoning&&(o?.reasoningEffort||o?.reasoningSummary?(d.reasoning={effort:o?.reasoningEffort?e.thinkingLevelMap?.[o.reasoningEffort]??o.reasoningEffort:"medium",summary:o?.reasoningSummary||"auto"},d.include=["reasoning.encrypted_content"]):"github-copilot"!==e.provider&&null!==e.thinkingLevelMap?.off&&(d.reasoning={effort:e.thinkingLevelMap?.off??"none"}),"xai"===e.provider&&(d.include=["reasoning.encrypted_content"])),o?.samplingParams&&Object.assign(d,o.samplingParams),d}(o,r,c,y,x);const P=await(c?.onPayload?.(O,o));void 0!==P&&(O=P);const L={...c?.signal?{signal:c.signal}:{},...void 0!==c?.timeoutMs?{timeout:c.timeoutMs}:{},maxRetries:0},{data:N,response:W}=await f(()=>k.responses.create(O,L).withResponse(),{maxRetries:c?.maxRetries,maxRetryDelayMs:c?.maxRetryDelayMs,signal:c?.signal});if(await(c?.onResponse?.({status:W.status,headers:u(W.headers)},o)),l.push({type:"start",partial:s}),await async function(t,o,n,s,r){let i=!1;const p=/* @__PURE__ */new Map,c=/* @__PURE__ */new Map,l=e=>{"message"===e.type&&"final_answer"===e.phase&&(o.stopReason="stop")},u=(e,t)=>{const o=p.get(e);return o?.type===t?o:void 0},d=(e,t)=>{void 0!==t&&n.push({type:"toolcall_delta",contentIndex:e.contentIndex,delta:t,partial:o})},m=(e,t)=>{if("reasoning"===t.type){const t={type:"thinking",thinking:""};o.content.push(t);const s={type:"thinking",block:t,contentIndex:o.content.length-1};return p.set(e,s),n.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if("message"===t.type){l(t);const s={type:"text",text:""};o.content.push(s);const r={type:"text",block:s,contentIndex:o.content.length-1};return p.set(e,r),n.push({type:"text_start",contentIndex:r.contentIndex,partial:o}),r}if("function_call"===t.type){const s={type:"toolCall",id:`${t.call_id}|${t.id}`,name:t.name,arguments:{},...void 0!==t.namespace?{namespace:t.namespace}:{},partialJson:t.arguments||""};o.content.push(s);const r={type:"toolCall",block:s,contentIndex:o.content.length-1};return p.set(e,r),n.push({type:"toolcall_start",contentIndex:r.contentIndex,partial:o}),r}if("custom_tool_call"===t.type){const s=r?.grammarToolInputProperties?.get(t.name)??"input",a=t.input||"",i={type:"toolCall",id:`${t.call_id}|${t.id}`,name:t.name,arguments:{[s]:a},...void 0!==t.namespace?{namespace:t.namespace}:{},customInput:{property:s,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(i);const c={type:"toolCall",block:i,contentIndex:o.content.length-1};return p.set(e,c),n.push({type:"toolcall_start",contentIndex:c.contentIndex,partial:o}),c}},f=(e,t)=>p.get(e)??m(e,t),g=e=>{if(i=!0,(e=>{for(const t of e){if("reasoning"!==t.type||!t.encrypted_content)continue;const e=c.get(t.id);if(!e?.thinkingSignature)continue;const o=JSON.parse(e.thinkingSignature);o.encrypted_content||(e.thinkingSignature=JSON.stringify({...o,encrypted_content:t.encrypted_content}))}})(e.output??[]),e?.id&&(o.responseId=e.id),e?.usage){const t=e.usage.input_tokens_details,n=t?.cached_tokens||0,s=t?.cache_write_tokens||0;o.usage={input:Math.max(0,(e.usage.input_tokens||0)-n-s),output:e.usage.output_tokens||0,cacheRead:n,cacheWrite:s,reasoning:e.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:e.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(a(s,o.usage),r?.applyServiceTierPricing){const t=r.resolveServiceTier?r.resolveServiceTier(e?.service_tier,r.serviceTier):e?.service_tier??r.serviceTier;r.applyServiceTierPricing(o.usage,t)}const t=e?.status,n=e?.incomplete_details,p="string"==typeof n?.reason?n.reason:void 0;o.rawStopReason=p?`${t}.${p}`:t;const l=function(e,t){if(!e)return{stopReason:"stop"};switch(e){case"completed":case"in_progress":case"queued":return{stopReason:"stop"};case"incomplete":return"max_output_tokens"===t?{stopReason:"length"}:{stopReason:"error",errorMessage:t?`Response incomplete: ${t}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};default:throw new Error(`Unhandled stop reason: ${e}`)}}(t,p);o.stopReason=l.stopReason,o.errorMessage=l.errorMessage,o.content.some(e=>"toolCall"===e.type)&&"stop"===o.stopReason&&(o.stopReason="toolUse")};for await(const a of t)if("response.created"===a.type)o.responseId=a.response.id;else if("response.output_item.added"===a.type)m(a.output_index,a.item);else if("response.reasoning_summary_text.delta"===a.type){const e=u(a.output_index,"thinking");if(!e)continue;e.block.thinking+=a.delta,n.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:a.delta,partial:o})}else if("response.reasoning_summary_part.done"===a.type){const e=u(a.output_index,"thinking");if(!e)continue;e.block.thinking+="\n\n",n.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:"\n\n",partial:o})}else if("response.reasoning_text.delta"===a.type){const e=u(a.output_index,"thinking");if(!e)continue;e.block.thinking+=a.delta,n.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:a.delta,partial:o})}else if("response.output_text.delta"===a.type){const e=u(a.output_index,"text");if(!e)continue;e.block.text+=a.delta,n.push({type:"text_delta",contentIndex:e.contentIndex,delta:a.delta,partial:o})}else if("response.refusal.delta"===a.type){const e=u(a.output_index,"text");if(!e)continue;e.block.text+=a.delta,n.push({type:"text_delta",contentIndex:e.contentIndex,delta:a.delta,partial:o})}else if("response.function_call_arguments.delta"===a.type){const t=u(a.output_index,"toolCall");if(!t||void 0===t.block.partialJson)continue;t.block.partialJson+=a.delta,t.block.arguments=e(t.block.partialJson),d(t,a.delta)}else if("response.function_call_arguments.done"===a.type){const t=u(a.output_index,"toolCall");if(!t||void 0===t.block.partialJson)continue;const o=t.block.partialJson;if(t.block.partialJson=a.arguments,t.block.arguments=e(t.block.partialJson),a.arguments.startsWith(o)){const e=a.arguments.slice(o.length);e.length>0&&d(t,e)}}else if("response.custom_tool_call_input.delta"===a.type){const e=u(a.output_index,"toolCall");if(!e||!e.block.customInput)continue;d(e,C(e.block,$(e.block)+a.delta,!1))}else if("response.custom_tool_call_input.done"===a.type){const e=u(a.output_index,"toolCall");if(!e||!e.block.customInput)continue;d(e,C(e.block,a.input,!0))}else if("response.output_item.done"===a.type){const t=a.item;l(t);const s=f(a.output_index,t);if("reasoning"===t.type&&"thinking"===s?.type){const e=t.summary?.map(e=>e.text).join("\n\n")||"",r=t.content?.map(e=>e.text).join("\n\n")||"";s.block.thinking=e||r||s.block.thinking,s.block.thinkingSignature=JSON.stringify(t),c.set(t.id,s.block),n.push({type:"thinking_end",contentIndex:s.contentIndex,content:s.block.thinking,partial:o}),p.delete(a.output_index)}else"message"===t.type&&"text"===s?.type?(s.block.text=t.content?.map(e=>"output_text"===e.type?e.text:e.refusal).join("")||"",s.block.textSignature=w(t.id,t.phase??void 0),n.push({type:"text_end",contentIndex:s.contentIndex,content:s.block.text,partial:o}),p.delete(a.output_index)):"function_call"===t.type&&"toolCall"===s?.type&&void 0!==s.block.partialJson?(s.block.arguments=e(t.arguments||s.block.partialJson||"{}"),void 0!==t.namespace&&(s.block.namespace=t.namespace),delete s.block.partialJson,n.push({type:"toolcall_end",contentIndex:s.contentIndex,toolCall:s.block,partial:o}),p.delete(a.output_index)):"custom_tool_call"===t.type&&"toolCall"===s?.type&&s.block.customInput&&(d(s,C(s.block,t.input??$(s.block),!0)),void 0!==t.namespace&&(s.block.namespace=t.namespace),delete s.block.customInput,n.push({type:"toolcall_end",contentIndex:s.contentIndex,toolCall:s.block,partial:o}),p.delete(a.output_index))}else if("response.completed"===a.type||"response.incomplete"===a.type)g(a.response);else{if("error"===a.type)throw new Error(`Error Code ${a.code}: ${a.message}`||"Unknown error");if("response.failed"===a.type){i=!0,o.rawStopReason=a.response?.status;const e=a.response?.error,t=a.response?.incomplete_details,n=e?`${e.code||"unknown"}: ${e.message||"no message"}`:t?.reason?`incomplete: ${t.reason}`:"Unknown error (no error details in response)";throw new Error(n)}}if(!i)throw new Error("OpenAI Responses stream ended before a terminal response event")}(N,s,l,o,{serviceTier:c?.serviceTier,grammarToolInputProperties:x,applyServiceTierPricing:(e,t)=>function(e,t,o){const n=function(e,t){switch(t){case"flex":return.5;case"priority":return"gpt-5.5"===e.id?2.5:2;default:return 1}}(o,t);1!==n&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}(e,t,o)}),c?.signal?.aborted)throw new Error("Request was aborted");if("pending"===s.stopReason)throw new Error("OpenAI Responses stream ended without a stop reason");if("aborted"===s.stopReason||"error"===s.stopReason)throw new Error(s.errorMessage||"An unknown error occurred");l.push({type:"done",reason:s.stopReason,message:s}),l.end()}catch(d){for(const e of s.content)delete e.index,delete e.partialJson,delete e.customInput;s.stopReason=c?.signal?.aborted?"aborted":"error",s.errorMessage=function(e){return k(x(e),"OpenAI API error")}(d),l.push({type:"error",reason:s.stopReason,error:s}),l.end()}})(),l},N=(e,t,o)=>{A(e.provider,o?.apiKey,o?.headers);const n=d(e,t,o,o?.apiKey),s=o?.reasoning?r(e,o.reasoning):void 0;return L(e,t,{...n,reasoningEffort:"off"===s?void 0:s})};export{L as stream,N as streamSimple};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e){const t={};for(const[r,n]of e.entries())t[r]=n;return t}function t(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))null!==n&&(t[r]=n);return Object.keys(t).length>0?t:void 0}function r(e){return e instanceof Error&&"status"in e&&"headers"in e&&(void 0===e.status||"number"==typeof e.status)&&(void 0===e.headers||e.headers instanceof Headers)}function n(e){const t=e.headers?.get("x-should-retry");return"true"===t||"false"!==t&&(void 0===e.status||408===e.status||409===e.status||429===e.status||"number"==typeof e.status&&e.status>=500)}function o(e,t,r){const n=t??6e4;if(n>0&&e>n)throw new Error(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s). ${r}`);return e}function s(e,t,r){const n=e.headers?.get("retry-after-ms");if(n){const t=Number.parseFloat(n);if(!Number.isNaN(t))return o(t,r,e.message)}const s=e.headers?.get("retry-after");if(s){const t=Number.parseFloat(s);return o(Number.isNaN(t)?Date.parse(s)-Date.now():1e3*t,r,e.message)}return 1e3*Math.min(.5*2**t,8)*(1-.25*Math.random())}function a(){const e=/* @__PURE__ */new Error("Request aborted");return e.name="AbortError",e}function i(e,t){return new Promise((r,n)=>{if(t?.aborted)return void n(a());const o=()=>{clearTimeout(s),n(a())},s=setTimeout(()=>{t?.removeEventListener("abort",o),r()},Math.max(0,e));t?.addEventListener("abort",o,{once:!0})})}async function u(e,t={}){const o=t.maxRetries??0;let u=o;for(;;)try{return await e()}catch(c){if(t.signal?.aborted)throw a();if(u<=0||!r(c)||!n(c))throw c;const e=o-u;u--,await i(s(c,e,t.maxRetryDelayMs),t.signal)}}function c(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});var l=class extends Error{},p=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function f(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function m(e){if(!f(e))return!1;const t="string"==typeof e.type?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes("object")||t.includes("array")||void 0!==e.properties||void 0!==e.items}function d(e){return!!f(e)&&(!!("null"===e.type||Array.isArray(e.type)&&e.type.includes("null"))||!!(null===e.const||Array.isArray(e.enum)&&e.enum.includes(null))||Array.isArray(e.anyOf)&&e.anyOf.some(e=>d(e)))}function g(e){if(!f(e))throw new l("boolean schemas are unsupported");for(const s of p)if(void 0!==e[s])throw new l(`${s} schemas are unsupported`);if(void 0!==e.anyOf){if(!Array.isArray(e.anyOf)||0===e.anyOf.length)throw new l("anyOf must contain at least one schema");for(const t of e.anyOf){if(m(t))throw new l("object and array unions are unsupported");g(t)}}if(void 0!==e.items){if(Array.isArray(e.items))throw new l("tuple schemas are unsupported");g(e.items)}const t="object"===e.type;if(void 0!==e.properties&&!t)throw new l("properties require type object");if(!t)return;if(void 0!==e.additionalProperties&&!1!==e.additionalProperties)throw new l("schema-valued or true additionalProperties is unsupported");if(void 0!==e.properties&&!f(e.properties))throw new l("object properties must be a schema map");if(void 0!==e.required&&(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e)))throw new l("object required must be a string array");const r=e.properties??{},n=Object.keys(r),o=new Set(Array.isArray(e.required)?e.required:[]);if([...o].some(e=>!n.includes(e)))throw new l("required contains an unknown property");for(const[s,a]of Object.entries(r))g(a),o.has(s)||d(a)||(r[s]={anyOf:[a,{type:"null"}]});e.required=n,e.additionalProperties=!1}function h(e){const t=structuredClone(e);if(!f(t))throw new l("root schema must have type object");if(g(t),"object"!==t.type)throw new l("root schema must have type object");return t}function y(e,t){return!0===t?h(e.parameters):e.parameters}function w(e,t,r){const n=t[r];if("string"!=typeof n)throw new Error(`Grammar tool call "${e}" requires argument "${r}" to be a string.`);return n}function x(e,t,r,n){if(e.closed){if(n&&r===e.input)return;throw new Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!r.startsWith(e.input))throw new Error(`grammar tool input for property "${t}" changed non-monotonically`);const o=r.slice(e.input.length);if(!n&&0===o.length)return;let s="";return e.started||(s+=`{${JSON.stringify(t)}:"`,e.started=!0),s+=JSON.stringify(o).slice(1,-1),e.input=r,n&&(s+='"}',e.closed=!0),s}function b(e){const t=e.parameters;if("object"!==t.type)throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(t.required)||1!==t.required.length||"string"!=typeof t.required[0])throw new Error("grammar constrained sampling requires exactly one required string property");const r=t.required[0];if(!t.properties?.[r])throw new Error(`grammar constrained sampling requires a properties entry for ${r}`);if("string"!==t.properties[r]?.type)throw new Error(`grammar constrained sampling property ${r} must have type string`);return r}function v(e,t){const r=e.constrainedSampling;if(r&&"json_schema"===r.type){if(t)try{return h(e.parameters),!0}catch(n){if(!(n instanceof l))throw n;if("require"!==r.strict)return;throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${n.message}.`)}if("require"===r.strict)throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function k(e,t){const r=e.constrainedSampling;if(!r||"grammar"!==r.type)return;if(!t)return;const n=r.variants.openai_lark,o=r.variants.openai_regex,s="string"==typeof n&&n.trim().length>0,a="string"==typeof o&&o.trim().length>0;if(!s&&!a)throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:s?"lark":"regex",definition:s?n:o,inputProperty:b(e)}}catch(i){const t=i instanceof Error?i.message:String(i);throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${t}.`)}}function T(e,t){const r=/* @__PURE__ */new Map;for(const n of e??[]){const e=k(n,t);e&&r.set(n.name,e.inputProperty)}return r}function A(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function M(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function q(e){return Math.ceil(e.length/4)}function E(e){return Math.ceil(function(e){if("string"==typeof e)return e.length;let t=0;for(const r of e)t+="text"===r.type?r.text.length:4800;return t}(e)/4)}function R(e){let t=0;if("user"===e.role)return E(e.content);if("toolResult"===e.role)return E(e.content);for(const r of e.content)"text"===r.type?t+=r.text.length:"thinking"===r.type?t+=r.thinking.length:t+=r.name.length+M(r.arguments).length;return Math.ceil(t/4)}function N(e){const t=function(e){let t,r=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const o=e[n];if("assistant"===o.role){const e=o;e.timestamp>=r&&"aborted"!==e.stopReason&&"error"!==e.stopReason&&A(e.usage)>0&&(t={usage:e.usage,index:n})}r=Math.max(r,o.timestamp)}return t}(e);if(t){const r=A(t.usage);let n=0;for(let o=t.index+1;o<e.length;o++)n+=R(e[o]);return{tokens:r+n,usageTokens:r,trailingTokens:n,lastUsageIndex:t.index}}let r=0;for(const n of e)r+=R(n);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function I(e){return e&&0!==e.length?q(M(e)):0}function O(e,t,r){if(e.contextWindow<=0)return Math.max(1,r);const n=e.contextWindow-function(e){if(t=e,Array.isArray(t))return N(e);var t;const r=N(e.messages);if(null!==r.lastUsageIndex){const t=new Set(e.messages.slice(r.lastUsageIndex+1).filter(e=>"toolResult"===e.role).flatMap(e=>e.addedToolNames??[])),n=I(e.tools?.filter(e=>t.has(e.name)));return{tokens:r.tokens+n,usageTokens:r.usageTokens,trailingTokens:r.trailingTokens+n,lastUsageIndex:r.lastUsageIndex}}const n=(e.systemPrompt?q(e.systemPrompt):0)+I(e.tools);return{tokens:r.tokens+n,usageTokens:r.usageTokens,trailingTokens:r.trailingTokens+n,lastUsageIndex:r.lastUsageIndex}}(t).tokens-4096;return Math.min(r,Math.max(1,n))}function P(e,t,r,n){const o=e.samplingParams||r?.samplingParams?{...e.samplingParams,...r?.samplingParams}:void 0;return{temperature:r?.temperature,samplingParams:o,maxTokens:O(e,t,r?.maxTokens??e.maxTokens),signal:r?.signal,telemetryContext:r?.telemetryContext,apiKey:n||r?.apiKey,fetch:r?.fetch,transport:r?.transport,cacheRetention:r?.cacheRetention,sessionId:r?.sessionId,headers:r?.headers,onPayload:r?.onPayload,onResponse:r?.onResponse,timeoutMs:r?.timeoutMs,websocketConnectTimeoutMs:r?.websocketConnectTimeoutMs,maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,metadata:r?.metadata,env:r?.env}}var $=1024;function S(e){return"xhigh"===e||"max"===e?"high":e}function j(e,t,r,n){let o={minimal:1024,low:2048,medium:8192,high:16384,...n}[S(r)];const s=void 0===e?t:Math.min(e+o,t);return s<=o&&(o=Math.max(0,s-1024)),{maxTokens:s,thinkingBudget:o}}function C(e,t){const r=[];let n=!1;for(const o of e)"image"!==o.type?(r.push(o),n=o.text===t):(n||r.push({type:"text",text:t}),n=!0);return r}function D(e,t,r){const n=/* @__PURE__ */new Map,o=function(e,t){return t.input.includes("image")?e:e.map(e=>"user"===e.role&&Array.isArray(e.content)?{...e,content:C(e.content,"(image omitted: model does not support images)")}:"toolResult"===e.role?{...e,content:C(e.content,"(tool image omitted: model does not support images)")}:e)}(e.map(e=>null==e.content?{...e,content:[]}:e),t).map(e=>{if("user"===e.role)return e;if("toolResult"===e.role){const t=n.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if("assistant"===e.role){const o=e,s=o.provider===t.provider&&o.api===t.api&&o.model===t.id,a=o.content.flatMap(e=>{if("thinking"===e.type)return e.redacted?s?e:[]:s&&e.thinkingSignature?e:e.thinking&&""!==e.thinking.trim()?s?e:{type:"text",text:e.thinking}:[];if("text"===e.type)return s?e:{type:"text",text:e.text};if("toolCall"===e.type){const a=e;let i=a;if(!s&&a.thoughtSignature&&(i={...a},delete i.thoughtSignature),!s&&r){const e=r(a.id,t,o);e!==a.id&&(n.set(a.id,e),i={...i,id:e})}return i}return e});return{...o,content:a}}return e}),s=[];let a=[],i=/* @__PURE__ */new Set;const u=()=>{if(a.length>0){for(const e of a)i.has(e.id)||s.push({role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});a=[],i=/* @__PURE__ */new Set}};for(let c=0;c<o.length;c++){const e=o[c];if("assistant"===e.role){u();const t=e;if("error"===t.stopReason||"aborted"===t.stopReason)continue;const r=t.content.filter(e=>"toolCall"===e.type);r.length>0&&(a=r,i=/* @__PURE__ */new Set),s.push(e)}else"toolResult"===e.role?(i.add(e.toolCallId),s.push(e)):"user"===e.role?(u(),s.push(e)):s.push(e)}return u(),s}export{O as a,T as c,k as d,v as f,t as g,e as h,P as i,w as l,u as m,$ as n,S as o,c as p,j as r,x as s,D as t,y as u};
|