@galaxyproject/jupyterlite 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/package.json +4 -3
  2. package/static/dist/_output/build/schemas/all_federated.json +1 -1
  3. package/static/dist/_output/extensions/@jupyterlite/ai/install.json +5 -0
  4. package/static/dist/_output/extensions/@jupyterlite/ai/package.json +252 -0
  5. package/static/dist/_output/extensions/@jupyterlite/ai/schemas/@jupyterlite/ai/settings-model.json +194 -0
  6. package/static/dist/_output/extensions/@jupyterlite/ai/static/116.010504c67cccbe983101.js +1 -0
  7. package/static/dist/_output/extensions/@jupyterlite/ai/static/155.33f38a7e48ddbeb5bb6e.js +1 -0
  8. package/static/dist/_output/extensions/@jupyterlite/ai/static/180.96635ff74c0413e0c580.js +1 -0
  9. package/static/dist/_output/extensions/@jupyterlite/ai/static/19.a1bb726875fe6561330e.js +1 -0
  10. package/static/dist/_output/extensions/@jupyterlite/ai/static/306.17ff80cd7d3702012f98.js +1 -0
  11. package/static/dist/_output/extensions/@jupyterlite/ai/static/313.e439dd0f4960f6e7585f.js +1 -0
  12. package/static/dist/_output/extensions/@jupyterlite/ai/static/324.77487b82034275866b8c.js +1 -0
  13. package/static/dist/_output/extensions/@jupyterlite/ai/static/340.e42ea25ea5b1b374a682.js +1 -0
  14. package/static/dist/_output/extensions/@jupyterlite/ai/static/374.d7b4dcf29eb3d2ebfd70.js +1 -0
  15. package/static/dist/_output/extensions/@jupyterlite/ai/static/472.05d097796e83ea9a22b4.js +1 -0
  16. package/static/dist/_output/extensions/@jupyterlite/ai/static/529.600d1aebb2de2d73fecb.js +2 -0
  17. package/static/dist/_output/extensions/@jupyterlite/ai/static/529.600d1aebb2de2d73fecb.js.LICENSE.txt +8 -0
  18. package/static/dist/_output/extensions/@jupyterlite/ai/static/537.eb8d9ccd76231e36d75f.js +1 -0
  19. package/static/dist/_output/extensions/@jupyterlite/ai/static/593.284fd5d2b50defc573f3.js +1 -0
  20. package/static/dist/_output/extensions/@jupyterlite/ai/static/665.564d208c226b2753e13b.js +1 -0
  21. package/static/dist/_output/extensions/@jupyterlite/ai/static/669.0094374ba6e3143702f7.js +1 -0
  22. package/static/dist/_output/extensions/@jupyterlite/ai/static/692.911f4d7dca73b3737833.js +1 -0
  23. package/static/dist/_output/extensions/@jupyterlite/ai/static/694.e439dd0f4960f6e7585f.js +1 -0
  24. package/static/dist/_output/extensions/@jupyterlite/ai/static/709.7578153f9eed366ee430.js +2 -0
  25. package/static/dist/_output/extensions/@jupyterlite/ai/static/709.7578153f9eed366ee430.js.LICENSE.txt +19 -0
  26. package/static/dist/_output/extensions/@jupyterlite/ai/static/728.d7c2cb9a2f7fdd846b35.js +1 -0
  27. package/static/dist/_output/extensions/@jupyterlite/ai/static/764.312b4b53ed50be5bf3f8.js +1 -0
  28. package/static/dist/_output/extensions/@jupyterlite/ai/static/798.dca29a3fc3b23c555f6b.js +1 -0
  29. package/static/dist/_output/extensions/@jupyterlite/ai/static/88.898492ebc5b41a4607c6.js +2 -0
  30. package/static/dist/_output/extensions/@jupyterlite/ai/static/88.898492ebc5b41a4607c6.js.LICENSE.txt +1 -0
  31. package/static/dist/_output/extensions/@jupyterlite/ai/static/885.1670a5138e0a13def795.js +1 -0
  32. package/static/dist/_output/extensions/@jupyterlite/ai/static/918.e91fcd78edba173284a4.js +1 -0
  33. package/static/dist/_output/extensions/@jupyterlite/ai/static/92.55c2fe71a33184c2e66d.js +1 -0
  34. package/static/dist/_output/extensions/@jupyterlite/ai/static/952.003f03c751075980ac7f.js +183 -0
  35. package/static/dist/_output/extensions/@jupyterlite/ai/static/remoteEntry.2f103c13fd640ab93eb9.js +1 -0
  36. package/static/dist/_output/extensions/@jupyterlite/ai/static/style.js +4 -0
  37. package/static/dist/_output/extensions/@jupyterlite/ai/static/third-party-licenses.json +352 -0
  38. package/static/dist/_output/extensions/jl-galaxy/extension.js +1 -1
  39. package/static/dist/_output/extensions/jupyter-secrets-manager/install.json +5 -0
  40. package/static/dist/_output/extensions/jupyter-secrets-manager/package.json +207 -0
  41. package/static/dist/_output/extensions/jupyter-secrets-manager/schemas/jupyter-secrets-manager/manager.json +14 -0
  42. package/static/dist/_output/extensions/jupyter-secrets-manager/static/728.69cdb8043c4eb7a36084.js +1 -0
  43. package/static/dist/_output/extensions/jupyter-secrets-manager/static/810.7ac328ef761c19894484.js +1 -0
  44. package/static/dist/_output/extensions/jupyter-secrets-manager/static/remoteEntry.6610dc2c9e0921c7f94a.js +1 -0
  45. package/static/dist/_output/extensions/jupyter-secrets-manager/static/style.js +4 -0
  46. package/static/dist/_output/extensions/jupyter-secrets-manager/static/third-party-licenses.json +16 -0
  47. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/install.json +5 -0
  48. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/package.json +90 -0
  49. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/374.f7ab05aeba5c1aa173c9.js +1 -0
  50. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/432.7cb3263d05824765a0d2.js +1 -0
  51. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/509.9384daafd8fb72a4ff3a.js +1 -0
  52. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/993.f7ab05aeba5c1aa173c9.js +1 -0
  53. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/remoteEntry.f80ac7a8e97b08d2a2fd.js +1 -0
  54. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/style.js +4 -0
  55. package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/third-party-licenses.json +22 -0
  56. package/static/dist/_output/extensions/jupyterlab-diff/install.json +5 -0
  57. package/static/dist/_output/extensions/jupyterlab-diff/package.json +224 -0
  58. package/static/dist/_output/extensions/jupyterlab-diff/static/299.07069b808cb23f84a242.js +1 -0
  59. package/static/dist/_output/extensions/jupyterlab-diff/static/379.2e2a6add1111d74422d2.js +1 -0
  60. package/static/dist/_output/extensions/jupyterlab-diff/static/383.dbd292b18614d410ed4b.js +1 -0
  61. package/static/dist/_output/extensions/jupyterlab-diff/static/499.e9c141febe62f251e965.js +1 -0
  62. package/static/dist/_output/extensions/jupyterlab-diff/static/680.07069b808cb23f84a242.js +1 -0
  63. package/static/dist/_output/extensions/jupyterlab-diff/static/728.559a28b17e14994cba46.js +1 -0
  64. package/static/dist/_output/extensions/jupyterlab-diff/static/747.e3256716cc1134700a59.js +1 -0
  65. package/static/dist/_output/extensions/jupyterlab-diff/static/879.749253139a5186f32109.js +1 -0
  66. package/static/dist/_output/extensions/jupyterlab-diff/static/remoteEntry.4830528fbe7c3ca55989.js +1 -0
  67. package/static/dist/_output/extensions/jupyterlab-diff/static/style.js +4 -0
  68. package/static/dist/_output/extensions/jupyterlab-diff/static/third-party-licenses.json +94 -0
  69. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/install.json +5 -0
  70. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/package.json +90 -0
  71. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/432.57100b29bc9fea211a0e.js +1 -0
  72. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/509.d1cc43983763b6a85f45.js +1 -0
  73. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/666.84cadfe40c86b502f11d.js +1 -0
  74. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/remoteEntry.5577376b289c1f9e2dc2.js +1 -0
  75. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/style.js +4 -0
  76. package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/third-party-licenses.json +22 -0
  77. package/static/dist/_output/jupyter-lite.json +43 -20
  78. package/static/dist/_output/pypi/attrs-25.4.0-py3-none-any.whl +0 -0
  79. package/static/dist/_output/pypi/gxy-0.0.0-py3-none-any.whl +0 -0
  80. package/static/dist/_output/pypi/jupyter_core-5.9.1-py3-none-any.whl +0 -0
  81. package/static/dist/_output/pypi/narwhals-2.13.0-py3-none-any.whl +0 -0
  82. package/static/dist/_output/pypi/{platformdirs-4.4.0-py3-none-any.whl → platformdirs-4.5.1-py3-none-any.whl} +0 -0
  83. package/static/dist/_output/pypi/referencing-0.37.0-py3-none-any.whl +0 -0
  84. package/static/dist/index.js +2 -2
  85. package/static/dist/_output/pypi/attrs-25.3.0-py3-none-any.whl +0 -0
  86. package/static/dist/_output/pypi/jupyter_core-5.8.1-py3-none-any.whl +0 -0
  87. package/static/dist/_output/pypi/narwhals-2.6.0-py3-none-any.whl +0 -0
  88. package/static/dist/_output/pypi/referencing-0.36.2-py3-none-any.whl +0 -0
@@ -0,0 +1 @@
1
+ "use strict";(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[306],{7306:(e,t,o)=>{o.r(t),o.d(t,{VERSION:()=>Ce,createOpenAI:()=>Me,openai:()=>Ne});var n=o(116),i=o(2100),s=o(6097),a=o(9717),r=s.Ik({error:s.Ik({message:s.Yj(),type:s.Yj().nullish(),param:s.bz().nullish(),code:s.KC([s.Yj(),s.ai()]).nullish()})}),l=(0,n.createJsonErrorResponseHandler)({errorSchema:r,errorToMessage:e=>e.error.message});function u({id:e,model:t,created:o}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=o?new Date(1e3*o):void 0}}function p(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var d=s.Ik({logitBias:s.g1(a.qG(s.rS,undefined),s.ai()).optional(),logprobs:s.KC([s.zM(),s.ai()]).optional(),parallelToolCalls:s.zM().optional(),user:s.Yj().optional(),reasoningEffort:s.k5(["minimal","low","medium","high"]).optional(),maxCompletionTokens:s.ai().optional(),store:s.zM().optional(),metadata:s.g1(s.Yj().max(64),s.Yj().max(512)).optional(),prediction:s.g1(s.Yj(),s.bz()).optional(),structuredOutputs:s.zM().optional(),serviceTier:s.k5(["auto","flex","priority"]).optional(),strictJsonSchema:s.zM().optional(),textVerbosity:s.k5(["low","medium","high"]).optional(),promptCacheKey:s.Yj().optional(),safetyIdentifier:s.Yj().optional()}),c=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:o,topP:s,topK:a,frequencyPenalty:r,presencePenalty:l,stopSequences:u,responseFormat:p,seed:c,tools:m,toolChoice:h,providerOptions:g}){var _,v,k,I;const b=[],Y=null!=(_=await(0,n.parseProviderOptions)({provider:"openai",providerOptions:g,schema:d}))?_:{},j=null==(v=Y.structuredOutputs)||v;null!=a&&b.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==p?void 0:p.type)||null==p.schema||j||b.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:w,warnings:x}=function({prompt:e,systemMessageMode:t="system"}){const o=[],s=[];for(const{role:a,content:r}of e)switch(a){case"system":switch(t){case"system":o.push({role:"system",content:r});break;case"developer":o.push({role:"developer",content:r});break;case"remove":s.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===r.length&&"text"===r[0].type){o.push({role:"user",content:r[0].text});break}o.push({role:"user",content:r.map((e,t)=>{var o,s,a;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${(0,n.convertToBase64)(e.data)}`,detail:null==(s=null==(o=e.providerOptions)?void 0:o.openai)?void 0:s.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new i.b8({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(a=e.filename)?a:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${(0,n.convertToBase64)(e.data)}`}}}throw new i.b8({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new i.b8({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:(0,n.convertToBase64)(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:(0,n.convertToBase64)(e.data),format:"mp3"}};default:throw new i.b8({functionality:`audio content parts with media type ${e.mediaType}`})}}})});break;case"assistant":{let e="";const t=[];for(const o of r)switch(o.type){case"text":e+=o.text;break;case"tool-call":t.push({id:o.toolCallId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.input)}})}o.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of r){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}o.push({role:"tool",tool_call_id:e.toolCallId,content:n})}break;default:throw new Error(`Unsupported role: ${a}`)}return{messages:o,warnings:s}}({prompt:e,systemMessageMode:y(this.modelId)});b.push(...x);const T=null!=(k=Y.strictJsonSchema)&&k,O={model:this.modelId,logit_bias:Y.logitBias,logprobs:!0===Y.logprobs||"number"==typeof Y.logprobs||void 0,top_logprobs:"number"==typeof Y.logprobs?Y.logprobs:"boolean"==typeof Y.logprobs&&Y.logprobs?0:void 0,user:Y.user,parallel_tool_calls:Y.parallelToolCalls,max_tokens:t,temperature:o,top_p:s,frequency_penalty:r,presence_penalty:l,response_format:"json"===(null==p?void 0:p.type)?j&&null!=p.schema?{type:"json_schema",json_schema:{schema:p.schema,strict:T,name:null!=(I=p.name)?I:"response",description:p.description}}:{type:"json_object"}:void 0,stop:u,seed:c,verbosity:Y.textVerbosity,max_completion_tokens:Y.maxCompletionTokens,store:Y.store,metadata:Y.metadata,prediction:Y.prediction,reasoning_effort:Y.reasoningEffort,service_tier:Y.serviceTier,prompt_cache_key:Y.promptCacheKey,safety_identifier:Y.safetyIdentifier,messages:w};var q;f(this.modelId)?(null!=O.temperature&&(O.temperature=void 0,b.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=O.top_p&&(O.top_p=void 0,b.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=O.frequency_penalty&&(O.frequency_penalty=void 0,b.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=O.presence_penalty&&(O.presence_penalty=void 0,b.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=O.logit_bias&&(O.logit_bias=void 0,b.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=O.logprobs&&(O.logprobs=void 0,b.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=O.top_logprobs&&(O.top_logprobs=void 0,b.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=O.max_tokens&&(null==O.max_completion_tokens&&(O.max_completion_tokens=O.max_tokens),O.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=O.temperature&&(O.temperature=void 0,b.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==Y.serviceTier||(q=this.modelId).startsWith("o3")||q.startsWith("o4-mini")||q.startsWith("gpt-5")&&!q.startsWith("gpt-5-chat")||(b.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),O.service_tier=void 0),"priority"!==Y.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(b.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),O.service_tier=void 0);const{tools:S,toolChoice:C,toolWarnings:M}=function({tools:e,toolChoice:t,structuredOutputs:o,strictJsonSchema:n}){const s=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:s};const a=[];for(const t of e)"function"===t.type?a.push({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:o?n:void 0}}):s.push({type:"unsupported-tool",tool:t});if(null==t)return{tools:a,toolChoice:void 0,toolWarnings:s};const r=t.type;switch(r){case"auto":case"none":case"required":return{tools:a,toolChoice:r,toolWarnings:s};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:s};default:{const e=r;throw new i.b8({functionality:`tool choice type: ${e}`})}}}({tools:m,toolChoice:h,structuredOutputs:j,strictJsonSchema:T});return{args:{...O,tools:S,tool_choice:C},warnings:[...b,...M]}}async doGenerate(e){var t,o,i,s,a,r,d,c,m,g,f,y,_,v;const{args:k,warnings:I}=await this.getArgs(e),{responseHeaders:b,value:Y,rawValue:j}=await(0,n.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:k,failedResponseHandler:l,successfulResponseHandler:(0,n.createJsonResponseHandler)(h),abortSignal:e.abortSignal,fetch:this.config.fetch}),w=Y.choices[0],x=[],T=w.message.content;null!=T&&T.length>0&&x.push({type:"text",text:T});for(const e of null!=(t=w.message.tool_calls)?t:[])x.push({type:"tool-call",toolCallId:null!=(o=e.id)?o:(0,n.generateId)(),toolName:e.function.name,input:e.function.arguments});for(const e of null!=(i=w.message.annotations)?i:[])x.push({type:"source",sourceType:"url",id:(0,n.generateId)(),url:e.url,title:e.title});const O=null==(s=Y.usage)?void 0:s.completion_tokens_details,q=null==(a=Y.usage)?void 0:a.prompt_tokens_details,S={openai:{}};return null!=(null==O?void 0:O.accepted_prediction_tokens)&&(S.openai.acceptedPredictionTokens=null==O?void 0:O.accepted_prediction_tokens),null!=(null==O?void 0:O.rejected_prediction_tokens)&&(S.openai.rejectedPredictionTokens=null==O?void 0:O.rejected_prediction_tokens),null!=(null==(r=w.logprobs)?void 0:r.content)&&(S.openai.logprobs=w.logprobs.content),{content:x,finishReason:p(w.finish_reason),usage:{inputTokens:null!=(c=null==(d=Y.usage)?void 0:d.prompt_tokens)?c:void 0,outputTokens:null!=(g=null==(m=Y.usage)?void 0:m.completion_tokens)?g:void 0,totalTokens:null!=(y=null==(f=Y.usage)?void 0:f.total_tokens)?y:void 0,reasoningTokens:null!=(_=null==O?void 0:O.reasoning_tokens)?_:void 0,cachedInputTokens:null!=(v=null==q?void 0:q.cached_tokens)?v:void 0},request:{body:k},response:{...u(Y),headers:b,body:j},warnings:I,providerMetadata:S}}async doStream(e){const{args:t,warnings:o}=await this.getArgs(e),s={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:r}=await(0,n.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:s,failedResponseHandler:l,successfulResponseHandler:(0,n.createEventSourceResponseHandler)(g),abortSignal:e.abortSignal,fetch:this.config.fetch}),d=[];let c="unknown";const m={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let h=!0,f=!1;const y={openai:{}};return{stream:r.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:o})},transform(t,o){var s,a,r,l,g,_,v,k,I,b,Y,j,w,x,T,O,q,S,C,M,N,R,E,$;if(e.includeRawChunks&&o.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return c="error",void o.enqueue({type:"error",error:t.error});const P=t.value;if("error"in P)return c="error",void o.enqueue({type:"error",error:P.error});h&&(h=!1,o.enqueue({type:"response-metadata",...u(P)})),null!=P.usage&&(m.inputTokens=null!=(s=P.usage.prompt_tokens)?s:void 0,m.outputTokens=null!=(a=P.usage.completion_tokens)?a:void 0,m.totalTokens=null!=(r=P.usage.total_tokens)?r:void 0,m.reasoningTokens=null!=(g=null==(l=P.usage.completion_tokens_details)?void 0:l.reasoning_tokens)?g:void 0,m.cachedInputTokens=null!=(v=null==(_=P.usage.prompt_tokens_details)?void 0:_.cached_tokens)?v:void 0,null!=(null==(k=P.usage.completion_tokens_details)?void 0:k.accepted_prediction_tokens)&&(y.openai.acceptedPredictionTokens=null==(I=P.usage.completion_tokens_details)?void 0:I.accepted_prediction_tokens),null!=(null==(b=P.usage.completion_tokens_details)?void 0:b.rejected_prediction_tokens)&&(y.openai.rejectedPredictionTokens=null==(Y=P.usage.completion_tokens_details)?void 0:Y.rejected_prediction_tokens));const W=P.choices[0];if(null!=(null==W?void 0:W.finish_reason)&&(c=p(W.finish_reason)),null!=(null==(j=null==W?void 0:W.logprobs)?void 0:j.content)&&(y.openai.logprobs=W.logprobs.content),null==(null==W?void 0:W.delta))return;const H=W.delta;if(null!=H.content&&(f||(o.enqueue({type:"text-start",id:"0"}),f=!0),o.enqueue({type:"text-delta",id:"0",delta:H.content})),null!=H.tool_calls)for(const e of H.tool_calls){const t=e.index;if(null==d[t]){if("function"!==e.type)throw new i.xn({data:e,message:"Expected 'function' type."});if(null==e.id)throw new i.xn({data:e,message:"Expected 'id' to be a string."});if(null==(null==(w=e.function)?void 0:w.name))throw new i.xn({data:e,message:"Expected 'function.name' to be a string."});o.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),d[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(x=e.function.arguments)?x:""},hasFinished:!1};const s=d[t];null!=(null==(T=s.function)?void 0:T.name)&&null!=(null==(O=s.function)?void 0:O.arguments)&&(s.function.arguments.length>0&&o.enqueue({type:"tool-input-delta",id:s.id,delta:s.function.arguments}),(0,n.isParsableJson)(s.function.arguments)&&(o.enqueue({type:"tool-input-end",id:s.id}),o.enqueue({type:"tool-call",toolCallId:null!=(q=s.id)?q:(0,n.generateId)(),toolName:s.function.name,input:s.function.arguments}),s.hasFinished=!0));continue}const s=d[t];s.hasFinished||(null!=(null==(S=e.function)?void 0:S.arguments)&&(s.function.arguments+=null!=(M=null==(C=e.function)?void 0:C.arguments)?M:""),o.enqueue({type:"tool-input-delta",id:s.id,delta:null!=(N=e.function.arguments)?N:""}),null!=(null==(R=s.function)?void 0:R.name)&&null!=(null==(E=s.function)?void 0:E.arguments)&&(0,n.isParsableJson)(s.function.arguments)&&(o.enqueue({type:"tool-input-end",id:s.id}),o.enqueue({type:"tool-call",toolCallId:null!=($=s.id)?$:(0,n.generateId)(),toolName:s.function.name,input:s.function.arguments}),s.hasFinished=!0))}if(null!=H.annotations)for(const e of H.annotations)o.enqueue({type:"source",sourceType:"url",id:(0,n.generateId)(),url:e.url,title:e.title})},flush(e){f&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:c,usage:m,...null!=y?{providerMetadata:y}:{}})}})),request:{body:s},response:{headers:a}}}},m=s.Ik({prompt_tokens:s.ai().nullish(),completion_tokens:s.ai().nullish(),total_tokens:s.ai().nullish(),prompt_tokens_details:s.Ik({cached_tokens:s.ai().nullish()}).nullish(),completion_tokens_details:s.Ik({reasoning_tokens:s.ai().nullish(),accepted_prediction_tokens:s.ai().nullish(),rejected_prediction_tokens:s.ai().nullish()}).nullish()}).nullish(),h=s.Ik({id:s.Yj().nullish(),created:s.ai().nullish(),model:s.Yj().nullish(),choices:s.YO(s.Ik({message:s.Ik({role:s.eu("assistant").nullish(),content:s.Yj().nullish(),tool_calls:s.YO(s.Ik({id:s.Yj().nullish(),type:s.eu("function"),function:s.Ik({name:s.Yj(),arguments:s.Yj()})})).nullish(),annotations:s.YO(s.Ik({type:s.eu("url_citation"),start_index:s.ai(),end_index:s.ai(),url:s.Yj(),title:s.Yj()})).nullish()}),index:s.ai(),logprobs:s.Ik({content:s.YO(s.Ik({token:s.Yj(),logprob:s.ai(),top_logprobs:s.YO(s.Ik({token:s.Yj(),logprob:s.ai()}))})).nullish()}).nullish(),finish_reason:s.Yj().nullish()})),usage:m}),g=s.KC([s.Ik({id:s.Yj().nullish(),created:s.ai().nullish(),model:s.Yj().nullish(),choices:s.YO(s.Ik({delta:s.Ik({role:s.k5(["assistant"]).nullish(),content:s.Yj().nullish(),tool_calls:s.YO(s.Ik({index:s.ai(),id:s.Yj().nullish(),type:s.eu("function").nullish(),function:s.Ik({name:s.Yj().nullish(),arguments:s.Yj().nullish()})})).nullish(),annotations:s.YO(s.Ik({type:s.eu("url_citation"),start_index:s.ai(),end_index:s.ai(),url:s.Yj(),title:s.Yj()})).nullish()}).nullish(),logprobs:s.Ik({content:s.YO(s.Ik({token:s.Yj(),logprob:s.ai(),top_logprobs:s.YO(s.Ik({token:s.Yj(),logprob:s.ai()}))})).nullish()}).nullish(),finish_reason:s.Yj().nullish(),index:s.ai()})),usage:m}),r]);function f(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function y(e){var t,o;return f(e)?null!=(o=null==(t=_[e])?void 0:t.systemMessageMode)?o:"developer":"system"}var _={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function v({id:e,model:t,created:o}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=o?new Date(1e3*o):void 0}}function k(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var I=s.Ik({echo:s.zM().optional(),logitBias:s.g1(s.Yj(),s.ai()).optional(),suffix:s.Yj().optional(),user:s.Yj().optional(),logprobs:s.KC([s.zM(),s.ai()]).optional()}),b=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:o,topP:s,topK:a,frequencyPenalty:r,presencePenalty:l,stopSequences:u,responseFormat:p,tools:d,toolChoice:c,seed:m,providerOptions:h}){const g=[],f={...await(0,n.parseProviderOptions)({provider:"openai",providerOptions:h,schema:I}),...await(0,n.parseProviderOptions)({provider:this.providerOptionsName,providerOptions:h,schema:I})};null!=a&&g.push({type:"unsupported-setting",setting:"topK"}),(null==d?void 0:d.length)&&g.push({type:"unsupported-setting",setting:"tools"}),null!=c&&g.push({type:"unsupported-setting",setting:"toolChoice"}),null!=p&&"text"!==p.type&&g.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:_}=function({prompt:e,user:t="user",assistant:o="assistant"}){let n="";"system"===e[0].role&&(n+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:s,content:a}of e)switch(s){case"system":throw new i.M3({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":n+=`${t}:\n${a.map(e=>{if("text"===e.type)return e.text}).filter(Boolean).join("")}\n\n`;break;case"assistant":n+=`${o}:\n${a.map(e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new i.b8({functionality:"tool-call messages"})}}).join("")}\n\n`;break;case"tool":throw new i.b8({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${s}`)}return n+=`${o}:\n`,{prompt:n,stopSequences:[`\n${t}:`]}}({prompt:e}),v=[...null!=_?_:[],...null!=u?u:[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:!0===(null==f?void 0:f.logprobs)?0:!1===(null==f?void 0:f.logprobs)||null==f?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:o,top_p:s,frequency_penalty:r,presence_penalty:l,seed:m,prompt:y,stop:v.length>0?v:void 0},warnings:g}}async doGenerate(e){var t,o,i;const{args:s,warnings:a}=await this.getArgs(e),{responseHeaders:r,value:u,rawValue:p}=await(0,n.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:s,failedResponseHandler:l,successfulResponseHandler:(0,n.createJsonResponseHandler)(j),abortSignal:e.abortSignal,fetch:this.config.fetch}),d=u.choices[0],c={openai:{}};return null!=d.logprobs&&(c.openai.logprobs=d.logprobs),{content:[{type:"text",text:d.text}],usage:{inputTokens:null==(t=u.usage)?void 0:t.prompt_tokens,outputTokens:null==(o=u.usage)?void 0:o.completion_tokens,totalTokens:null==(i=u.usage)?void 0:i.total_tokens},finishReason:k(d.finish_reason),request:{body:s},response:{...v(u),headers:r,body:p},providerMetadata:c,warnings:a}}async doStream(e){const{args:t,warnings:o}=await this.getArgs(e),i={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await(0,n.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:i,failedResponseHandler:l,successfulResponseHandler:(0,n.createEventSourceResponseHandler)(w),abortSignal:e.abortSignal,fetch:this.config.fetch});let r="unknown";const u={openai:{}},p={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let d=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:o})},transform(t,o){if(e.includeRawChunks&&o.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return r="error",void o.enqueue({type:"error",error:t.error});const n=t.value;if("error"in n)return r="error",void o.enqueue({type:"error",error:n.error});d&&(d=!1,o.enqueue({type:"response-metadata",...v(n)}),o.enqueue({type:"text-start",id:"0"})),null!=n.usage&&(p.inputTokens=n.usage.prompt_tokens,p.outputTokens=n.usage.completion_tokens,p.totalTokens=n.usage.total_tokens);const i=n.choices[0];null!=(null==i?void 0:i.finish_reason)&&(r=k(i.finish_reason)),null!=(null==i?void 0:i.logprobs)&&(u.openai.logprobs=i.logprobs),null!=(null==i?void 0:i.text)&&i.text.length>0&&o.enqueue({type:"text-delta",id:"0",delta:i.text})},flush(e){d||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:r,providerMetadata:u,usage:p})}})),request:{body:i},response:{headers:s}}}},Y=s.Ik({prompt_tokens:s.ai(),completion_tokens:s.ai(),total_tokens:s.ai()}),j=s.Ik({id:s.Yj().nullish(),created:s.ai().nullish(),model:s.Yj().nullish(),choices:s.YO(s.Ik({text:s.Yj(),finish_reason:s.Yj(),logprobs:s.Ik({tokens:s.YO(s.Yj()),token_logprobs:s.YO(s.ai()),top_logprobs:s.YO(s.g1(s.Yj(),s.ai())).nullish()}).nullish()})),usage:Y.nullish()}),w=s.KC([s.Ik({id:s.Yj().nullish(),created:s.ai().nullish(),model:s.Yj().nullish(),choices:s.YO(s.Ik({text:s.Yj(),finish_reason:s.Yj().nullish(),index:s.ai(),logprobs:s.Ik({tokens:s.YO(s.Yj()),token_logprobs:s.YO(s.ai()),top_logprobs:s.YO(s.g1(s.Yj(),s.ai())).nullish()}).nullish()})),usage:Y.nullish()}),r]),x=s.Ik({dimensions:s.ai().optional(),user:s.Yj().optional()}),T=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:o,providerOptions:s}){var a;if(e.length>this.maxEmbeddingsPerCall)throw new i.Ch({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const r=null!=(a=await(0,n.parseProviderOptions)({provider:"openai",providerOptions:s,schema:x}))?a:{},{responseHeaders:u,value:p,rawValue:d}=await(0,n.postJsonToApi)({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:r.dimensions,user:r.user},failedResponseHandler:l,successfulResponseHandler:(0,n.createJsonResponseHandler)(O),abortSignal:o,fetch:this.config.fetch});return{embeddings:p.data.map(e=>e.embedding),usage:p.usage?{tokens:p.usage.prompt_tokens}:void 0,response:{headers:u,body:d}}}},O=s.Ik({data:s.YO(s.Ik({embedding:s.YO(s.ai())})),usage:s.Ik({prompt_tokens:s.ai()}).nullish()}),q={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},S=new Set(["gpt-image-1","gpt-image-1-mini"]),C=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=q[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:o,aspectRatio:i,seed:s,providerOptions:a,headers:r,abortSignal:u}){var p,d,c,m;const h=[];null!=i&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=s&&h.push({type:"unsupported-setting",setting:"seed"});const g=null!=(c=null==(d=null==(p=this.config._internal)?void 0:p.currentDate)?void 0:d.call(p))?c:new Date,{value:f,responseHeaders:y}=await(0,n.postJsonToApi)({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),r),body:{model:this.modelId,prompt:e,n:t,size:o,...null!=(m=a.openai)?m:{},...S.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:l,successfulResponseHandler:(0,n.createJsonResponseHandler)(M),abortSignal:u,fetch:this.config.fetch});return{images:f.data.map(e=>e.b64_json),warnings:h,response:{timestamp:g,modelId:this.modelId,headers:y},providerMetadata:{openai:{images:f.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},M=s.Ik({data:s.YO(s.Ik({b64_json:s.Yj(),revised_prompt:s.Yj().optional()}))}),N=s.Ik({code:s.Yj().nullish(),containerId:s.Yj()}),R=s.Ik({outputs:s.YO(s.gM("type",[s.Ik({type:s.eu("logs"),logs:s.Yj()}),s.Ik({type:s.eu("image"),url:s.Yj()})])).nullish()}),E=s.Ik({container:s.KC([s.Yj(),s.Ik({fileIds:s.YO(s.Yj()).optional()})]).optional()}),$=(0,n.createProviderDefinedToolFactoryWithOutputSchema)({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:N,outputSchema:R}),P=s.Ik({key:s.Yj(),type:s.k5(["eq","ne","gt","gte","lt","lte"]),value:s.KC([s.Yj(),s.ai(),s.zM()])}),W=s.Ik({type:s.k5(["and","or"]),filters:s.YO(s.KC([P,s.RZ(()=>W)]))}),H=s.Ik({vectorStoreIds:s.YO(s.Yj()),maxNumResults:s.ai().optional(),ranking:s.Ik({ranker:s.Yj().optional(),scoreThreshold:s.ai().optional()}).optional(),filters:s.KC([P,W]).optional()}),A=s.Ik({queries:s.YO(s.Yj()),results:s.YO(s.Ik({attributes:s.g1(s.Yj(),s.L5()),fileId:s.Yj(),filename:s.Yj(),score:s.ai(),text:s.Yj()})).nullable()}),J=(0,n.createProviderDefinedToolFactoryWithOutputSchema)({id:"openai.file_search",name:"file_search",inputSchema:s.Ik({}),outputSchema:A}),z=s.Ik({background:s.k5(["auto","opaque","transparent"]).optional(),inputFidelity:s.k5(["low","high"]).optional(),inputImageMask:s.Ik({fileId:s.Yj().optional(),imageUrl:s.Yj().optional()}).optional(),model:s.Yj().optional(),moderation:s.k5(["auto"]).optional(),outputCompression:s.ai().int().min(0).max(100).optional(),outputFormat:s.k5(["png","jpeg","webp"]).optional(),quality:s.k5(["auto","low","medium","high"]).optional(),size:s.k5(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict(),D=s.Ik({result:s.Yj()}),F=(0,n.createProviderDefinedToolFactoryWithOutputSchema)({id:"openai.image_generation",name:"image_generation",inputSchema:s.Ik({}),outputSchema:D}),V=s.Ik({action:s.Ik({type:s.eu("exec"),command:s.YO(s.Yj()),timeoutMs:s.ai().optional(),user:s.Yj().optional(),workingDirectory:s.Yj().optional(),env:s.g1(s.Yj(),s.Yj()).optional()})}),U=s.Ik({output:s.Yj()}),K=(0,n.createProviderDefinedToolFactoryWithOutputSchema)({id:"openai.local_shell",name:"local_shell",inputSchema:V,outputSchema:U}),B=s.Ik({filters:s.Ik({allowedDomains:s.YO(s.Yj()).optional()}).optional(),searchContextSize:s.k5(["low","medium","high"]).optional(),userLocation:s.Ik({type:s.eu("approximate"),country:s.Yj().optional(),city:s.Yj().optional(),region:s.Yj().optional(),timezone:s.Yj().optional()}).optional()}),L=(0,n.createProviderDefinedToolFactory)({id:"openai.web_search",name:"web_search",inputSchema:s.Ik({action:s.gM("type",[s.Ik({type:s.eu("search"),query:s.Yj().nullish()}),s.Ik({type:s.eu("open_page"),url:s.Yj()}),s.Ik({type:s.eu("find"),url:s.Yj(),pattern:s.Yj()})]).nullish()})}),G=s.Ik({searchContextSize:s.k5(["low","medium","high"]).optional(),userLocation:s.Ik({type:s.eu("approximate"),country:s.Yj().optional(),city:s.Yj().optional(),region:s.Yj().optional(),timezone:s.Yj().optional()}).optional()}),Z={codeInterpreter:(e={})=>$(e),fileSearch:J,imageGeneration:(e={})=>F(e),localShell:K,webSearchPreview:(0,n.createProviderDefinedToolFactory)({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:s.Ik({action:s.gM("type",[s.Ik({type:s.eu("search"),query:s.Yj().nullish()}),s.Ik({type:s.eu("open_page"),url:s.Yj()}),s.Ik({type:s.eu("find"),url:s.Yj(),pattern:s.Yj()})]).nullish()})}),webSearch:(e={})=>L(e)};function Q(e,t){return!!t&&t.some(t=>e.startsWith(t))}var X=s.Ik({itemId:s.Yj().nullish(),reasoningEncryptedContent:s.Yj().nullish()});function ee({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var te=s.Ik({type:s.eu("web_search_call"),id:s.Yj(),status:s.Yj(),action:s.gM("type",[s.Ik({type:s.eu("search"),query:s.Yj().nullish()}),s.Ik({type:s.eu("open_page"),url:s.Yj()}),s.Ik({type:s.eu("find"),url:s.Yj(),pattern:s.Yj()})]).nullish()}),oe=s.Ik({type:s.eu("file_search_call"),id:s.Yj(),queries:s.YO(s.Yj()),results:s.YO(s.Ik({attributes:s.g1(s.Yj(),s.L5()),file_id:s.Yj(),filename:s.Yj(),score:s.ai(),text:s.Yj()})).nullish()}),ne=s.Ik({type:s.eu("code_interpreter_call"),id:s.Yj(),code:s.Yj().nullable(),container_id:s.Yj(),outputs:s.YO(s.gM("type",[s.Ik({type:s.eu("logs"),logs:s.Yj()}),s.Ik({type:s.eu("image"),url:s.Yj()})])).nullable()}),ie=s.Ik({type:s.eu("local_shell_call"),id:s.Yj(),call_id:s.Yj(),action:s.Ik({type:s.eu("exec"),command:s.YO(s.Yj()),timeout_ms:s.ai().optional(),user:s.Yj().optional(),working_directory:s.Yj().optional(),env:s.g1(s.Yj(),s.Yj()).optional()})}),se=s.Ik({type:s.eu("image_generation_call"),id:s.Yj(),result:s.Yj()}),ae=s.YO(s.Ik({token:s.Yj(),logprob:s.ai(),top_logprobs:s.YO(s.Ik({token:s.Yj(),logprob:s.ai()}))})),re=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:o,topP:s,topK:a,presencePenalty:r,frequencyPenalty:l,seed:u,prompt:p,providerOptions:d,tools:c,toolChoice:m,responseFormat:h}){var g,f,y,_;const v=[],k=function(e){const t={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),supportsPriorityProcessing:e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")};return e.startsWith("gpt-5-chat")?{...t,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...t,isReasoningModel:!0,systemMessageMode:"remove"}:{...t,isReasoningModel:!0,systemMessageMode:"developer"}:{...t,isReasoningModel:!1}}(this.modelId);null!=a&&v.push({type:"unsupported-setting",setting:"topK"}),null!=u&&v.push({type:"unsupported-setting",setting:"seed"}),null!=r&&v.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=l&&v.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=o&&v.push({type:"unsupported-setting",setting:"stopSequences"});const I=await(0,n.parseProviderOptions)({provider:"openai",providerOptions:d,schema:je}),{input:b,warnings:Y}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:o,store:s,hasLocalShellTool:a=!1}){var r,l,u,p,d,c,m,h,g;const f=[],y=[];for(const{role:_,content:v}of e)switch(_){case"system":switch(t){case"system":f.push({role:"system",content:v});break;case"developer":f.push({role:"developer",content:v});break;case"remove":y.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":f.push({role:"user",content:v.map((e,t)=>{var s,a,r;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&Q(e.data,o)?{file_id:e.data}:{image_url:`data:${t};base64,${(0,n.convertToBase64)(e.data)}`},detail:null==(a=null==(s=e.providerOptions)?void 0:s.openai)?void 0:a.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&Q(e.data,o)?{file_id:e.data}:{filename:null!=(r=e.filename)?r:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${(0,n.convertToBase64)(e.data)}`}};throw new i.b8({functionality:`file part media type ${e.mediaType}`})}})});break;case"assistant":{const e={},t={};for(const o of v)switch(o.type){case"text":f.push({role:"assistant",content:[{type:"output_text",text:o.text}],id:null!=(u=null==(l=null==(r=o.providerOptions)?void 0:r.openai)?void 0:l.itemId)?u:void 0});break;case"tool-call":if(t[o.toolCallId]=o,o.providerExecuted)break;if(a&&"local_shell"===o.toolName){const e=V.parse(o.input);f.push({type:"local_shell_call",call_id:o.toolCallId,id:null!=(c=null==(d=null==(p=o.providerOptions)?void 0:p.openai)?void 0:d.itemId)?c:void 0,action:{type:"exec",command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}f.push({type:"function_call",call_id:o.toolCallId,name:o.toolName,arguments:JSON.stringify(o.input),id:null!=(g=null==(h=null==(m=o.providerOptions)?void 0:m.openai)?void 0:h.itemId)?g:void 0});break;case"tool-result":s?f.push({type:"item_reference",id:o.toolCallId}):y.push({type:"other",message:`Results for OpenAI tool ${o.toolName} are not sent to the API when store is false`});break;case"reasoning":{const t=await(0,n.parseProviderOptions)({provider:"openai",providerOptions:o.providerOptions,schema:X}),i=null==t?void 0:t.itemId;if(null!=i){const n=e[i];if(s)void 0===n&&(f.push({type:"item_reference",id:i}),e[i]={type:"reasoning",id:i,summary:[]});else{const s=[];o.text.length>0?s.push({type:"summary_text",text:o.text}):void 0!==n&&y.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(o)}.`}),void 0===n?(e[i]={type:"reasoning",id:i,encrypted_content:null==t?void 0:t.reasoningEncryptedContent,summary:s},f.push(e[i])):n.summary.push(...s)}}else y.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(o)}.`});break}}break}case"tool":for(const e of v){const t=e.output;if(a&&"local_shell"===e.toolName&&"json"===t.type){f.push({type:"local_shell_call_output",call_id:e.toolCallId,output:U.parse(t.value).output});break}let o;switch(t.type){case"text":case"error-text":o=t.value;break;case"content":case"json":case"error-json":o=JSON.stringify(t.value)}f.push({type:"function_call_output",call_id:e.toolCallId,output:o})}break;default:throw new Error(`Unsupported role: ${_}`)}return{input:f,warnings:y}}({prompt:p,systemMessageMode:k.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:null==(g=null==I?void 0:I.store)||g,hasLocalShellTool:T("openai.local_shell")});v.push(...Y);const j=null!=(f=null==I?void 0:I.strictJsonSchema)&&f;let w=null==I?void 0:I.include;function x(e){w=null!=w?[...w,e]:[e]}function T(e){return null!=(null==c?void 0:c.find(t=>"provider-defined"===t.type&&t.id===e))}const O="number"==typeof(null==I?void 0:I.logprobs)?null==I?void 0:I.logprobs:!0===(null==I?void 0:I.logprobs)?20:void 0;O&&x("message.output_text.logprobs");const q=null==(y=null==c?void 0:c.find(e=>"provider-defined"===e.type&&("openai.web_search"===e.id||"openai.web_search_preview"===e.id)))?void 0:y.name;q&&x("web_search_call.action.sources"),T("openai.code_interpreter")&&x("code_interpreter_call.outputs");const S={model:this.modelId,input:b,temperature:t,top_p:s,max_output_tokens:e,...("json"===(null==h?void 0:h.type)||(null==I?void 0:I.textVerbosity))&&{text:{..."json"===(null==h?void 0:h.type)&&{format:null!=h.schema?{type:"json_schema",strict:j,name:null!=(_=h.name)?_:"response",description:h.description,schema:h.schema}:{type:"json_object"}},...(null==I?void 0:I.textVerbosity)&&{verbosity:I.textVerbosity}}},max_tool_calls:null==I?void 0:I.maxToolCalls,metadata:null==I?void 0:I.metadata,parallel_tool_calls:null==I?void 0:I.parallelToolCalls,previous_response_id:null==I?void 0:I.previousResponseId,store:null==I?void 0:I.store,user:null==I?void 0:I.user,instructions:null==I?void 0:I.instructions,service_tier:null==I?void 0:I.serviceTier,include:w,prompt_cache_key:null==I?void 0:I.promptCacheKey,safety_identifier:null==I?void 0:I.safetyIdentifier,top_logprobs:O,...k.isReasoningModel&&(null!=(null==I?void 0:I.reasoningEffort)||null!=(null==I?void 0:I.reasoningSummary))&&{reasoning:{...null!=(null==I?void 0:I.reasoningEffort)&&{effort:I.reasoningEffort},...null!=(null==I?void 0:I.reasoningSummary)&&{summary:I.reasoningSummary}}},...k.requiredAutoTruncation&&{truncation:"auto"}};k.isReasoningModel?(null!=S.temperature&&(S.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=S.top_p&&(S.top_p=void 0,v.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==I?void 0:I.reasoningEffort)&&v.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==I?void 0:I.reasoningSummary)&&v.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==I?void 0:I.serviceTier)||k.supportsFlexProcessing||(v.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete S.service_tier),"priority"!==(null==I?void 0:I.serviceTier)||k.supportsPriorityProcessing||(v.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete S.service_tier);const{tools:C,toolChoice:M,toolWarnings:N}=function({tools:e,toolChoice:t,strictJsonSchema:o}){const n=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const t of e)switch(t.type){case"function":s.push({type:"function",name:t.name,description:t.description,parameters:t.inputSchema,strict:o});break;case"provider-defined":switch(t.id){case"openai.file_search":{const e=H.parse(t.args);s.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case"openai.local_shell":s.push({type:"local_shell"});break;case"openai.web_search_preview":{const e=G.parse(t.args);s.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.web_search":{const e=B.parse(t.args);s.push({type:"web_search",filters:null!=e.filters?{allowed_domains:e.filters.allowedDomains}:void 0,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=E.parse(t.args);s.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}case"openai.image_generation":{const e=z.parse(t.args);s.push({type:"image_generation",background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:n.push({type:"unsupported-tool",tool:t})}if(null==t)return{tools:s,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:n};case"tool":return{tools:s,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"image_generation"===t.toolName||"web_search_preview"===t.toolName||"web_search"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const e=a;throw new i.b8({functionality:`tool choice type: ${e}`})}}}({tools:c,toolChoice:m,strictJsonSchema:j});return{webSearchToolName:q,args:{...S,tools:C,tool_choice:M},warnings:[...v,...N]}}async doGenerate(e){var t,o,a,r,u,p,d,c,m,h,g,f,y,_,v,k,I,b,Y;const{args:j,warnings:w,webSearchToolName:x}=await this.getArgs(e),T=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:O,value:q,rawValue:S}=await(0,n.postJsonToApi)({url:T,headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:j,failedResponseHandler:l,successfulResponseHandler:(0,n.createJsonResponseHandler)(s.Ik({id:s.Yj(),created_at:s.ai(),error:s.Ik({code:s.Yj(),message:s.Yj()}).nullish(),model:s.Yj(),output:s.YO(s.gM("type",[s.Ik({type:s.eu("message"),role:s.eu("assistant"),id:s.Yj(),content:s.YO(s.Ik({type:s.eu("output_text"),text:s.Yj(),logprobs:ae.nullish(),annotations:s.YO(s.gM("type",[s.Ik({type:s.eu("url_citation"),start_index:s.ai(),end_index:s.ai(),url:s.Yj(),title:s.Yj()}),s.Ik({type:s.eu("file_citation"),file_id:s.Yj(),filename:s.Yj().nullish(),index:s.ai().nullish(),start_index:s.ai().nullish(),end_index:s.ai().nullish(),quote:s.Yj().nullish()}),s.Ik({type:s.eu("container_file_citation")})]))}))}),te,oe,ne,se,ie,s.Ik({type:s.eu("function_call"),call_id:s.Yj(),name:s.Yj(),arguments:s.Yj(),id:s.Yj()}),s.Ik({type:s.eu("computer_call"),id:s.Yj(),status:s.Yj().optional()}),s.Ik({type:s.eu("reasoning"),id:s.Yj(),encrypted_content:s.Yj().nullish(),summary:s.YO(s.Ik({type:s.eu("summary_text"),text:s.Yj()}))})])),service_tier:s.Yj().nullish(),incomplete_details:s.Ik({reason:s.Yj()}).nullish(),usage:le})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(q.error)throw new i.hL({message:q.error.message,url:T,requestBodyValues:j,statusCode:400,responseHeaders:O,responseBody:S,isRetryable:!1});const C=[],M=[];let N=!1;for(const i of q.output)switch(i.type){case"reasoning":0===i.summary.length&&i.summary.push({type:"summary_text",text:""});for(const e of i.summary)C.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:i.id,reasoningEncryptedContent:null!=(t=i.encrypted_content)?t:null}}});break;case"image_generation_call":C.push({type:"tool-call",toolCallId:i.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),C.push({type:"tool-result",toolCallId:i.id,toolName:"image_generation",result:{result:i.result},providerExecuted:!0});break;case"local_shell_call":C.push({type:"tool-call",toolCallId:i.call_id,toolName:"local_shell",input:JSON.stringify({action:i.action}),providerMetadata:{openai:{itemId:i.id}}});break;case"message":for(const t of i.content){(null==(a=null==(o=e.providerOptions)?void 0:o.openai)?void 0:a.logprobs)&&t.logprobs&&M.push(t.logprobs),C.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:i.id}}});for(const e of t.annotations)"url_citation"===e.type?C.push({type:"source",sourceType:"url",id:null!=(p=null==(u=(r=this.config).generateId)?void 0:u.call(r))?p:(0,n.generateId)(),url:e.url,title:e.title}):"file_citation"===e.type&&C.push({type:"source",sourceType:"document",id:null!=(m=null==(c=(d=this.config).generateId)?void 0:c.call(d))?m:(0,n.generateId)(),mediaType:"text/plain",title:null!=(g=null!=(h=e.quote)?h:e.filename)?g:"Document",filename:null!=(f=e.filename)?f:e.file_id})}break;case"function_call":N=!0,C.push({type:"tool-call",toolCallId:i.call_id,toolName:i.name,input:i.arguments,providerMetadata:{openai:{itemId:i.id}}});break;case"web_search_call":C.push({type:"tool-call",toolCallId:i.id,toolName:null!=x?x:"web_search",input:JSON.stringify({action:i.action}),providerExecuted:!0}),C.push({type:"tool-result",toolCallId:i.id,toolName:null!=x?x:"web_search",result:{status:i.status},providerExecuted:!0});break;case"computer_call":C.push({type:"tool-call",toolCallId:i.id,toolName:"computer_use",input:"",providerExecuted:!0}),C.push({type:"tool-result",toolCallId:i.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:i.status||"completed"},providerExecuted:!0});break;case"file_search_call":C.push({type:"tool-call",toolCallId:i.id,toolName:"file_search",input:"{}",providerExecuted:!0}),C.push({type:"tool-result",toolCallId:i.id,toolName:"file_search",result:{queries:i.queries,results:null!=(_=null==(y=i.results)?void 0:y.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text})))?_:null},providerExecuted:!0});break;case"code_interpreter_call":C.push({type:"tool-call",toolCallId:i.id,toolName:"code_interpreter",input:JSON.stringify({code:i.code,containerId:i.container_id}),providerExecuted:!0}),C.push({type:"tool-result",toolCallId:i.id,toolName:"code_interpreter",result:{outputs:i.outputs},providerExecuted:!0})}const R={openai:{responseId:q.id}};return M.length>0&&(R.openai.logprobs=M),"string"==typeof q.service_tier&&(R.openai.serviceTier=q.service_tier),{content:C,finishReason:ee({finishReason:null==(v=q.incomplete_details)?void 0:v.reason,hasFunctionCall:N}),usage:{inputTokens:q.usage.input_tokens,outputTokens:q.usage.output_tokens,totalTokens:q.usage.input_tokens+q.usage.output_tokens,reasoningTokens:null!=(I=null==(k=q.usage.output_tokens_details)?void 0:k.reasoning_tokens)?I:void 0,cachedInputTokens:null!=(Y=null==(b=q.usage.input_tokens_details)?void 0:b.cached_tokens)?Y:void 0},request:{body:j},response:{id:q.id,timestamp:new Date(1e3*q.created_at),modelId:q.model,headers:O,body:S},providerMetadata:R,warnings:w}}async doStream(e){const{args:t,warnings:o,webSearchToolName:i}=await this.getArgs(e),{responseHeaders:s,value:a}=await(0,n.postJsonToApi)({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:l,successfulResponseHandler:(0,n.createEventSourceResponseHandler)(Ie),abortSignal:e.abortSignal,fetch:this.config.fetch}),r=this;let u="unknown";const p={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d=[];let c=null;const m={};let h=!1;const g={};let f;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:o})},transform(t,o){var s,a,l,y,_,v,k,I,b,Y,j,w,x,T,O,q,S,C,M,N,R,E,$;if(e.includeRawChunks&&o.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return u="error",void o.enqueue({type:"error",error:t.error});const P=t.value;if(Ye(P))"function_call"===P.item.type?(m[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},o.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name})):"web_search_call"===P.item.type?(m[P.output_index]={toolName:null!=i?i:"web_search",toolCallId:P.item.id},o.enqueue({type:"tool-input-start",id:P.item.id,toolName:null!=i?i:"web_search",providerExecuted:!0})):"computer_call"===P.item.type?(m[P.output_index]={toolName:"computer_use",toolCallId:P.item.id},o.enqueue({type:"tool-input-start",id:P.item.id,toolName:"computer_use",providerExecuted:!0})):"code_interpreter_call"===P.item.type?(m[P.output_index]={toolName:"code_interpreter",toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},o.enqueue({type:"tool-input-start",id:P.item.id,toolName:"code_interpreter",providerExecuted:!0}),o.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`})):"file_search_call"===P.item.type?o.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):"image_generation_call"===P.item.type?o.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):"message"===P.item.type?o.enqueue({type:"text-start",id:P.item.id,providerMetadata:{openai:{itemId:P.item.id}}}):function(e){return Ye(e)&&"reasoning"===e.item.type}(P)&&(g[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:[0]},o.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{openai:{itemId:P.item.id,reasoningEncryptedContent:null!=(s=P.item.encrypted_content)?s:null}}}));else if(be(P)){if("function_call"===P.item.type)m[P.output_index]=void 0,h=!0,o.enqueue({type:"tool-input-end",id:P.item.call_id}),o.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{openai:{itemId:P.item.id}}});else if("web_search_call"===P.item.type)m[P.output_index]=void 0,o.enqueue({type:"tool-input-end",id:P.item.id}),o.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:"web_search",input:JSON.stringify({action:P.item.action}),providerExecuted:!0}),o.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:"web_search",result:{status:P.item.status},providerExecuted:!0});else if("computer_call"===P.item.type)m[P.output_index]=void 0,o.enqueue({type:"tool-input-end",id:P.item.id}),o.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),o.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:P.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===P.item.type)m[P.output_index]=void 0,o.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:"file_search",result:{queries:P.item.queries,results:null!=(l=null==(a=P.item.results)?void 0:a.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text})))?l:null},providerExecuted:!0});else if("code_interpreter_call"===P.item.type)m[P.output_index]=void 0,o.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:"code_interpreter",result:{outputs:P.item.outputs},providerExecuted:!0});else if("image_generation_call"===P.item.type)o.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:"image_generation",result:{result:P.item.result},providerExecuted:!0});else if("local_shell_call"===P.item.type)m[P.output_index]=void 0,o.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:P.item.action.command,timeoutMs:P.item.action.timeout_ms,user:P.item.action.user,workingDirectory:P.item.action.working_directory,env:P.item.action.env}}),providerMetadata:{openai:{itemId:P.item.id}}});else if("message"===P.item.type)o.enqueue({type:"text-end",id:P.item.id});else if(function(e){return be(e)&&"reasoning"===e.item.type}(P)){const e=g[P.item.id];for(const t of e.summaryParts)o.enqueue({type:"reasoning-end",id:`${P.item.id}:${t}`,providerMetadata:{openai:{itemId:P.item.id,reasoningEncryptedContent:null!=(y=P.item.encrypted_content)?y:null}}});delete g[P.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(P)){const e=m[P.output_index];null!=e&&o.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:P.delta})}else if(function(e){return"response.code_interpreter_call_code.delta"===e.type}(P)){const e=m[P.output_index];null!=e&&o.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:JSON.stringify(P.delta).slice(1,-1)})}else if(function(e){return"response.code_interpreter_call_code.done"===e.type}(P)){const e=m[P.output_index];null!=e&&(o.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:'"}'}),o.enqueue({type:"tool-input-end",id:e.toolCallId}),o.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:P.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else!function(e){return"response.created"===e.type}(P)?function(e){return"response.output_text.delta"===e.type}(P)?(o.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(null==(v=null==(_=e.providerOptions)?void 0:_.openai)?void 0:v.logprobs)&&P.logprobs&&d.push(P.logprobs)):function(e){return"response.reasoning_summary_part.added"===e.type}(P)?P.summary_index>0&&(null==(k=g[P.item_id])||k.summaryParts.push(P.summary_index),o.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{openai:{itemId:P.item_id,reasoningEncryptedContent:null!=(b=null==(I=g[P.item_id])?void 0:I.encryptedContent)?b:null}}})):function(e){return"response.reasoning_summary_text.delta"===e.type}(P)?o.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{openai:{itemId:P.item_id}}}):function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(P)?(u=ee({finishReason:null==(Y=P.response.incomplete_details)?void 0:Y.reason,hasFunctionCall:h}),p.inputTokens=P.response.usage.input_tokens,p.outputTokens=P.response.usage.output_tokens,p.totalTokens=P.response.usage.input_tokens+P.response.usage.output_tokens,p.reasoningTokens=null!=(w=null==(j=P.response.usage.output_tokens_details)?void 0:j.reasoning_tokens)?w:void 0,p.cachedInputTokens=null!=(T=null==(x=P.response.usage.input_tokens_details)?void 0:x.cached_tokens)?T:void 0,"string"==typeof P.response.service_tier&&(f=P.response.service_tier)):function(e){return"response.output_text.annotation.added"===e.type}(P)?"url_citation"===P.annotation.type?o.enqueue({type:"source",sourceType:"url",id:null!=(S=null==(q=(O=r.config).generateId)?void 0:q.call(O))?S:(0,n.generateId)(),url:P.annotation.url,title:P.annotation.title}):"file_citation"===P.annotation.type&&o.enqueue({type:"source",sourceType:"document",id:null!=(N=null==(M=(C=r.config).generateId)?void 0:M.call(C))?N:(0,n.generateId)(),mediaType:"text/plain",title:null!=(E=null!=(R=P.annotation.quote)?R:P.annotation.filename)?E:"Document",filename:null!=($=P.annotation.filename)?$:P.annotation.file_id}):function(e){return"error"===e.type}(P)&&o.enqueue({type:"error",error:P}):(c=P.response.id,o.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(1e3*P.response.created_at),modelId:P.response.model}))},flush(e){const t={openai:{responseId:c}};d.length>0&&(t.openai.logprobs=d),void 0!==f&&(t.openai.serviceTier=f),e.enqueue({type:"finish",finishReason:u,usage:p,providerMetadata:t})}})),request:{body:t},response:{headers:s}}}},le=s.Ik({input_tokens:s.ai(),input_tokens_details:s.Ik({cached_tokens:s.ai().nullish()}).nullish(),output_tokens:s.ai(),output_tokens_details:s.Ik({reasoning_tokens:s.ai().nullish()}).nullish()}),ue=s.Ik({type:s.eu("response.output_text.delta"),item_id:s.Yj(),delta:s.Yj(),logprobs:ae.nullish()}),pe=s.Ik({type:s.eu("error"),code:s.Yj(),message:s.Yj(),param:s.Yj().nullish(),sequence_number:s.ai()}),de=s.Ik({type:s.k5(["response.completed","response.incomplete"]),response:s.Ik({incomplete_details:s.Ik({reason:s.Yj()}).nullish(),usage:le,service_tier:s.Yj().nullish()})}),ce=s.Ik({type:s.eu("response.created"),response:s.Ik({id:s.Yj(),created_at:s.ai(),model:s.Yj(),service_tier:s.Yj().nullish()})}),me=s.Ik({type:s.eu("response.output_item.added"),output_index:s.ai(),item:s.gM("type",[s.Ik({type:s.eu("message"),id:s.Yj()}),s.Ik({type:s.eu("reasoning"),id:s.Yj(),encrypted_content:s.Yj().nullish()}),s.Ik({type:s.eu("function_call"),id:s.Yj(),call_id:s.Yj(),name:s.Yj(),arguments:s.Yj()}),s.Ik({type:s.eu("web_search_call"),id:s.Yj(),status:s.Yj(),action:s.Ik({type:s.eu("search"),query:s.Yj().optional()}).nullish()}),s.Ik({type:s.eu("computer_call"),id:s.Yj(),status:s.Yj()}),s.Ik({type:s.eu("file_search_call"),id:s.Yj()}),s.Ik({type:s.eu("image_generation_call"),id:s.Yj()}),s.Ik({type:s.eu("code_interpreter_call"),id:s.Yj(),container_id:s.Yj(),code:s.Yj().nullable(),outputs:s.YO(s.gM("type",[s.Ik({type:s.eu("logs"),logs:s.Yj()}),s.Ik({type:s.eu("image"),url:s.Yj()})])).nullable(),status:s.Yj()})])}),he=s.Ik({type:s.eu("response.output_item.done"),output_index:s.ai(),item:s.gM("type",[s.Ik({type:s.eu("message"),id:s.Yj()}),s.Ik({type:s.eu("reasoning"),id:s.Yj(),encrypted_content:s.Yj().nullish()}),s.Ik({type:s.eu("function_call"),id:s.Yj(),call_id:s.Yj(),name:s.Yj(),arguments:s.Yj(),status:s.eu("completed")}),ne,se,te,oe,ie,s.Ik({type:s.eu("computer_call"),id:s.Yj(),status:s.eu("completed")})])}),ge=s.Ik({type:s.eu("response.function_call_arguments.delta"),item_id:s.Yj(),output_index:s.ai(),delta:s.Yj()}),fe=s.Ik({type:s.eu("response.code_interpreter_call_code.delta"),item_id:s.Yj(),output_index:s.ai(),delta:s.Yj()}),ye=s.Ik({type:s.eu("response.code_interpreter_call_code.done"),item_id:s.Yj(),output_index:s.ai(),code:s.Yj()}),_e=s.Ik({type:s.eu("response.output_text.annotation.added"),annotation:s.gM("type",[s.Ik({type:s.eu("url_citation"),url:s.Yj(),title:s.Yj()}),s.Ik({type:s.eu("file_citation"),file_id:s.Yj(),filename:s.Yj().nullish(),index:s.ai().nullish(),start_index:s.ai().nullish(),end_index:s.ai().nullish(),quote:s.Yj().nullish()})])}),ve=s.Ik({type:s.eu("response.reasoning_summary_part.added"),item_id:s.Yj(),summary_index:s.ai()}),ke=s.Ik({type:s.eu("response.reasoning_summary_text.delta"),item_id:s.Yj(),summary_index:s.ai(),delta:s.Yj()}),Ie=s.KC([ue,de,ce,me,he,ge,fe,ye,_e,ve,ke,pe,s.Ik({type:s.Yj()}).loose()]);function be(e){return"response.output_item.done"===e.type}function Ye(e){return"response.output_item.added"===e.type}var je=s.Ik({include:s.YO(s.k5(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:s.Yj().nullish(),logprobs:s.KC([s.zM(),s.ai().min(1).max(20)]).optional(),maxToolCalls:s.ai().nullish(),metadata:s.bz().nullish(),parallelToolCalls:s.zM().nullish(),previousResponseId:s.Yj().nullish(),promptCacheKey:s.Yj().nullish(),reasoningEffort:s.Yj().nullish(),reasoningSummary:s.Yj().nullish(),safetyIdentifier:s.Yj().nullish(),serviceTier:s.k5(["auto","flex","priority"]).nullish(),store:s.zM().nullish(),strictJsonSchema:s.zM().nullish(),textVerbosity:s.k5(["low","medium","high"]).nullish(),user:s.Yj().nullish()}),we=s.Ik({instructions:s.Yj().nullish(),speed:s.ai().min(.25).max(4).default(1).nullish()}),xe=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:o="mp3",speed:i,instructions:s,language:a,providerOptions:r}){const l=[],u=await(0,n.parseProviderOptions)({provider:"openai",providerOptions:r,schema:we}),p={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:i,instructions:s};if(o&&(["mp3","opus","aac","flac","wav","pcm"].includes(o)?p.response_format=o:l.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${o}. Using mp3 instead.`})),u){const e={};for(const t in e){const o=e[t];void 0!==o&&(p[t]=o)}}return a&&l.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:p,warnings:l}}async doGenerate(e){var t,o,i;const s=null!=(i=null==(o=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:o.call(t))?i:new Date,{requestBody:a,warnings:r}=await this.getArgs(e),{value:u,responseHeaders:p,rawValue:d}=await(0,n.postJsonToApi)({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),body:a,failedResponseHandler:l,successfulResponseHandler:(0,n.createBinaryResponseHandler)(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:u,warnings:r,request:{body:JSON.stringify(a)},response:{timestamp:s,modelId:this.modelId,headers:p,body:d}}}},Te=s.Ik({include:s.YO(s.Yj()).optional(),language:s.Yj().optional(),prompt:s.Yj().optional(),temperature:s.ai().min(0).max(1).default(0).optional(),timestampGranularities:s.YO(s.k5(["word","segment"])).default(["segment"]).optional()}),Oe={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},qe=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:o}){const i=await(0,n.parseProviderOptions)({provider:"openai",providerOptions:o,schema:Te}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([(0,n.convertBase64ToUint8Array)(e)]);s.append("model",this.modelId);const r=(0,n.mediaTypeToExtension)(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${r}`),i){const e={include:i.include,language:i.language,prompt:i.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(const[t,o]of Object.entries(e))if(null!=o)if(Array.isArray(o))for(const e of o)s.append(`${t}[]`,String(e));else s.append(t,String(o))}return{formData:s,warnings:[]}}async doGenerate(e){var t,o,i,s,a,r,u,p;const d=null!=(i=null==(o=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:o.call(t))?i:new Date,{formData:c,warnings:m}=await this.getArgs(e),{value:h,responseHeaders:g,rawValue:f}=await(0,n.postFormDataToApi)({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:(0,n.combineHeaders)(this.config.headers(),e.headers),formData:c,failedResponseHandler:l,successfulResponseHandler:(0,n.createJsonResponseHandler)(Se),abortSignal:e.abortSignal,fetch:this.config.fetch}),y=null!=h.language&&h.language in Oe?Oe[h.language]:void 0;return{text:h.text,segments:null!=(u=null!=(r=null==(s=h.segments)?void 0:s.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))?r:null==(a=h.words)?void 0:a.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))?u:[],language:y,durationInSeconds:null!=(p=h.duration)?p:void 0,warnings:m,response:{timestamp:d,modelId:this.modelId,headers:g,body:f}}}},Se=s.Ik({text:s.Yj(),language:s.Yj().nullish(),duration:s.ai().nullish(),words:s.YO(s.Ik({word:s.Yj(),start:s.ai(),end:s.ai()})).nullish(),segments:s.YO(s.Ik({id:s.ai(),seek:s.ai(),start:s.ai(),end:s.ai(),text:s.Yj(),tokens:s.YO(s.ai()),temperature:s.ai(),avg_logprob:s.ai(),compression_ratio:s.ai(),no_speech_prob:s.ai()})).nullish()}),Ce="2.0.44";function Me(e={}){var t,o;const i=null!=(t=(0,n.withoutTrailingSlash)((0,n.loadOptionalSetting)({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))?t:"https://api.openai.com/v1",s=null!=(o=e.name)?o:"openai",a=()=>(0,n.withUserAgentSuffix)({Authorization:`Bearer ${(0,n.loadApiKey)({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Ce}`),r=t=>new T(t,{provider:`${s}.embedding`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch}),l=t=>new C(t,{provider:`${s}.image`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch}),u=t=>new qe(t,{provider:`${s}.transcription`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch}),p=t=>new xe(t,{provider:`${s}.speech`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch}),d=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return m(e)},m=t=>new re(t,{provider:`${s}.responses`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch,fileIdPrefixes:["file-"]}),h=function(e){return d(e)};return h.languageModel=d,h.chat=t=>new c(t,{provider:`${s}.chat`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch}),h.completion=t=>new b(t,{provider:`${s}.completion`,url:({path:e})=>`${i}${e}`,headers:a,fetch:e.fetch}),h.responses=m,h.embedding=r,h.textEmbedding=r,h.textEmbeddingModel=r,h.image=l,h.imageModel=l,h.transcription=u,h.transcriptionModel=u,h.speech=p,h.speechModel=p,h.tools=Z,h}var Ne=Me()}}]);
@@ -0,0 +1 @@
1
+ "use strict";(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[313,694],{3313:(e,t,s)=>{s.r(t),s.d(t,{ISecretsManager:()=>l,InMemoryConnector:()=>d,LocalStorageConnector:()=>u,SecretsManager:()=>c,default:()=>p});var i,n=s(9816),r=s(3603),a=s(7262),o=s(4602);class c{constructor(e){var t;this._onInput=async e=>{var t;await this.storing,this._storing=new a.PromiseDelegate;const s=e.target,{namespace:n,id:r}=null!==(t=i.secretPath.get(s))&&void 0!==t?t:{};if(n&&r){const e=i.buildConnectorId(n,r);await this.ready,await i.set(e,{namespace:n,id:r,value:s.value})}this._storing.resolve()},this._ready=new a.PromiseDelegate,this._fieldsVisibilityChanged=new o.Signal(this),this._storing=new a.PromiseDelegate,this._storing.resolve(),i.setSecretFieldsVisibility(null!==(t=e.showSecretFields)&&void 0!==t&&t),!1===e.showSecretFields&&i.lockFieldsVisibility()}setConnector(e){i.setConnector(e),this._ready.resolve()}get ready(){return this._ready.promise}get storing(){return this._storing.promise}get fieldVisibilityChanged(){return this._fieldsVisibilityChanged}get secretFieldsVisibility(){return i.getSecretFieldsVisibility()}set secretFieldsVisibility(e){i.setSecretFieldsVisibility(e)&&this._fieldsVisibilityChanged.emit(i.getSecretFieldsVisibility())}async get(e,t,s){return i.checkNamespace(e,t),await Promise.all([this.ready,this.storing]),i.get(i.buildConnectorId(t,s))}async set(e,t,s,n){return i.checkNamespace(e,t),await this.ready,i.set(i.buildConnectorId(t,s),n)}async list(e,t){return i.checkNamespace(e,t),await Promise.all([this.ready,this.storing]),i.list(t)}async remove(e,t,s){return i.checkNamespace(e,t),await this.ready,i.remove(i.buildConnectorId(t,s))}async attach(e,t,s,n,r){i.checkNamespace(e,t);const a=i.buildConnectorId(t,s);i.inputs.get(a)&&this.detach(e,t,s),i.inputs.set(a,n),i.secretPath.set(n,{namespace:t,id:s});const o=await i.get(a);!n.value&&o?(n.value=o.value,n.dispatchEvent(new Event("input")),r&&r(o.value)):n.value&&n.value!==(null==o?void 0:o.value)&&(await this.ready,i.set(a,{namespace:t,id:s,value:n.value})),n.addEventListener("input",this._onInput)}async detach(e,t,s){i.checkNamespace(e,t),this._detach(i.buildConnectorId(t,s))}async detachAll(e,t){i.checkNamespace(e,t);for(const e of i.secretPath.values())e.namespace===t&&this._detach(i.buildConnectorId(e.namespace,e.id))}_detach(e){const t=i.inputs.get(e);t&&(t.removeEventListener("input",this._onInput),i.secretPath.delete(t),i.inputs.delete(e))}}Object.freeze(c.prototype),function(e){e.sign=function(e,t){const{lock:s,isLocked:n,namespaces:a,symbols:o}=i,{isDisabled:c}=r.PageConfig.Extension;if(n())throw new Error("Secrets manager is locked, check errors.");c("jupyter-secrets-manager:manager")&&(console.warn("Secrets manager is disabled."),s()),c(e)&&s(`Sign error: plugin ${e} is disabled.`),o.has(e)&&s(`Sign error: another plugin signed as "${e}".`);const l=Symbol(e),d=t(l);return e!==d.id&&s(`Sign error: plugin ID mismatch "${d.id}"≠"${e}".`),a.set(l,e),o.set(e,l),d}}(c||(c={})),function(e){let t=!1;function s(e){if(t=!0,e)throw new Error(e)}function i(){return t}e.namespaces=new Map,e.symbols=new Map,e.lock=s,e.isLocked=i,e.checkNamespace=function(t,s){if(i()||e.namespaces.get(t)!==s)throw new Error(`The secrets namespace ${s} is not available with the provided token`)};let n=null;e.setConnector=function(e){null!==n&&s("A secrets manager connector already exists."),n=e},e.get=async function(e){if(null==n?void 0:n.fetch)return n.fetch(e)},e.list=async function(e){if(null==n?void 0:n.list)return n.list(e)},e.set=async function(e,t){if(null==n?void 0:n.save)return n.save(e,t)},e.remove=async function(e){if(null==n?void 0:n.remove)return n.remove(e)};let r=!1;e.lockFieldsVisibility=function(){r=!0};let a=!1;e.getSecretFieldsVisibility=function(){return a},e.setSecretFieldsVisibility=function(e){return!r&&e!==a&&(a=e,!0)},e.inputs=new Map,e.secretPath=new Map,e.buildConnectorId=function(e,t){return`${e}:${t}`}}(i||(i={}));const l=new a.Token("jupyter-secret-manager:manager","The secrets manager");class d{constructor(){this._secrets=new Map}async fetch(e){return this._secrets.get(e)}async save(e,t){this._secrets.set(e,t)}async remove(e){this._secrets.delete(e)}async list(e){const t=[],s=[];return this._secrets.forEach((i,n)=>{i.namespace===e&&(t.push(n),s.push(i))}),{ids:t,values:s}}}class u{constructor(){this.storage="jupyter-secrets:secrets",console.warn("\nThe secret connector used currently should not be used in production, since the\npasswords are stored as plain text in the local storage of the browser'\n ")}async fetch(e){var t;const s=JSON.parse(null!==(t=localStorage.getItem(this.storage))&&void 0!==t?t:"{}");if(s&&s[e])return s[e]}async save(e,t){var s;const i=JSON.parse(null!==(s=localStorage.getItem(this.storage))&&void 0!==s?s:"{}");i[e]=t,localStorage.setItem(this.storage,JSON.stringify(i))}async remove(e){var t;const s=JSON.parse(null!==(t=localStorage.getItem(this.storage))&&void 0!==t?t:"{}");delete s[e],localStorage.setItem(this.storage,JSON.stringify(s))}async list(e){var t;const s=JSON.parse(null!==(t=localStorage.getItem(this.storage))&&void 0!==t?t:"{}");return Object.keys(s).filter(t=>s[t].namespace===e).reduce((e,t)=>(e.ids.push(t),e.values.push(s[t]),e),{ids:[],values:[]})}}const h={id:"jupyter-secrets-manager:connector",description:"A JupyterLab extension to manage secrets.",autoStart:!0,requires:[l],activate:(e,t)=>{t.setConnector(new d)}},g={id:"jupyter-secrets-manager:manager",description:"A JupyterLab extension to manage secrets.",autoStart:!0,provides:l,optional:[n.ISettingRegistry],activate:(e,t)=>{let s=!0;"false"===r.PageConfig.getOption("secretsManager-showFields")&&(s=!1);const i=new c({showSecretFields:s});return t.load(g.id).then(e=>{var t;if(!s)return void(null===(t=e.schema.properties)||void 0===t||delete t.ShowSecretFields);const n=()=>{var t;const s=null!==(t=e.get("ShowSecretFields").composite)&&void 0!==t&&t;i.secretFieldsVisibility=s};e.changed.connect(()=>n()),n()}).catch(e=>{console.error(`Failed to load settings for ${g.id}`,e)}),console.debug("JupyterLab extension jupyter-secrets-manager is activated!"),i}},p=[h,g]}}]);
@@ -0,0 +1 @@
1
+ "use strict";(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[324],{1408:(e,t,r)=>{r.d(t,{Z:()=>i});class o extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function n(e){}class i extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let i;super({start(s){i=function(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=n,onError:r=n,onRetry:i=n,onComment:s}=e;let a,c="",l=!0,d="",u="";function p(e){if(""===e)return d.length>0&&t({id:a,event:u||void 0,data:d.endsWith("\n")?d.slice(0,-1):d}),a=void 0,d="",void(u="");if(e.startsWith(":"))return void(s&&s(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),o=" "===e[r+1]?2:1;return void h(t,e.slice(r+o),e)}h(e,"",e)}function h(e,t,n){switch(e){case"event":u=t;break;case"data":d=`${d}${t}\n`;break;case"id":a=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?i(parseInt(t,10)):r(new o(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new o(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){const t=l?e.replace(/^\xEF\xBB\xBF/,""):e,[r,o]=function(e){const t=[];let r="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),i=e.indexOf("\n",o);let s=-1;if(-1!==n&&-1!==i?s=Math.min(n,i):-1!==n?s=n===e.length-1?-1:n:-1!==i&&(s=i),-1===s){r=e.slice(o);break}{const r=e.slice(o,s);t.push(r),o=s+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[t,r]}(`${c}${t}`);for(const e of r)p(e);c=o,l=!1},reset:function(e={}){c&&e.consume&&p(c),l=!0,a=void 0,d="",u="",c=""}}}({onEvent:e=>{s.enqueue(e)},onError(t){"terminate"===e?s.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){i.feed(e)}})}}},2324:(e,t,r)=>{r.d(t,{StreamableHTTPClientTransport:()=>Z});var o=r(8092);let n;async function i(e){const t=await(await n).subtle.digest("SHA-256",(new TextEncoder).encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function s(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await async function(e){return await async function(e){let t="";const r=await async function(e){return(await n).getRandomValues(new Uint8Array(e))}(e);for(let o=0;o<e;o++)t+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[r[o]%66];return t}(e)}(e);return{code_verifier:t,code_challenge:await i(t)}}n=globalThis.crypto;var a=r(9661);const c=a.z.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:a.z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),a.z.NEVER}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),l=a.z.object({resource:a.z.string().url(),authorization_servers:a.z.array(c).optional(),jwks_uri:a.z.string().url().optional(),scopes_supported:a.z.array(a.z.string()).optional(),bearer_methods_supported:a.z.array(a.z.string()).optional(),resource_signing_alg_values_supported:a.z.array(a.z.string()).optional(),resource_name:a.z.string().optional(),resource_documentation:a.z.string().optional(),resource_policy_uri:a.z.string().url().optional(),resource_tos_uri:a.z.string().url().optional(),tls_client_certificate_bound_access_tokens:a.z.boolean().optional(),authorization_details_types_supported:a.z.array(a.z.string()).optional(),dpop_signing_alg_values_supported:a.z.array(a.z.string()).optional(),dpop_bound_access_tokens_required:a.z.boolean().optional()}).passthrough(),d=a.z.object({issuer:a.z.string(),authorization_endpoint:c,token_endpoint:c,registration_endpoint:c.optional(),scopes_supported:a.z.array(a.z.string()).optional(),response_types_supported:a.z.array(a.z.string()),response_modes_supported:a.z.array(a.z.string()).optional(),grant_types_supported:a.z.array(a.z.string()).optional(),token_endpoint_auth_methods_supported:a.z.array(a.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:a.z.array(a.z.string()).optional(),service_documentation:c.optional(),revocation_endpoint:c.optional(),revocation_endpoint_auth_methods_supported:a.z.array(a.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:a.z.array(a.z.string()).optional(),introspection_endpoint:a.z.string().optional(),introspection_endpoint_auth_methods_supported:a.z.array(a.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:a.z.array(a.z.string()).optional(),code_challenge_methods_supported:a.z.array(a.z.string()).optional()}).passthrough(),u=a.z.object({issuer:a.z.string(),authorization_endpoint:c,token_endpoint:c,userinfo_endpoint:c.optional(),jwks_uri:c,registration_endpoint:c.optional(),scopes_supported:a.z.array(a.z.string()).optional(),response_types_supported:a.z.array(a.z.string()),response_modes_supported:a.z.array(a.z.string()).optional(),grant_types_supported:a.z.array(a.z.string()).optional(),acr_values_supported:a.z.array(a.z.string()).optional(),subject_types_supported:a.z.array(a.z.string()),id_token_signing_alg_values_supported:a.z.array(a.z.string()),id_token_encryption_alg_values_supported:a.z.array(a.z.string()).optional(),id_token_encryption_enc_values_supported:a.z.array(a.z.string()).optional(),userinfo_signing_alg_values_supported:a.z.array(a.z.string()).optional(),userinfo_encryption_alg_values_supported:a.z.array(a.z.string()).optional(),userinfo_encryption_enc_values_supported:a.z.array(a.z.string()).optional(),request_object_signing_alg_values_supported:a.z.array(a.z.string()).optional(),request_object_encryption_alg_values_supported:a.z.array(a.z.string()).optional(),request_object_encryption_enc_values_supported:a.z.array(a.z.string()).optional(),token_endpoint_auth_methods_supported:a.z.array(a.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:a.z.array(a.z.string()).optional(),display_values_supported:a.z.array(a.z.string()).optional(),claim_types_supported:a.z.array(a.z.string()).optional(),claims_supported:a.z.array(a.z.string()).optional(),service_documentation:a.z.string().optional(),claims_locales_supported:a.z.array(a.z.string()).optional(),ui_locales_supported:a.z.array(a.z.string()).optional(),claims_parameter_supported:a.z.boolean().optional(),request_parameter_supported:a.z.boolean().optional(),request_uri_parameter_supported:a.z.boolean().optional(),require_request_uri_registration:a.z.boolean().optional(),op_policy_uri:c.optional(),op_tos_uri:c.optional()}).passthrough().merge(d.pick({code_challenge_methods_supported:!0})),p=a.z.object({access_token:a.z.string(),id_token:a.z.string().optional(),token_type:a.z.string(),expires_in:a.z.number().optional(),scope:a.z.string().optional(),refresh_token:a.z.string().optional()}).strip(),h=a.z.object({error:a.z.string(),error_description:a.z.string().optional(),error_uri:a.z.string().optional()}),_=a.z.object({redirect_uris:a.z.array(c),token_endpoint_auth_method:a.z.string().optional(),grant_types:a.z.array(a.z.string()).optional(),response_types:a.z.array(a.z.string()).optional(),client_name:a.z.string().optional(),client_uri:c.optional(),logo_uri:c.optional(),scope:a.z.string().optional(),contacts:a.z.array(a.z.string()).optional(),tos_uri:c.optional(),policy_uri:a.z.string().optional(),jwks_uri:c.optional(),jwks:a.z.any().optional(),software_id:a.z.string().optional(),software_version:a.z.string().optional(),software_statement:a.z.string().optional()}).strip(),f=a.z.object({client_id:a.z.string(),client_secret:a.z.string().optional(),client_id_issued_at:a.z.number().optional(),client_secret_expires_at:a.z.number().optional()}).strip(),w=_.merge(f);a.z.object({error:a.z.string(),error_description:a.z.string().optional()}).strip(),a.z.object({token:a.z.string(),token_type_hint:a.z.string().optional()}).strip();class g extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class v extends g{}v.errorCode="invalid_request";class m extends g{}m.errorCode="invalid_client";class y extends g{}y.errorCode="invalid_grant";class z extends g{}z.errorCode="unauthorized_client";class k extends g{}k.errorCode="unsupported_grant_type";class b extends g{}b.errorCode="invalid_scope";class C extends g{}C.errorCode="access_denied";class U extends g{}U.errorCode="server_error";class R extends g{}R.errorCode="temporarily_unavailable";class E extends g{}E.errorCode="unsupported_response_type";class T extends g{}T.errorCode="unsupported_token_type";class x extends g{}x.errorCode="invalid_token";class S extends g{}S.errorCode="method_not_allowed";class I extends g{}I.errorCode="too_many_requests";class P extends g{}P.errorCode="invalid_client_metadata";class $ extends g{}$.errorCode="insufficient_scope";const A={[v.errorCode]:v,[m.errorCode]:m,[y.errorCode]:y,[z.errorCode]:z,[k.errorCode]:k,[b.errorCode]:b,[C.errorCode]:C,[U.errorCode]:U,[R.errorCode]:R,[E.errorCode]:E,[T.errorCode]:T,[x.errorCode]:x,[S.errorCode]:S,[I.errorCode]:I,[P.errorCode]:P,[$.errorCode]:$};class O extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function j(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function L(e,t,r,o){const{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}(n,i,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(n,i,o);case"none":return void function(e,t){t.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function M(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=h.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(A[t]||U)(o||"",n)}catch(e){return new U(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function F(e,t){var r,o;try{return await H(e,t)}catch(n){if(n instanceof m||n instanceof z)return await(null===(r=e.invalidateCredentials)||void 0===r?void 0:r.call(e,"all")),await H(e,t);if(n instanceof y)return await(null===(o=e.invalidateCredentials)||void 0===o?void 0:o.call(e,"tokens")),await H(e,t);throw n}}async function H(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:a}){let c,h;try{c=await async function(e,t,r=fetch){const n=await async function(e,t,r,n){var i,s;const a=new URL(e),c=null!==(i=null==n?void 0:n.protocolVersion)&&void 0!==i?i:o.aE;let l;if(null==n?void 0:n.metadataUrl)l=new URL(n.metadataUrl);else{const e=function(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,a.pathname);l=new URL(e,null!==(s=null==n?void 0:n.metadataServerUrl)&&void 0!==s?s:a),l.search=a.search}let d=await V(l,c,r);if(!(null==n?void 0:n.metadataUrl)&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(d,a.pathname)){const e=new URL(`/.well-known/${t}`,a);d=await V(e,c,r)}return d}(e,"oauth-protected-resource",r,{protocolVersion:null==t?void 0:t.protocolVersion,metadataUrl:null==t?void 0:t.resourceMetadataUrl});if(!n||404===n.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return l.parse(await n.json())}(t,{resourceMetadataUrl:i},a),c.authorization_servers&&c.authorization_servers.length>0&&(h=c.authorization_servers[0])}catch(e){}h||(h=t);const _=await async function(e,t,r){const o=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(o,null==r?void 0:r.resource);if(r){if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}(t,e,c),f=await async function(e,{fetchFn:t=fetch,protocolVersion:r=o.aE}={}){var n;const i={"MCP-Protocol-Version":r},s=function(e){const t="string"==typeof e?new URL(e):e,r=[];if(!("/"!==t.pathname))return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),r.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}(e);for(const{url:e,type:r}of s){const o=await q(e,i,t);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}if("oauth"===r)return d.parse(await o.json());{const t=u.parse(await o.json());if(!(null===(n=t.code_challenge_methods_supported)||void 0===n?void 0:n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}(h,{fetchFn:a});let v=await Promise.resolve(e.clientInformation());if(!v){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const i=await(null!=o?o:fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw await M(i);return w.parse(await i.json())}(h,{metadata:f,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(t),v=t}if(void 0!==r){const t=await e.codeVerifier(),o=await async function(e,{metadata:t,clientInformation:r,authorizationCode:o,codeVerifier:n,redirectUri:i,resource:s,addClientAuthentication:a,fetchFn:c}){var l;const d="authorization_code",u=(null==t?void 0:t.token_endpoint)?new URL(t.token_endpoint):new URL("/token",e);if((null==t?void 0:t.grant_types_supported)&&!t.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),_=new URLSearchParams({grant_type:d,code:o,code_verifier:n,redirect_uri:String(i)});a?a(h,_,e,t):L(j(r,null!==(l=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==l?l:[]),r,h,_),s&&_.set("resource",s.href);const f=await(null!=c?c:fetch)(u,{method:"POST",headers:h,body:_});if(!f.ok)throw await M(f);return p.parse(await f.json())}(h,{metadata:f,clientInformation:v,authorizationCode:r,codeVerifier:t,redirectUri:e.redirectUrl,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(o),"AUTHORIZED"}const m=await e.tokens();if(null==m?void 0:m.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:s}){var a;const c="refresh_token";let l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),u=new URLSearchParams({grant_type:c,refresh_token:o});i?i(d,u,e,t):L(j(r,null!==(a=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==a?a:[]),r,d,u),n&&u.set("resource",n.href);const h=await(null!=s?s:fetch)(l,{method:"POST",headers:d,body:u});if(!h.ok)throw await M(h);return p.parse({refresh_token:o,...await h.json()})}(h,{metadata:f,clientInformation:v,refreshToken:m.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof g&&!(e instanceof U))throw e}const y=e.state?await e.state():void 0,{authorizationUrl:z,codeVerifier:k}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:a}){const c="code",l="S256";let d;if(t){if(d=new URL(t.authorization_endpoint),!t.response_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support response type ${c}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else d=new URL("/authorize",e);const u=await s(),p=u.code_verifier,h=u.code_challenge;return d.searchParams.set("response_type",c),d.searchParams.set("client_id",r.client_id),d.searchParams.set("code_challenge",h),d.searchParams.set("code_challenge_method",l),d.searchParams.set("redirect_uri",String(o)),i&&d.searchParams.set("state",i),n&&d.searchParams.set("scope",n),(null==n?void 0:n.includes("offline_access"))&&d.searchParams.append("prompt","consent"),a&&d.searchParams.set("resource",a.href),{authorizationUrl:d,codeVerifier:p}}(h,{metadata:f,clientInformation:v,state:y,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:_});return await e.saveCodeVerifier(k),await e.redirectToAuthorization(z),"REDIRECT"}async function q(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?q(e,void 0,r):void 0;throw o}}async function V(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await q(e,o,r)}var D=r(1408);const W={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class N extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Z{constructor(e,t){var r;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==t?void 0:t.requestInit,this._authProvider=null==t?void 0:t.authProvider,this._fetch=null==t?void 0:t.fetch,this._sessionId=null==t?void 0:t.sessionId,this._reconnectionOptions=null!==(r=null==t?void 0:t.reconnectionOptions)&&void 0!==r?r:W}async _authThenStart(){var e;if(!this._authProvider)throw new O("No auth provider");let t;try{t=await F(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}if("AUTHORIZED"!==t)throw new O;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const t={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(t.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...t,...r})}async _startOrAuthSse(e){var t,r,o;const{resumptionToken:n}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),n&&o.set("last-event-id",n);const i=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,{method:"GET",headers:o,signal:null===(r=this._abortController)||void 0===r?void 0:r.signal});if(!i.ok){if(401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new N(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}_getNextReconnectionDelay(e){const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var r;const o=this._reconnectionOptions.maxRetries;if(o>0&&t>=o)return void(null===(r=this.onerror)||void 0===r||r.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`)));const n=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var o;null===(o=this.onerror)||void 0===o||o.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:i}=t;let s;(async()=>{var t,a,c,l;try{const r=e.pipeThrough(new TextDecoderStream).pipeThrough(new D.Z).getReader();for(;;){const{value:e,done:c}=await r.read();if(c)break;if(e.id&&(s=e.id,null==n||n(e.id)),!e.event||"message"===e.event)try{const r=o.OR.parse(JSON.parse(e.data));void 0!==i&&(0,o.tG)(r)&&(r.id=i),null===(t=this.onmessage)||void 0===t||t.call(this,r)}catch(e){null===(a=this.onerror)||void 0===a||a.call(this,e)}}}catch(e){if(null===(c=this.onerror)||void 0===c||c.call(this,new Error(`SSE stream disconnected: ${e}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(e){null===(l=this.onerror)||void 0===l||l.call(this,new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new O("No auth provider");if("AUTHORIZED"!==await F(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new O("Failed to authorize")}async close(){var e,t;null===(e=this._abortController)||void 0===e||e.abort(),null===(t=this.onclose)||void 0===t||t.call(this)}async send(e,t){var r,n,i,s;try{const{resumptionToken:s,onresumptiontoken:a}=t||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:(0,o.vo)(e)?e.id:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)});const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const l={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:null===(r=this._abortController)||void 0===r?void 0:r.signal},d=await(null!==(n=this._fetch)&&void 0!==n?n:fetch)(this._url,l),u=d.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!d.ok){if(401===d.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new N(401,"Server returned 401 after successful authentication");if(this._resourceMetadataUrl=function(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return;const n=/resource_metadata="([^"]*)"/.exec(t);if(n)try{return new URL(n[1])}catch(e){return}}(d),"AUTHORIZED"!==await F(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new O;return this._hasCompletedAuthFlow=!0,this.send(e)}const t=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${t}`)}if(this._hasCompletedAuthFlow=!1,202===d.status)return void((0,o.wU)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)}));const p=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,h=d.headers.get("content-type");if(p)if(null==h?void 0:h.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:a},!1);else{if(!(null==h?void 0:h.includes("application/json")))throw new N(-1,`Unexpected content type: ${h}`);{const e=await d.json(),t=Array.isArray(e)?e.map(e=>o.OR.parse(e)):[o.OR.parse(e)];for(const e of t)null===(i=this.onmessage)||void 0===i||i.call(this,e)}}}catch(e){throw null===(s=this.onerror)||void 0===s||s.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,r;if(this._sessionId)try{const r=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:r,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},n=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,o);if(!n.ok&&405!==n.status)throw new N(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw null===(r=this.onerror)||void 0===r||r.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}}}]);
@@ -0,0 +1 @@
1
+ "use strict";(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[340],{340:(e,t,s)=>{s.r(t),s.d(t,{Agent:()=>n.g6,AgentHooks:()=>n.u9,AgentsError:()=>n.pf,BatchTraceProcessor:()=>n.AF,ConsoleSpanExporter:()=>n.VD,GuardrailExecutionError:()=>n.yZ,Handoff:()=>n.Pj,InputGuardrailTripwireTriggered:()=>n.Fb,MCPServerSSE:()=>n.p2,MCPServerStdio:()=>n.l6,MCPServerStreamableHttp:()=>n.Wm,MaxTurnsExceededError:()=>n.MP,ModelBehaviorError:()=>n.af,NoopSpan:()=>n.fz,NoopTrace:()=>n.ih,OPENAI_DEFAULT_MODEL_ENV_VARIABLE_NAME:()=>n.ST,OpenAIChatCompletionsModel:()=>Yn,OpenAIProvider:()=>er,OpenAIResponsesModel:()=>Hn,OpenAITracingExporter:()=>tr,OutputGuardrailTripwireTriggered:()=>n.K6,RunAgentUpdatedStreamEvent:()=>n.gm,RunContext:()=>n.ZI,RunHandoffCallItem:()=>n.f_,RunHandoffOutputItem:()=>n.AU,RunItemStreamEvent:()=>n.R1,RunMessageOutputItem:()=>n.js,RunRawModelStreamEvent:()=>n.zG,RunReasoningItem:()=>n.ZS,RunResult:()=>n.ns,RunState:()=>n.ll,RunToolApprovalItem:()=>n.A9,RunToolCallItem:()=>n.nM,RunToolCallOutputItem:()=>n.KR,Runner:()=>n.by,RuntimeEventEmitter:()=>n.j3,Span:()=>n.L9,StreamedRunResult:()=>n.A1,SystemError:()=>n._N,ToolCallError:()=>n.Du,Trace:()=>n.Cn,TraceProvider:()=>n.hh,Usage:()=>n._U,UserError:()=>n.yo,addTraceProcessor:()=>n.VP,assistant:()=>n.h1,codeInterpreterTool:()=>En,computerTool:()=>n.ab,createAgentSpan:()=>n.M6,createCustomSpan:()=>n.ub,createFunctionSpan:()=>n.tQ,createGenerationSpan:()=>n.Xq,createGuardrailSpan:()=>n.Eu,createHandoffSpan:()=>n.DT,createMCPListToolsSpan:()=>n.ux,createMCPToolStaticFilter:()=>n.V4,createResponseSpan:()=>n.UI,createSpeechGroupSpan:()=>n.it,createSpeechSpan:()=>n.tL,createTranscriptionSpan:()=>n.B9,defineOutputGuardrail:()=>n._o,extractAllTextOutput:()=>n.ZV,fileSearchTool:()=>Tn,generateGroupId:()=>n.uA,generateSpanId:()=>n.ZF,generateTraceId:()=>n.el,getAllMcpTools:()=>n.Ph,getCurrentSpan:()=>n.YP,getCurrentTrace:()=>n.Co,getDefaultModel:()=>n.fZ,getDefaultModelSettings:()=>n.sL,getGlobalTraceProvider:()=>n.At,getHandoff:()=>n.Pu,getLogger:()=>n.tZ,getOrCreateTrace:()=>n.Nn,getTransferMessage:()=>n.Nx,gpt5ReasoningSettingsRequired:()=>n.Z5,handoff:()=>n.NS,hostedMcpTool:()=>n.cp,imageGenerationTool:()=>Cn,invalidateServerToolsCache:()=>n.qi,isGpt5Default:()=>n.w_,mcpToFunctionTool:()=>n.y6,protocol:()=>n.TB,realtime:()=>nr,resetCurrentSpan:()=>n.h6,run:()=>n.eF,setCurrentSpan:()=>n.mq,setDefaultModelProvider:()=>n.MJ,setDefaultOpenAIClient:()=>bn,setDefaultOpenAIKey:()=>xn,setDefaultOpenAITracingExporter:()=>sr,setOpenAIAPI:()=>vn,setTraceProcessors:()=>n.JA,setTracingDisabled:()=>n.dr,setTracingExportApiKey:()=>wn,startTraceExportLoop:()=>n.Qv,system:()=>n.qU,tool:()=>n.z6,user:()=>n.kQ,webSearchTool:()=>On,withAgentSpan:()=>n.mp,withCustomSpan:()=>n.Ee,withFunctionSpan:()=>n.PJ,withGenerationSpan:()=>n.hn,withGuardrailSpan:()=>n.cS,withHandoffSpan:()=>n.$t,withMCPListToolsSpan:()=>n.cW,withResponseSpan:()=>n.Cp,withSpeechGroupSpan:()=>n.UC,withSpeechSpan:()=>n.L0,withTrace:()=>n.SZ,withTranscriptionSpan:()=>n.LG});var n=s(6162);function r(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s}function o(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}let i=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return i=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^s()&15>>+e/4).toString(16))};var a=s(2588);const l=/^[a-z][a-z0-9+.-]*:/i;let c=e=>(c=Array.isArray,c(e)),u=c;function d(e){return"object"!=typeof e?{}:e??{}}function p(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const h=e=>new Promise(t=>setTimeout(t,e));var f=s(921);const m="5.23.2",g=()=>{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":m,"X-Stainless-OS":y(Deno.build.os),"X-Stainless-Arch":_(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":m,"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":m,"X-Stainless-OS":y(globalThis.process.platform??"unknown"),"X-Stainless-Arch":_(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;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e)return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":m,"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":m,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},_=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",y=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";let w;function v(...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 b(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return v({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function x(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}}}const S=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),A="RFC3986",D=e=>String(e),k={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:D};let I=(e,t)=>(I=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),I(e,t));const $=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),R=1024;function O(e,t){if(c(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const T={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},E=function(e,t){Array.prototype.push.apply(e,c(t)?t:[t])};let C;const P={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let o=e;if("symbol"==typeof e?o=Symbol.prototype.toString.call(e):"string"!=typeof e&&(o=String(e)),"iso-8859-1"===s)return escape(o).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let i="";for(let e=0;e<o.length;e+=R){const t=o.length>=R?o.slice(e,e+R):o,s=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?s[s.length]=t.charAt(e):n<128?s[s.length]=$[n]:n<2048?s[s.length]=$[192|n>>6]+$[128|63&n]:n<55296||n>=57344?s[s.length]=$[224|n>>12]+$[128|n>>6&63]+$[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=$[240|n>>18]+$[128|n>>12&63]+$[128|n>>6&63]+$[128|63&n])}i+=s.join("")}return i},encodeValuesOnly:!1,format:A,formatter:D,indices:!1,serializeDate:e=>(C??(C=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},M={};function q(e,t,s,n,r,o,i,a,l,u,d,p,h,f,m,g,_,y){let w=e,v=y,b=0,x=!1;for(;void 0!==(v=v.get(M))&&!x;){const t=v.get(e);if(b+=1,void 0!==t){if(t===b)throw new RangeError("Cyclic object value");x=!0}void 0===v.get(M)&&(b=0)}if("function"==typeof u?w=u(t,w):w instanceof Date?w=h?.(w):"comma"===s&&c(w)&&(w=O(w,function(e){return e instanceof Date?h?.(e):e})),null===w){if(o)return l&&!g?l(t,P.encoder,_,"key",f):t;w=""}if("string"==typeof(S=w)||"number"==typeof S||"boolean"==typeof S||"symbol"==typeof S||"bigint"==typeof S||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(w)){if(l){const e=g?t:l(t,P.encoder,_,"key",f);return[m?.(e)+"="+m?.(l(w,P.encoder,_,"value",f))]}return[m?.(t)+"="+m?.(String(w))]}var S;const A=[];if(void 0===w)return A;let D;if("comma"===s&&c(w))g&&l&&(w=O(w,l)),D=[{value:w.length>0?w.join(",")||null:void 0}];else if(c(u))D=u;else{const e=Object.keys(w);D=d?e.sort(d):e}const k=a?String(t).replace(/\./g,"%2E"):String(t),I=n&&c(w)&&1===w.length?k+"[]":k;if(r&&c(w)&&0===w.length)return I+"[]";for(let t=0;t<D.length;++t){const v=D[t],x="object"==typeof v&&void 0!==v.value?v.value:w[v];if(i&&null===x)continue;const S=p&&a?v.replace(/\./g,"%2E"):v,k=c(w)?"function"==typeof s?s(I,S):I:I+(p?"."+S:"["+S+"]");y.set(e,b);const $=new WeakMap;$.set(M,y),E(A,q(x,k,s,n,r,o,i,a,"comma"===s&&g&&c(w)?null:l,u,d,p,h,f,m,g,_,$))}return A}let L,N;function j(e){let t;return(L??(t=new globalThis.TextEncoder,L=t.encode.bind(t)))(e)}function U(e){let t;return(N??(t=new globalThis.TextDecoder,N=t.decode.bind(t)))(e)}var B,W;class F{constructor(){B.set(this,void 0),W.set(this,void 0),r(this,B,new Uint8Array,"f"),r(this,W,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?j(e):e;r(this,B,function(e){let t=0;for(const s of e)t+=s.length;const s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}([o(this,B,"f"),t]),"f");const s=[];let n;for(;null!=(n=H(o(this,B,"f"),o(this,W,"f")));){if(n.carriage&&null==o(this,W,"f")){r(this,W,n.index,"f");continue}if(null!=o(this,W,"f")&&(n.index!==o(this,W,"f")+1||n.carriage)){s.push(U(o(this,B,"f").subarray(0,o(this,W,"f")-1))),r(this,B,o(this,B,"f").subarray(o(this,W,"f")),"f"),r(this,W,null,"f");continue}const e=null!==o(this,W,"f")?n.preceding-1:n.preceding,t=U(o(this,B,"f").subarray(0,e));s.push(t),r(this,B,o(this,B,"f").subarray(n.index),"f"),r(this,W,null,"f")}return s}flush(){return o(this,B,"f").length?this.decode("\n"):[]}}function H(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 J(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}B=new WeakMap,W=new WeakMap,F.NEWLINE_CHARS=new Set(["\n","\r"]),F.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const K={off:0,error:200,warn:300,info:400,debug:500},X=(e,t,s)=>{var n,r;if(e)return n=K,r=e,Object.prototype.hasOwnProperty.call(n,r)?e:void Z(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(K))}`)};function z(){}function G(e,t,s){return!t||K[e]>K[s]?z:t[e].bind(t)}const V={error:z,warn:z,info:z,debug:z};let Q=new WeakMap;function Z(e){const t=e.logger,s=e.logLevel??"off";if(!t)return V;const n=Q.get(t);if(n&&n[0]===s)return n[1];const r={error:G("error",t,s),warn:G("warn",t,s),info:G("info",t,s),debug:G("debug",t,s)};return Q.set(t,[s,r]),r}const Y=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()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var ee,te,se;class ne{constructor(e,t,s){this.iterator=e,ee.set(this,void 0),this.controller=t,r(this,ee,s,"f")}static fromSSEResponse(e,t,s){let n=!1;const r=s?Z(s):console;return new ne(async function*(){if(n)throw new a.vc("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new a.vc("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 a.vc("Attempted to iterate over a response with no body")}const s=new re,n=new F,r=x(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const s of e){if(null==s)continue;const e=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?j(s):s;let n,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(n=J(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(r))for(const t of n.decode(e)){const e=s.decode(t);e&&(yield e)}for(const e of n.flush()){const t=s.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null!==n.event&&n.event.startsWith("thread.")){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new a.LG(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw r.error("Could not parse message into JSON:",n.data),r.error("From chunk:",n.raw),e}if(t&&t.error)throw new a.LG(void 0,t.error,void 0,e.headers);yield t}s=!0}catch(e){if((0,f.z)(e))return;throw e}finally{s||t.abort()}},t,s)}static fromReadableStream(e,t,s){let n=!1;return new ne(async function*(){if(n)throw new a.vc("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new F,s=x(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(e){if((0,f.z)(e))return;throw e}finally{s||t.abort()}},t,s)}[(ee=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new ne(()=>n(e),this.controller,o(this,ee,"f")),new ne(()=>n(t),this.controller,o(this,ee,"f"))]}toReadableStream(){const e=this;let t;return v({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:n}=await t.next();if(n)return e.close();const r=j(JSON.stringify(s)+"\n");e.enqueue(r)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class re{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,n]=function(e){const t=e.indexOf(":");return-1!==t?[e.substring(0,t),":",e.substring(t+1)]:[e,"",""]}(e);return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function oe(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:o}=t,i=await(async()=>{if(t.options.stream)return Z(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):ne.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const n=s.headers.get("content-type"),r=n?.split(";")[0]?.trim();return r?.includes("application/json")||r?.endsWith("+json")?ie(await s.json(),s):await s.text()})();return Z(e).debug(`[${n}] response parsed`,Y({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-o})),i}function ie(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})}class ae extends Promise{constructor(e,t,s=oe){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,te.set(this,void 0),r(this,te,e,"f")}_thenUnwrap(e){return new ae(o(this,te,"f"),this.responsePromise,async(t,s)=>ie(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,te,"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)}}te=new WeakMap;class le{constructor(e,t,s,n){se.set(this,void 0),r(this,se,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new a.vc("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,se,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(se=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class ce extends ae{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await oe(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class ue extends le{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class de extends le{constructor(e,t,s,n){super(e,t,s,n),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:{...d(this.options.query),after:t}}:null}}class pe extends le{constructor(e,t,s,n){super(e,t,s,n),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:{...d(this.options.query),after:e}}:null}}const he=()=>{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 fe(e,t,s){return he(),new File(e,t??"unknown_file",s)}function me(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}const ge=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],_e=async(e,t)=>({...e,body:await we(e.body,t)}),ye=new WeakMap,we=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,s=ye.get(t);if(s)return s;const n=(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 ye.set(t,n),n}(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])=>ve(s,e,t))),s},ve=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,fe([await s.blob()],me(s)));else if(ge(s))e.append(t,fe([await new Response(b(s)).blob()],me(s)));else if((e=>e instanceof Blob&&"name"in e)(s))e.append(t,s,me(s));else if(Array.isArray(s))await Promise.all(s.map(s=>ve(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,n])=>ve(e,`${t}[${s}]`,n)))}}},be=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 xe(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(be(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!ge(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";return`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await xe(s))}return t}class Se{constructor(e){this._client=e}}function Ae(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const De=Object.freeze(Object.create(null)),ke=(e=Ae)=>function(t,...s){if(1===t.length)return t[0];let n=!1;const r=[],o=t.reduce((t,o,i)=>{/[?#]/.test(o)&&(n=!0);const a=s[i];let l=(n?encodeURIComponent:e)(""+a);return i!==s.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??De)??De)?.toString)&&(l=a+"",r.push({start:t.length+o.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(a).slice(8,-1)} is not a valid path parameter`})),t+o+(i===s.length?"":l)},""),i=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=l.exec(i));)r.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(r.sort((e,t)=>e.start-t.start),r.length>0){let e=0;const t=r.reduce((t,s)=>{const n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r},"");throw new a.vc(`Path parameters result in path with invalid segments:\n${r.map(e=>e.error).join("\n")}\n${o}\n${t}`)}return o},Ie=ke(Ae);class $e extends Se{list(e,t={},s){return this._client.getAPIList(Ie`/chat/completions/${e}/messages`,de,{query:t,...s})}}var Re=s(7036),Oe=s(9731);const Te=e=>"assistant"===e?.role,Ee=e=>"tool"===e?.role;var Ce,Pe,Me,qe,Le,Ne,je,Ue,Be,We,Fe,He,Je,Ke,Xe,ze,Ge,Ve,Qe,Ze,Ye;class et{constructor(){Ce.add(this),this.controller=new AbortController,Pe.set(this,void 0),Me.set(this,()=>{}),qe.set(this,()=>{}),Le.set(this,void 0),Ne.set(this,()=>{}),je.set(this,()=>{}),Ue.set(this,{}),Be.set(this,!1),We.set(this,!1),Fe.set(this,!1),He.set(this,!1),r(this,Pe,new Promise((e,t)=>{r(this,Me,e,"f"),r(this,qe,t,"f")}),"f"),r(this,Le,new Promise((e,t)=>{r(this,Ne,e,"f"),r(this,je,t,"f")}),"f"),o(this,Pe,"f").catch(()=>{}),o(this,Le,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Ce,"m",Je).bind(this))},0)}_connected(){this.ended||(o(this,Me,"f").call(this),this._emit("connect"))}get ended(){return o(this,Be,"f")}get errored(){return o(this,We,"f")}get aborted(){return o(this,Fe,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,Ue,"f")[e]||(o(this,Ue,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,Ue,"f")[e];if(!s)return this;const n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(o(this,Ue,"f")[e]||(o(this,Ue,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{r(this,He,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){r(this,He,!0,"f"),await o(this,Le,"f")}_emit(e,...t){if(o(this,Be,"f"))return;"end"===e&&(r(this,Be,!0,"f"),o(this,Ne,"f").call(this));const s=o(this,Ue,"f")[e];if(s&&(o(this,Ue,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return o(this,He,"f")||s?.length||Promise.reject(e),o(this,qe,"f").call(this,e),o(this,je,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];o(this,He,"f")||s?.length||Promise.reject(e),o(this,qe,"f").call(this,e),o(this,je,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function tt(e){return"function"==typeof e.parse}Pe=new WeakMap,Me=new WeakMap,qe=new WeakMap,Le=new WeakMap,Ne=new WeakMap,je=new WeakMap,Ue=new WeakMap,Be=new WeakMap,We=new WeakMap,Fe=new WeakMap,He=new WeakMap,Ce=new WeakSet,Je=function(e){if(r(this,We,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new Re.cH),e instanceof Re.cH)return r(this,Fe,!0,"f"),this._emit("abort",e);if(e instanceof Re.vc)return this._emit("error",e);if(e instanceof Error){const t=new Re.vc(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Re.vc(String(e)))};const st=10;class nt extends et{constructor(){super(...arguments),Ke.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),Ee(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Te(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Re.vc("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,Ke,"m",Xe).call(this)}async finalMessage(){return await this.done(),o(this,Ke,"m",ze).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,Ke,"m",Ge).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,Ke,"m",Ve).call(this)}async totalUsage(){return await this.done(),o(this,Ke,"m",Qe).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,Ke,"m",ze).call(this);t&&this._emit("finalMessage",t);const s=o(this,Ke,"m",Xe).call(this);s&&this._emit("finalContent",s);const n=o(this,Ke,"m",Ge).call(this);n&&this._emit("finalFunctionToolCall",n);const r=o(this,Ke,"m",Ve).call(this);null!=r&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",o(this,Ke,"m",Qe).call(this))}async _createChatCompletion(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),o(this,Ke,"m",Ze).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion((0,Oe.ie)(r,t))}async _runChatCompletion(e,t,s){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const n="tool",{tool_choice:r="auto",stream:i,...a}=t,l="string"!=typeof r&&"function"===r.type&&r?.function?.name,{maxChatCompletions:c=st}=s||{},u=t.tools.map(e=>{if((0,Oe.i_)(e)){if(!e.$callback)throw new Re.vc("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 e of u)"function"===e.type&&(d[e.function.name||e.function.function.name]=e.function);const p="tools"in t?u.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 e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:p,messages:[...this.messages]},s),i=t.choices[0]?.message;if(!i)throw new Re.vc("missing message in ChatCompletion response");if(!i.tool_calls?.length)return;for(const e of i.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:s,arguments:r}=e.function,i=d[s];if(!i){const e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(d).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(l&&l!==s){const e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let a;try{a=tt(i)?await i.parse(r):r}catch(e){const s=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:s});continue}const c=await i.function(a,this),u=o(this,Ke,"m",Ye).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:u}),l)return}}}}Ke=new WeakSet,Xe=function(){return o(this,Ke,"m",ze).call(this).content??null},ze=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Te(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new Re.vc("stream ended without producing a ChatCompletionMessage with role=assistant")},Ge=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Te(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},Ve=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ee(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}},Qe=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},Ze=function(e){if(null!=e.n&&e.n>1)throw new Re.vc("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ye=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class rt extends nt{static runTools(e,t,s){const n=new rt,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,r)),n}_addMessage(e,t=!0){super._addMessage(e,t),Te(e)&&e.content&&this._emit("content",e.content)}}class ot extends Error{}class it extends Error{}const at=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 n=0;const r=e=>{throw new ot(`${e} at position ${n}`)},o=e=>{throw new it(`${e} at position ${n}`)},i=()=>(d(),n>=s&&r("Unexpected end of input"),'"'===e[n]?a():"{"===e[n]?l():"["===e[n]?c():"null"===e.substring(n,n+4)||16&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||32&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||32&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||128&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||256&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||64&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),a=()=>{const i=n;let a=!1;for(n++;n<s&&('"'!==e[n]||a&&"\\"===e[n-1]);)a="\\"===e[n]&&!a,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(i,++n-Number(a)))}catch(e){o(String(e))}else if(1&t)try{return JSON.parse(e.substring(i,n-Number(a))+'"')}catch(t){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,d();const o={};try{for(;"}"!==e[n];){if(d(),n>=s&&8&t)return o;const r=a();d(),n++;try{const e=i();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(8&t)return o;throw e}d(),","===e[n]&&n++}}catch(e){if(8&t)return o;r("Expected '}' at end of object")}return n++,o},c=()=>{n++;const s=[];try{for(;"]"!==e[n];)s.push(i()),d(),","===e[n]&&n++}catch(e){if(4&t)return s;r("Expected ']' at end of array")}return n++,s},u=()=>{if(0===n){"-"===e&&2&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(s){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(e){}o(String(s))}}const i=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=s||2&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,n))}catch(s){"-"===e.substring(i,n)&&2&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){o(String(e))}}},d=()=>{for(;n<s&&" \n\r\t".includes(e[n]);)n++};return i()})(e.trim(),t)}(e,509);var lt,ct,ut,dt,pt,ht,ft,mt,gt,_t,yt,wt;class vt extends nt{constructor(e){super(),lt.add(this),ct.set(this,void 0),ut.set(this,void 0),dt.set(this,void 0),r(this,ct,e,"f"),r(this,ut,[],"f")}get currentChatCompletionSnapshot(){return o(this,dt,"f")}static fromReadableStream(e){const t=new vt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const n=new vt(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,s){super._createChatCompletion;const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),o(this,lt,"m",pt).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const e of r)o(this,lt,"m",ft).call(this,e);if(r.controller.signal?.aborted)throw new Re.cH;return this._addChatCompletion(o(this,lt,"m",_t).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),o(this,lt,"m",pt).call(this),this._connected();const n=ne.fromReadableStream(e,this.controller);let r;for await(const e of n)r&&r!==e.id&&this._addChatCompletion(o(this,lt,"m",_t).call(this)),o(this,lt,"m",ft).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new Re.cH;return this._addChatCompletion(o(this,lt,"m",_t).call(this))}[(ct=new WeakMap,ut=new WeakMap,dt=new WeakMap,lt=new WeakSet,pt=function(){this.ended||r(this,dt,void 0,"f")},ht=function(e){let t=o(this,ut,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},o(this,ut,"f")[e.index]=t,t)},ft=function(e){if(this.ended)return;const t=o(this,lt,"m",wt).call(this,e);this._emit("chunk",e,t);for(const s of e.choices){const e=t.choices[s.index];null!=s.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),null!=s.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=s.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=o(this,lt,"m",ht).call(this,e);e.finish_reason&&(o(this,lt,"m",gt).call(this,e),null!=n.current_tool_call_index&&o(this,lt,"m",mt).call(this,e,n.current_tool_call_index));for(const t of s.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(o(this,lt,"m",gt).call(this,e),null!=n.current_tool_call_index&&o(this,lt,"m",mt).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of s.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??""}):St())}}},mt=function(e,t){if(o(this,lt,"m",ht).call(this,e).done_tool_calls.has(t))return;const s=e.message.tool_calls?.[t];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if("function"===s.type){const e=o(this,ct,"f")?.tools?.find(e=>(0,Oe.Tw)(e)&&e.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:t,arguments:s.function.arguments,parsed_arguments:(0,Oe.i_)(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},gt=function(e){const t=o(this,lt,"m",ht).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const s=o(this,lt,"m",yt).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},_t=function(){if(this.ended)throw new Re.vc("stream has ended, this shouldn't happen");const e=o(this,dt,"f");if(!e)throw new Re.vc("request ended without sending any chunks");return r(this,dt,void 0,"f"),r(this,ut,[],"f"),function(e,t){const{id:s,choices:n,created:r,model:o,system_fingerprint:i,...a}=e,l={...a,id:s,choices:n.map(({message:t,finish_reason:s,index:n,logprobs:r,...o})=>{if(!s)throw new Re.vc(`missing finish_reason for choice ${n}`);const{content:i=null,function_call:a,tool_calls:l,...c}=t,u=t.role;if(!u)throw new Re.vc(`missing role for choice ${n}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new Re.vc(`missing function_call.arguments for choice ${n}`);if(!l)throw new Re.vc(`missing function_call.name for choice ${n}`);return{...o,message:{content:i,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}return l?{...o,index:n,finish_reason:s,logprobs:r,message:{...c,role:u,content:i,refusal:t.refusal??null,tool_calls:l.map((t,s)=>{const{function:r,type:o,id:i,...a}=t,{arguments:l,name:c,...u}=r||{};if(null==i)throw new Re.vc(`missing choices[${n}].tool_calls[${s}].id\n${bt(e)}`);if(null==o)throw new Re.vc(`missing choices[${n}].tool_calls[${s}].type\n${bt(e)}`);if(null==c)throw new Re.vc(`missing choices[${n}].tool_calls[${s}].function.name\n${bt(e)}`);if(null==l)throw new Re.vc(`missing choices[${n}].tool_calls[${s}].function.arguments\n${bt(e)}`);return{...a,id:i,type:o,function:{...u,name:c,arguments:l}}})}}:{...o,message:{...c,content:i,role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return(0,Oe.OJ)(l,t)}(e,o(this,ct,"f"))},yt=function(){const e=o(this,ct,"f")?.response_format;return(0,Oe.U)(e)?e:null},wt=function(e){var t,s,n,i;let a=o(this,dt,"f");const{choices:l,...c}=e;a?Object.assign(a,c):a=r(this,dt,{...c,choices:[]},"f");for(const{delta:r,finish_reason:l,index:c,logprobs:u=null,...d}of e.choices){let e=a.choices[c];if(e||(e=a.choices[c]={finish_reason:l,index:c,message:{},logprobs:u,...d}),u)if(e.logprobs){const{content:n,refusal:r,...o}=u;xt(),Object.assign(e.logprobs,o),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),r&&((s=e.logprobs).refusal??(s.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},u);if(l&&(e.finish_reason=l,o(this,ct,"f")&&(0,Oe.d4)(o(this,ct,"f")))){if("length"===l)throw new Re.k5;if("content_filter"===l)throw new Re.pf}if(Object.assign(e,d),!r)continue;const{content:p,refusal:h,function_call:f,role:m,tool_calls:g,..._}=r;if(xt(),Object.assign(e.message,_),h&&(e.message.refusal=(e.message.refusal||"")+h),m&&(e.message.role=m),f&&(e.message.function_call?(f.name&&(e.message.function_call.name=f.name),f.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=f.arguments)):e.message.function_call=f),p&&(e.message.content=(e.message.content||"")+p,!e.message.refusal&&o(this,lt,"m",yt).call(this)&&(e.message.parsed=at(e.message.content))),g){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:s,type:n,function:r,...a}of g){const l=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(l,a),s&&(l.id=s),n&&(l.type=n),r&&(l.function??(l.function={name:r.name??"",arguments:""})),r?.name&&(l.function.name=r.name),r?.arguments&&(l.function.arguments+=r.arguments,(0,Oe.tp)(o(this,ct,"f"),l)&&(l.function.parsed_arguments=at(l.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",s=>{const n=t.shift();n?n.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 ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function bt(e){return JSON.stringify(e)}function xt(e){}function St(e){}class At extends vt{static fromReadableStream(e){const t=new At(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const n=new At(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,r)),n}}class Dt extends Se{constructor(){super(...arguments),this.messages=new $e(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(Ie`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(Ie`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",de,{query:e,...t})}delete(e,t){return this._client.delete(Ie`/chat/completions/${e}`,t)}parse(e,t){return(0,Oe.cz)(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>(0,Oe.ie)(t,e))}runTools(e,t){return e.stream?At.runTools(this._client,e,t):rt.runTools(this._client,e,t)}stream(e,t){return vt.createChatCompletion(this._client,e,t)}}Dt.Messages=$e;class kt extends Se{constructor(){super(...arguments),this.completions=new Dt(this._client)}}kt.Completions=Dt;const It=Symbol("brand.privateNullableHeaders");function*$t(e){if(!e)return;if(It 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():u(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=u(e[1])?e[1]:[e[1]];let r=!1;for(const e of n)void 0!==e&&(s&&!r&&(r=!0,yield[t,null]),yield[t,e])}}const Rt=e=>{const t=new Headers,s=new Set;for(const n of e){const e=new Set;for(const[r,o]of $t(n)){const n=r.toLowerCase();e.has(n)||(t.delete(r),e.add(n)),null===o?(t.delete(r),s.add(n)):(t.append(r,o),s.delete(n))}}return{[It]:!0,values:t,nulls:s}};class Ot extends Se{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Rt([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Tt extends Se{create(e,t){return this._client.post("/audio/transcriptions",_e({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Et extends Se{create(e,t){return this._client.post("/audio/translations",_e({body:e,...t,__metadata:{model:e.model}},this._client))}}class Ct extends Se{constructor(){super(...arguments),this.transcriptions=new Tt(this._client),this.translations=new Et(this._client),this.speech=new Ot(this._client)}}Ct.Transcriptions=Tt,Ct.Translations=Et,Ct.Speech=Ot;class Pt extends Se{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ie`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",de,{query:e,...t})}cancel(e,t){return this._client.post(Ie`/batches/${e}/cancel`,t)}}class Mt extends Se{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ie`/assistants/${e}`,{...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(Ie`/assistants/${e}`,{body:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",de,{query:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Ie`/assistants/${e}`,{...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends Se{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Lt extends Se{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Nt extends Se{constructor(){super(...arguments),this.sessions=new qt(this._client),this.transcriptionSessions=new Lt(this._client)}}Nt.Sessions=qt,Nt.TranscriptionSessions=Lt;class jt extends Se{create(e,t,s){return this._client.post(Ie`/threads/${e}/messages`,{body:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(Ie`/threads/${n}/messages/${e}`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(Ie`/threads/${n}/messages/${e}`,{body:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(Ie`/threads/${e}/messages`,de,{query:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:n}=t;return this._client.delete(Ie`/threads/${n}/messages/${e}`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Ut extends Se{retrieve(e,t,s){const{thread_id:n,run_id:r,...o}=t;return this._client.get(Ie`/threads/${n}/runs/${r}/steps/${e}`,{query:o,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:n,...r}=t;return this._client.getAPIList(Ie`/threads/${n}/runs/${e}/steps`,de,{query:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const Bt=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var Wt,Ft,Ht,Jt,Kt,Xt,zt,Gt,Vt,Qt,Zt,Yt,es,ts,ss,ns,rs,os,is,as,ls,cs,us;class ds extends et{constructor(){super(...arguments),Wt.add(this),Ht.set(this,[]),Jt.set(this,{}),Kt.set(this,{}),Xt.set(this,void 0),zt.set(this,void 0),Gt.set(this,void 0),Vt.set(this,void 0),Qt.set(this,void 0),Zt.set(this,void 0),Yt.set(this,void 0),es.set(this,void 0),ts.set(this,void 0)}[(Ht=new WeakMap,Jt=new WeakMap,Kt=new WeakMap,Xt=new WeakMap,zt=new WeakMap,Gt=new WeakMap,Vt=new WeakMap,Qt=new WeakMap,Zt=new WeakMap,Yt=new WeakMap,es=new WeakMap,ts=new WeakMap,Wt=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",s=>{const n=t.shift();n?n.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 Ft;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const n=ne.fromReadableStream(e,this.controller);for await(const e of n)o(this,Wt,"m",ss).call(this,e);if(n.controller.signal?.aborted)throw new Re.cH;return this._addRun(o(this,Wt,"m",ns).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){const r=new Ft;return r._run(()=>r._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createToolAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(const e of a)o(this,Wt,"m",ss).call(this,e);if(a.controller.signal?.aborted)throw new Re.cH;return this._addRun(o(this,Wt,"m",ns).call(this))}static createThreadAssistantStream(e,t,s){const n=new Ft;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){const r=new Ft;return r._run(()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return o(this,Yt,"f")}currentRun(){return o(this,es,"f")}currentMessageSnapshot(){return o(this,Xt,"f")}currentRunStepSnapshot(){return o(this,ts,"f")}async finalRunSteps(){return await this.done(),Object.values(o(this,Jt,"f"))}async finalMessages(){return await this.done(),Object.values(o(this,Kt,"f"))}async finalRun(){if(await this.done(),!o(this,zt,"f"))throw Error("Final run was not received.");return o(this,zt,"f")}async _createThreadAssistantStream(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));const r={...t,stream:!0},i=await e.createAndRun(r,{...s,signal:this.controller.signal});this._connected();for await(const e of i)o(this,Wt,"m",ss).call(this,e);if(i.controller.signal?.aborted)throw new Re.cH;return this._addRun(o(this,Wt,"m",ns).call(this))}async _createAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(const e of a)o(this,Wt,"m",ss).call(this,e);if(a.controller.signal?.aborted)throw new Re.cH;return this._addRun(o(this,Wt,"m",ns).call(this))}static accumulateDelta(e,t){for(const[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let t=e[s];if(null!=t)if("index"!==s&&"type"!==s){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!p(t)||!p(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...n);continue}for(const e of n){if(!p(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const s=e.index;if(null==s)throw console.error(e),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 n=t[s];null==n?t.push(e):t[s]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[s]=t}else e[s]=n;else e[s]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}}Ft=ds,ss=function(e){if(!this.ended)switch(r(this,Yt,e,"f"),o(this,Wt,"m",is).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":o(this,Wt,"m",us).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":o(this,Wt,"m",os).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":o(this,Wt,"m",rs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},ns=function(){if(this.ended)throw new Re.vc("stream has ended, this shouldn't happen");if(!o(this,zt,"f"))throw Error("Final run has not been received");return o(this,zt,"f")},rs=function(e){const[t,s]=o(this,Wt,"m",ls).call(this,e,o(this,Xt,"f"));r(this,Xt,t,"f"),o(this,Kt,"f")[t.id]=t;for(const e of s){const s=t.content[e.index];"text"==s?.type&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if("text"==s.type&&s.text){let e=s.text,n=t.content[s.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(s.index!=o(this,Gt,"f")){if(o(this,Vt,"f"))switch(o(this,Vt,"f").type){case"text":this._emit("textDone",o(this,Vt,"f").text,o(this,Xt,"f"));break;case"image_file":this._emit("imageFileDone",o(this,Vt,"f").image_file,o(this,Xt,"f"))}r(this,Gt,s.index,"f")}r(this,Vt,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==o(this,Gt,"f")){const t=e.data.content[o(this,Gt,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,o(this,Xt,"f"));break;case"text":this._emit("textDone",t.text,o(this,Xt,"f"))}}o(this,Xt,"f")&&this._emit("messageDone",e.data),r(this,Xt,void 0,"f")}},os=function(e){const t=o(this,Wt,"m",as).call(this,e);switch(r(this,ts,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&"tool_calls"==s.step_details.type&&s.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of s.step_details.tool_calls)e.index==o(this,Qt,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(o(this,Zt,"f")&&this._emit("toolCallDone",o(this,Zt,"f")),r(this,Qt,e.index,"f"),r(this,Zt,t.step_details.tool_calls[e.index],"f"),o(this,Zt,"f")&&this._emit("toolCallCreated",o(this,Zt,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":r(this,ts,void 0,"f"),"tool_calls"==e.data.step_details.type&&o(this,Zt,"f")&&(this._emit("toolCallDone",o(this,Zt,"f")),r(this,Zt,void 0,"f")),this._emit("runStepDone",e.data,t)}},is=function(e){o(this,Ht,"f").push(e),this._emit("event",e)},as=function(e){switch(e.event){case"thread.run.step.created":return o(this,Jt,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=o(this,Jt,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const n=Ft.accumulateDelta(t,s.delta);o(this,Jt,"f")[e.data.id]=n}return o(this,Jt,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":o(this,Jt,"f")[e.data.id]=e.data}if(o(this,Jt,"f")[e.data.id])return o(this,Jt,"f")[e.data.id];throw new Error("No snapshot available")},ls=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let s=t.content[e.index];t.content[e.index]=o(this,Wt,"m",cs).call(this,e,s)}else t.content[e.index]=e,s.push(e);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},cs=function(e,t){return Ft.accumulateDelta(t,e)},us=function(e){switch(r(this,es,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.cancelling":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":r(this,zt,e.data,"f"),o(this,Zt,"f")&&(this._emit("toolCallDone",o(this,Zt,"f")),r(this,Zt,void 0,"f"))}};class ps extends Se{constructor(){super(...arguments),this.steps=new Ut(this._client)}create(e,t,s){const{include:n,...r}=t;return this._client.post(Ie`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(Ie`/threads/${n}/runs/${e}`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(Ie`/threads/${n}/runs/${e}`,{body:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(Ie`/threads/${e}/runs`,de,{query:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:n}=t;return this._client.post(Ie`/threads/${n}/runs/${e}/cancel`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return ds.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n=Rt([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await h(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return ds.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:n,...r}=t;return this._client.post(Ie`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){const n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return ds.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}}ps.Steps=Ut;class hs extends Se{constructor(){super(...arguments),this.runs=new ps(this._client),this.messages=new jt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ie`/threads/${e}`,{...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(Ie`/threads/${e}`,{body:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(Ie`/threads/${e}`,{...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}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 ds.createThreadAssistantStream(e,this._client.beta.threads,t)}}hs.Runs=ps,hs.Messages=jt;class fs extends Se{constructor(){super(...arguments),this.realtime=new Nt(this._client),this.assistants=new Mt(this._client),this.threads=new hs(this._client)}}fs.Realtime=Nt,fs.Assistants=Mt,fs.Threads=hs;class ms extends Se{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class gs extends Se{retrieve(e,t,s){const{container_id:n}=t;return this._client.get(Ie`/containers/${n}/files/${e}/content`,{...s,headers:Rt([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}class _s extends Se{constructor(){super(...arguments),this.content=new gs(this._client)}create(e,t,s){return this._client.post(Ie`/containers/${e}/files`,_e({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:n}=t;return this._client.get(Ie`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(Ie`/containers/${e}/files`,de,{query:t,...s})}delete(e,t,s){const{container_id:n}=t;return this._client.delete(Ie`/containers/${n}/files/${e}`,{...s,headers:Rt([{Accept:"*/*"},s?.headers])})}}_s.Content=gs;class ys extends Se{constructor(){super(...arguments),this.files=new _s(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(Ie`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",de,{query:e,...t})}delete(e,t){return this._client.delete(Ie`/containers/${e}`,{...t,headers:Rt([{Accept:"*/*"},t?.headers])})}}ys.Files=_s;class ws extends Se{create(e,t,s){const{include:n,...r}=t;return this._client.post(Ie`/conversations/${e}/items`,{query:{include:n},body:r,...s})}retrieve(e,t,s){const{conversation_id:n,...r}=t;return this._client.get(Ie`/conversations/${n}/items/${e}`,{query:r,...s})}list(e,t={},s){return this._client.getAPIList(Ie`/conversations/${e}/items`,pe,{query:t,...s})}delete(e,t,s){const{conversation_id:n}=t;return this._client.delete(Ie`/conversations/${n}/items/${e}`,s)}}class vs extends Se{constructor(){super(...arguments),this.items=new ws(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(Ie`/conversations/${e}`,t)}update(e,t,s){return this._client.post(Ie`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(Ie`/conversations/${e}`,t)}}vs.Items=ws;class bs extends Se{create(e,t){const s=!!e.encoding_format;let n=s?e.encoding_format:"base64";s&&Z(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?r:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),r._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,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)}),e)))}}class xs extends Se{retrieve(e,t,s){const{eval_id:n,run_id:r}=t;return this._client.get(Ie`/evals/${n}/runs/${r}/output_items/${e}`,s)}list(e,t,s){const{eval_id:n,...r}=t;return this._client.getAPIList(Ie`/evals/${n}/runs/${e}/output_items`,de,{query:r,...s})}}class Ss extends Se{constructor(){super(...arguments),this.outputItems=new xs(this._client)}create(e,t,s){return this._client.post(Ie`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:n}=t;return this._client.get(Ie`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(Ie`/evals/${e}/runs`,de,{query:t,...s})}delete(e,t,s){const{eval_id:n}=t;return this._client.delete(Ie`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:n}=t;return this._client.post(Ie`/evals/${n}/runs/${e}`,s)}}Ss.OutputItems=xs;class As extends Se{constructor(){super(...arguments),this.runs=new Ss(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(Ie`/evals/${e}`,t)}update(e,t,s){return this._client.post(Ie`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",de,{query:e,...t})}delete(e,t){return this._client.delete(Ie`/evals/${e}`,t)}}As.Runs=Ss;class Ds extends Se{create(e,t){return this._client.post("/files",_e({body:e,...t},this._client))}retrieve(e,t){return this._client.get(Ie`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",de,{query:e,...t})}delete(e,t){return this._client.delete(Ie`/files/${e}`,t)}content(e,t){return this._client.get(Ie`/files/${e}/content`,{...t,headers:Rt([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!n.has(o.status);)if(await h(t),o=await this.retrieve(e),Date.now()-r>s)throw new Re.qA({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}}class ks extends Se{}class Is extends Se{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class $s extends Se{constructor(){super(...arguments),this.graders=new Is(this._client)}}$s.Graders=Is;class Rs extends Se{create(e,t,s){return this._client.getAPIList(Ie`/fine_tuning/checkpoints/${e}/permissions`,ue,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(Ie`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(Ie`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}}class Os extends Se{constructor(){super(...arguments),this.permissions=new Rs(this._client)}}Os.Permissions=Rs;class Ts extends Se{list(e,t={},s){return this._client.getAPIList(Ie`/fine_tuning/jobs/${e}/checkpoints`,de,{query:t,...s})}}class Es extends Se{constructor(){super(...arguments),this.checkpoints=new Ts(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(Ie`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",de,{query:e,...t})}cancel(e,t){return this._client.post(Ie`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(Ie`/fine_tuning/jobs/${e}/events`,de,{query:t,...s})}pause(e,t){return this._client.post(Ie`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(Ie`/fine_tuning/jobs/${e}/resume`,t)}}Es.Checkpoints=Ts;class Cs extends Se{constructor(){super(...arguments),this.methods=new ks(this._client),this.jobs=new Es(this._client),this.checkpoints=new Os(this._client),this.alpha=new $s(this._client)}}Cs.Methods=ks,Cs.Jobs=Es,Cs.Checkpoints=Os,Cs.Alpha=$s;class Ps extends Se{}class Ms extends Se{constructor(){super(...arguments),this.graderModels=new Ps(this._client)}}Ms.GraderModels=Ps;class qs extends Se{createVariation(e,t){return this._client.post("/images/variations",_e({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",_e({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class Ls extends Se{retrieve(e,t){return this._client.get(Ie`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ue,e)}delete(e,t){return this._client.delete(Ie`/models/${e}`,t)}}class Ns extends Se{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class js extends Se{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class Us extends Se{constructor(){super(...arguments),this.clientSecrets=new js(this._client)}}Us.ClientSecrets=js;var Bs,Ws,Fs,Hs,Js,Ks,Xs,zs,Gs,Vs,Qs,Zs,Ys,en,tn,sn=s(839);class nn extends et{constructor(e){super(),Bs.add(this),Ws.set(this,void 0),Fs.set(this,void 0),Hs.set(this,void 0),r(this,Ws,e,"f")}static createResponse(e,t,s){const n=new nn(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),o(this,Bs,"m",Js).call(this);let i=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const e of r)o(this,Bs,"m",Ks).call(this,e,i);if(r.controller.signal?.aborted)throw new Re.cH;return o(this,Bs,"m",Xs).call(this)}[(Ws=new WeakMap,Fs=new WeakMap,Hs=new WeakMap,Bs=new WeakSet,Js=function(){this.ended||r(this,Fs,void 0,"f")},Ks=function(e,t){if(this.ended)return;const s=(e,s)=>{(null==t||s.sequence_number>t)&&this._emit(e,s)},n=o(this,Bs,"m",zs).call(this,e);switch(s("event",e),e.type){case"response.output_text.delta":{const t=n.output[e.output_index];if(!t)throw new Re.vc(`missing output at index ${e.output_index}`);if("message"===t.type){const n=t.content[e.content_index];if(!n)throw new Re.vc(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new Re.vc(`expected content to be 'output_text', got ${n.type}`);s("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{const t=n.output[e.output_index];if(!t)throw new Re.vc(`missing output at index ${e.output_index}`);"function_call"===t.type&&s("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:s(e.type,e)}},Xs=function(){if(this.ended)throw new Re.vc("stream has ended, this shouldn't happen");const e=o(this,Fs,"f");if(!e)throw new Re.vc("request ended without sending any events");r(this,Fs,void 0,"f");const t=function(e,t){return(0,sn.J4)(e,t)}(e,o(this,Ws,"f"));return r(this,Hs,t,"f"),t},zs=function(e){let t=o(this,Fs,"f");if(!t){if("response.created"!==e.type)throw new Re.vc(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=r(this,Fs,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const s=t.output[e.output_index];if(!s)throw new Re.vc(`missing output at index ${e.output_index}`);const n=s.type,r=e.part;"message"===n&&"reasoning_text"!==r.type?s.content.push(r):"reasoning"===n&&"reasoning_text"===r.type&&(s.content||(s.content=[]),s.content.push(r));break}case"response.output_text.delta":{const s=t.output[e.output_index];if(!s)throw new Re.vc(`missing output at index ${e.output_index}`);if("message"===s.type){const t=s.content[e.content_index];if(!t)throw new Re.vc(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Re.vc(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const s=t.output[e.output_index];if(!s)throw new Re.vc(`missing output at index ${e.output_index}`);"function_call"===s.type&&(s.arguments+=e.delta);break}case"response.reasoning_text.delta":{const s=t.output[e.output_index];if(!s)throw new Re.vc(`missing output at index ${e.output_index}`);if("reasoning"===s.type){const t=s.content?.[e.content_index];if(!t)throw new Re.vc(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new Re.vc(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":r(this,Fs,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",s=>{const n=t.shift();n?n.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=o(this,Hs,"f");if(!e)throw new Re.vc("stream ended without producing a ChatCompletion");return e}}class rn extends Se{list(e,t={},s){return this._client.getAPIList(Ie`/responses/${e}/input_items`,de,{query:t,...s})}}class on extends Se{constructor(){super(...arguments),this.inputItems=new rn(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&(0,sn.aD)(e),e))}retrieve(e,t={},s){return this._client.get(Ie`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&(0,sn.aD)(e),e))}delete(e,t){return this._client.delete(Ie`/responses/${e}`,{...t,headers:Rt([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>(0,sn.xp)(t,e))}stream(e,t){return nn.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Ie`/responses/${e}/cancel`,t)}}on.InputItems=rn;class an extends Se{create(e,t,s){return this._client.post(Ie`/uploads/${e}/parts`,_e({body:t,...s},this._client))}}class ln extends Se{constructor(){super(...arguments),this.parts=new an(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(Ie`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(Ie`/uploads/${e}/complete`,{body:t,...s})}}ln.Parts=an;class cn extends Se{create(e,t,s){return this._client.post(Ie`/vector_stores/${e}/file_batches`,{body:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(Ie`/vector_stores/${n}/file_batches/${e}`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:n}=t;return this._client.post(Ie`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){const{vector_store_id:n,...r}=t;return this._client.getAPIList(Ie`/vector_stores/${n}/file_batches/${e}/files`,de,{query:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const n=Rt([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await h(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){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 r=n?.maxConcurrency??5,o=Math.min(r,t.length),i=this._client,a=t.values(),l=[...s],c=Array(o).fill(a).map(async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},n);l.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)console.error(e.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(c),await this.createAndPoll(e,{file_ids:l})}}class un extends Se{create(e,t,s){return this._client.post(Ie`/vector_stores/${e}/files`,{body:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(Ie`/vector_stores/${n}/files/${e}`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:n,...r}=t;return this._client.post(Ie`/vector_stores/${n}/files/${e}`,{body:r,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(Ie`/vector_stores/${e}/files`,de,{query:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:n}=t;return this._client.delete(Ie`/vector_stores/${n}/files/${e}`,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){const n=Rt([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const r=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await h(e);break;case"failed":case"completed":return o}}}async upload(e,t,s){const n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){const n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){const{vector_store_id:n}=t;return this._client.getAPIList(Ie`/vector_stores/${n}/files/${e}/content`,ue,{...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class dn extends Se{constructor(){super(...arguments),this.files=new un(this._client),this.fileBatches=new cn(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ie`/vector_stores/${e}`,{...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(Ie`/vector_stores/${e}`,{body:t,...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",de,{query:e,...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Ie`/vector_stores/${e}`,{...t,headers:Rt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(Ie`/vector_stores/${e}/search`,ue,{body:t,method:"post",...s,headers:Rt([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}dn.Files=un,dn.FileBatches=cn;class pn extends Se{constructor(){super(...arguments),Gs.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=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");o(this,Gs,"m",Vs).call(this,s);const r=Rt([t]).values,i=o(this,Gs,"m",Qs).call(this,r,"webhook-signature"),a=o(this,Gs,"m",Qs).call(this,r,"webhook-timestamp"),l=o(this,Gs,"m",Qs).call(this,r,"webhook-id"),c=parseInt(a,10);if(isNaN(c))throw new Re.RA("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-c>n)throw new Re.RA("Webhook timestamp is too old");if(c>u+n)throw new Re.RA("Webhook timestamp is too new");const d=i.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),p=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),h=l?`${l}.${a}.${e}`:`${a}.${e}`,f=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of d)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",f,t,(new TextEncoder).encode(h)))return}catch{continue}throw new Re.RA("The given webhook signature does not match the expected signature")}}Gs=new WeakSet,Vs=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")},Qs=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};class hn{constructor({baseURL:e=Bt("OPENAI_BASE_URL"),apiKey:t=Bt("OPENAI_API_KEY"),organization:s=Bt("OPENAI_ORG_ID")??null,project:n=Bt("OPENAI_PROJECT_ID")??null,webhookSecret:o=Bt("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Zs.add(this),en.set(this,void 0),this.completions=new ms(this),this.chat=new kt(this),this.embeddings=new bs(this),this.files=new Ds(this),this.images=new qs(this),this.audio=new Ct(this),this.moderations=new Ns(this),this.models=new Ls(this),this.fineTuning=new Cs(this),this.graders=new Ms(this),this.vectorStores=new dn(this),this.webhooks=new pn(this),this.beta=new fs(this),this.batches=new Pt(this),this.uploads=new ln(this),this.responses=new on(this),this.realtime=new Us(this),this.conversations=new vs(this),this.evals=new As(this),this.containers=new ys(this),void 0===t)throw new a.vc("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const l={apiKey:t,organization:s,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new a.vc("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=l.baseURL,this.timeout=l.timeout??Ys.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=X(l.logLevel,"ClientOptions.logLevel",this)??X(Bt("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??function(){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`")}(),r(this,en,S,"f"),this._options=l,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=s,this.project=n,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.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return Rt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return function(e,t={}){let s=e;const n=function(e=P){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||P.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=A;if(void 0!==e.format){if(!I(k,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=k[s];let r,o=P.filter;if(("function"==typeof e.filter||c(e.filter))&&(o=e.filter),r=e.arrayFormat&&e.arrayFormat in T?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":P.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=void 0===e.allowDots?1==!!e.encodeDotInKeys||P.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:P.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:P.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:P.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?P.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:P.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:P.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:P.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:P.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:P.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:P.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:P.strictNullHandling}}(t);let r,o;"function"==typeof n.filter?(o=n.filter,s=o("",s)):c(n.filter)&&(o=n.filter,r=o);const i=[];if("object"!=typeof s||null===s)return"";const a=T[n.arrayFormat],l="comma"===a&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const u=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];n.skipNulls&&null===s[t]||E(i,q(s[t],t,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}const d=i.join(n.delimiter);let p=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),d.length>0?p+d:""}(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${m}`}defaultIdempotencyKey(){return`stainless-node-retry-${i()}`}makeStatusError(e,t,s,n){return a.LG.generate(e,t,s,n)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(e){if(e instanceof a.vc)throw e;throw new a.vc(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new a.vc(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const n=!o(this,Zs,"m",tn).call(this)&&s||this.baseURL,r=(e=>l.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(i)||(t={...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ae(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);const{req:o,url:i,timeout:l}=await this.buildRequest(n,{retryCount:r-t});await this.prepareRequest(o,{url:i,options:n});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=void 0===s?"":`, retryOf: ${s}`,d=Date.now();if(Z(this).debug(`[${c}] sending request`,Y({retryOfRequestLogID:s,method:n.method,url:i,options:n,headers:o.headers})),n.signal?.aborted)throw new a.cH;const p=new AbortController,h=await this.fetchWithTimeout(i,o,l,p).catch(f.r),m=Date.now();if(h instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new a.cH;const r=(0,f.z)(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Z(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),Z(this).debug(`[${c}] connection ${r?"timed out":"failed"} (${e})`,Y({retryOfRequestLogID:s,url:i,durationMs:m-d,message:h.message})),this.retryRequest(n,t,s??c);if(Z(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${c}] connection ${r?"timed out":"failed"} (error; no more retries left)`,Y({retryOfRequestLogID:s,url:i,durationMs:m-d,message:h.message})),r)throw new a.qA;throw new a.xX({cause:h})}const g=`[${c}${u}${[...h.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${o.method} ${i} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${m-d}ms`;if(!h.ok){const e=await this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(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}(h.body),Z(this).info(`${g} - ${e}`),Z(this).debug(`[${c}] response error (${e})`,Y({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),this.retryRequest(n,t,s??c,h.headers)}const r=e?"error; no more retries left":"error; not retryable";Z(this).info(`${g} - ${r}`);const o=await h.text().catch(e=>(0,f.r)(e).message),i=(e=>{try{return JSON.parse(e)}catch(e){return}})(o),a=i?void 0:o;throw Z(this).debug(`[${c}] response error (${r})`,Y({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:a,durationMs:Date.now()-d})),this.makeStatusError(h.status,i,a,h.headers)}return Z(this).info(g),Z(this).debug(`[${c}] response start`,Y({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),{response:h,options:n,controller:p,requestLogID:c,retryOfRequestLogID:s,startTime:d}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new ce(this,s,e)}async fetchWithTimeout(e,t,s,n){const{signal:r,method:o,...i}=t||{};r&&r.addEventListener("abort",()=>n.abort());const a=setTimeout(()=>n.abort(),s),l=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,c={signal:n.signal,...l?{duplex:"half"}:{},method:"GET",...i};o&&(c.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(a)}}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,n){let r;const o=n?.get("retry-after-ms");if(o){const e=parseFloat(o);Number.isNaN(e)||(r=e)}const i=n?.get("retry-after");if(i&&!r){const e=parseFloat(i);r=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){const s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await h(r),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:n,path:r,query:o,defaultBaseURL:i}=s,l=this.buildURL(r,o,i);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new a.vc(`${e} must be an integer`);if(t<0)throw new a.vc(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:u}=this.buildBody({options:s});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let r={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const o=Rt([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...w??(w=g()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=Rt([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:b(e)}:o(this,en,"f").call(this,{body:e,headers:s})}}Ys=hn,en=new WeakMap,Zs=new WeakSet,tn=function(){return"https://api.openai.com/v1"!==this.baseURL},hn.OpenAI=Ys,hn.DEFAULT_TIMEOUT=6e5,hn.OpenAIError=a.vc,hn.APIError=a.LG,hn.APIConnectionError=a.xX,hn.APIConnectionTimeoutError=a.qA,hn.APIUserAbortError=a.cH,hn.NotFoundError=a.m_,hn.ConflictError=a.fK,hn.RateLimitError=a.OE,hn.BadRequestError=a.v7,hn.AuthenticationError=a.v3,hn.InternalServerError=a.PO,hn.PermissionDeniedError=a.Ll,hn.UnprocessableEntityError=a.Is,hn.InvalidWebhookSignatureError=a.RA,hn.toFile=async function(e,t,s){if(he(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&be(e))(e=await e))return e instanceof File?e:fe([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),fe(await xe(n),t,s)}const n=await xe(e);if(t||(t=me(e)),!s?.type){const e=n.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(s={...s,type:e})}return fe(n,t,s)},hn.Completions=ms,hn.Chat=kt,hn.Embeddings=bs,hn.Files=Ds,hn.Images=qs,hn.Audio=Ct,hn.Moderations=Ns,hn.Models=Ls,hn.FineTuning=Cs,hn.Graders=Ms,hn.VectorStores=dn,hn.Webhooks=pn,hn.Beta=fs,hn.Batches=Pt,hn.Uploads=ln,hn.Responses=on,hn.Realtime=Us,hn.Conversations=vs,hn.Evals=As,hn.Containers=ys,s(5606),new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var fn=s(341);let mn,gn,_n,yn="responses";function wn(e){_n=e}function vn(e){yn=e}function bn(e){mn=e}function xn(e){gn=e}const Sn={"User-Agent":"Agents/JavaScript 0.1.9"},An=(0,n.tZ)("openai-agents:openai");var Dn=s(4231);const kn=Dn.z.enum(["in_progress","completed","searching","failed"]).default("failed"),In=Dn.z.enum(["in_progress","completed","searching","failed","incomplete"]).default("failed"),$n=Dn.z.enum(["in_progress","completed","interpreting"]).default("in_progress"),Rn=Dn.z.enum(["in_progress","completed","generating","failed"]).default("failed");function On(e={}){const t={type:"web_search",name:e.name??"web_search",user_location:e.userLocation,filters:e.filters?.allowedDomains?{allowed_domains:e.filters.allowedDomains}:void 0,search_context_size:e.searchContextSize??"medium"};return{type:"hosted_tool",name:e.name??"web_search",providerData:t}}function Tn(e,t={}){const s=Array.isArray(e)?e:[e],n={type:"file_search",name:t.name??"file_search",vector_store_ids:s,max_num_results:t.maxNumResults,include_search_results:t.includeSearchResults,ranking_options:t.rankingOptions,filters:t.filters};return{type:"hosted_tool",name:t.name??"file_search",providerData:n}}function En(e={}){const t={type:"code_interpreter",name:e.name??"code_interpreter",container:e.container??{type:"auto"}};return{type:"hosted_tool",name:e.name??"code_interpreter",providerData:t}}function Cn(e={}){const t={type:"image_generation",name:e.name??"image_generation",background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask,model:e.model,moderation:e.moderation,output_compression:e.outputCompression,output_format:e.outputFormat,partial_images:e.partialImages,quality:e.quality,size:e.size};return{type:"hosted_tool",name:e.name??"image_generation",providerData:t}}function Pn(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t={};for(const[s,n]of Object.entries(e))t[s.replace(/([A-Z])/g,"_$1").toLowerCase()]=Pn(n);return t}const Mn=Dn.z.enum(["file_search","web_search","web_search_preview","computer_use_preview","code_interpreter","image_generation","mcp"]),qn=Dn.z.enum(["auto","required","none"]);function Ln(e){if("function"===e.type)return{tool:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict},include:void 0};if("computer"===e.type)return{tool:{type:"computer_use_preview",environment:e.environment,display_width:e.dimensions[0],display_height:e.dimensions[1]},include:void 0};if("hosted_tool"===e.type){if("web_search"===e.providerData?.type)return{tool:{type:"web_search",user_location:e.providerData.user_location,filters:e.providerData.filters,search_context_size:e.providerData.search_context_size},include:void 0};if("web_search_preview"===e.providerData?.type)return{tool:{type:"web_search_preview",user_location:e.providerData.user_location,search_context_size:e.providerData.search_context_size},include:void 0};if("file_search"===e.providerData?.type)return{tool:{type:"file_search",vector_store_ids:e.providerData.vector_store_ids||("string"==typeof e.providerData.vector_store_id?[e.providerData.vector_store_id]:e.providerData.vector_store_id),max_num_results:e.providerData.max_num_results,ranking_options:e.providerData.ranking_options,filters:e.providerData.filters},include:e.providerData.include_search_results?["file_search_call.results"]:void 0};if("code_interpreter"===e.providerData?.type)return{tool:{type:"code_interpreter",container:e.providerData.container},include:void 0};if("image_generation"===e.providerData?.type)return{tool:{type:"image_generation",background:e.providerData.background,input_fidelity:e.providerData.input_fidelity,input_image_mask:e.providerData.input_image_mask,model:e.providerData.model,moderation:e.providerData.moderation,output_compression:e.providerData.output_compression,output_format:e.providerData.output_format,partial_images:e.providerData.partial_images,quality:e.providerData.quality,size:e.providerData.size},include:void 0};if("mcp"===e.providerData?.type)return{tool:{type:"mcp",server_label:e.providerData.server_label,server_url:e.providerData.server_url,connector_id:e.providerData.connector_id,authorization:e.providerData.authorization,allowed_tools:e.providerData.allowed_tools,headers:e.providerData.headers,require_approval:(t=e.providerData.require_approval,"never"===t||void 0===t?"never":"always"===t?"always":{never:{tool_names:t.never?.tool_names},always:{tool_names:t.always?.tool_names}})},include:void 0};if(e.providerData)return{tool:e.providerData,include:void 0}}var t;throw new Error(`Unsupported tool type: ${JSON.stringify(e)}`)}function Nn(e){return{name:e.toolName,description:e.toolDescription,parameters:e.inputJsonSchema,strict:e.strictJsonSchema,type:"function"}}function jn(e){if("input_text"===e.type)return{type:"input_text",text:e.text,...Pn(e.providerData)};if("input_image"===e.type){const t={type:"input_image",detail:"auto"};return"string"==typeof e.image?t.image_url=e.image:t.file_id=e.image.id,{...t,...Pn(e.providerData)}}if("input_file"===e.type){const t={type:"input_file"};if("string"==typeof e.file)if(e.file.startsWith("data:"))t.file_data=e.file;else{if(!e.file.startsWith("https://"))throw new n.yo("Unsupported string data for file input. If you're trying to pass an uploaded file's ID, use an object with the ID property instead.");t.file_url=e.file}else"id"in e.file?t.file_id=e.file.id:"url"in e.file&&(t.file_url=e.file.url);return{...t,...Pn(e.providerData)}}throw new n.yo(`Unsupported input content type: ${JSON.stringify(e)}`)}function Un(e){if("output_text"===e.type)return{type:"output_text",text:e.text,annotations:[],...Pn(e.providerData)};if("refusal"===e.type)return{type:"refusal",refusal:e.refusal,...Pn(e.providerData)};throw new n.yo(`Unsupported output content type: ${JSON.stringify(e)}`)}function Bn(e){return{type:"computer_screenshot",image_url:e.output.data}}function Wn(e){if("output_text"===e.type){const{type:t,text:s,...n}=e;return{type:t,text:s,...n}}if("refusal"===e.type){const{type:t,refusal:s,...n}=e;return{type:t,refusal:s,...n}}throw new Error(`Unsupported message content type: ${JSON.stringify(e)}`)}function Fn(e){return e.map(e=>{if("message"===e.type){const{id:t,type:s,role:n,content:r,status:o,...i}=e;return{id:t,type:s,role:n,content:r.map(Wn),status:o,providerData:i}}if("file_search_call"===e.type||"web_search_call"===e.type||"image_generation_call"===e.type||"code_interpreter_call"===e.type){const{status:t,...s}=e;let n;return"result"in s&&null!==s.result&&(n=s.result,delete s.result),{type:"hosted_tool_call",id:e.id,name:e.type,status:t,output:n,providerData:s}}if("function_call"===e.type){const{call_id:t,name:s,status:n,arguments:r,...o}=e;return{type:"function_call",id:e.id,callId:t,name:s,status:n,arguments:r,providerData:o}}if("computer_call"===e.type){const{call_id:t,status:s,action:n,...r}=e;return{type:"computer_call",id:e.id,callId:t,status:s,action:n,providerData:r}}if("mcp_list_tools"===e.type){const{...t}=e;return{type:"hosted_tool_call",id:e.id,name:e.type,status:"completed",output:void 0,providerData:t}}if("mcp_approval_request"===e.type){const{...t}=e;return{type:"hosted_tool_call",id:e.id,name:"mcp_approval_request",status:"completed",output:void 0,providerData:t}}if("mcp_call"===e.type){const{output:t,...s}=e;return{type:"hosted_tool_call",id:e.id,name:e.type,status:"completed",output:t||void 0,providerData:s}}if("reasoning"===e.type){const{summary:t,...s}=e;return{type:"reasoning",id:e.id,content:t.map(e=>{const{text:t,...s}=e;return{type:"input_text",text:t,providerData:s}}),providerData:s}}return{type:"unknown",providerData:e}})}class Hn{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async#s(e,t){const s=function(e){return"string"==typeof e?[{role:"user",content:e}]:e.map(e=>{if(function(e){return"message"===e.type||void 0===e.type&&"string"==typeof e.role}(e))return function(e){if("system"===e.role)return{id:e.id,role:"system",content:e.content,...Pn(e.providerData)};if("user"===e.role)return"string"==typeof e.content?{id:e.id,role:"user",content:e.content,...Pn(e.providerData)}:{id:e.id,role:"user",content:e.content.map(jn),...Pn(e.providerData)};if("assistant"===e.role)return{type:"message",id:e.id,role:"assistant",content:e.content.map(Un),status:e.status,...Pn(e.providerData)};throw new n.yo(`Unsupported item ${JSON.stringify(e)}`)}(e);if("function_call"===e.type)return{id:e.id,type:"function_call",name:e.name,call_id:e.callId,arguments:e.arguments,status:e.status,...Pn(e.providerData)};if("function_call_result"===e.type){if("text"!==e.output.type)throw new n.yo(`Unsupported tool result type: ${JSON.stringify(e.output)}`);return{type:"function_call_output",id:e.id,call_id:e.callId,output:e.output.text,status:e.status,...Pn(e.providerData)}}if("reasoning"===e.type)return{id:e.id,type:"reasoning",summary:e.content.map(e=>({type:"summary_text",text:e.text,...Pn(e.providerData)})),encrypted_content:e.providerData?.encryptedContent,...Pn(e.providerData)};if("computer_call"===e.type)return{type:"computer_call",call_id:e.callId,id:e.id,action:e.action,status:e.status,pending_safety_checks:[],...Pn(e.providerData)};if("computer_call_result"===e.type)return{type:"computer_call_output",id:e.id,call_id:e.callId,output:Bn(e),status:e.providerData?.status,acknowledged_safety_checks:e.providerData?.acknowledgedSafetyChecks,...Pn(e.providerData)};if("hosted_tool_call"===e.type){if("web_search_call"===e.providerData?.type||"web_search"===e.providerData?.type)return{...Pn(e.providerData),type:"web_search_call",id:e.id,status:kn.parse(e.status??"failed")};if("file_search_call"===e.providerData?.type||"file_search"===e.providerData?.type)return{...Pn(e.providerData),type:"file_search_call",id:e.id,status:In.parse(e.status??"failed"),queries:e.providerData?.queries??[],results:e.providerData?.results};if("code_interpreter_call"===e.providerData?.type||"code_interpreter"===e.providerData?.type)return{...Pn(e.providerData),type:"code_interpreter_call",id:e.id,code:e.providerData?.code??"",outputs:e.providerData?.outputs??e.providerData?.results??[],status:$n.parse(e.status??"failed"),container_id:e.providerData?.container_id};if("image_generation_call"===e.providerData?.type||"image_generation"===e.providerData?.type)return{...Pn(e.providerData),type:"image_generation_call",id:e.id,result:e.providerData?.result??null,status:Rn.parse(e.status??"failed")};if("mcp_list_tools"===e.providerData?.type||"mcp_list_tools"===e.name){const t=e.providerData;return{...Pn(e.providerData),type:"mcp_list_tools",id:e.id,tools:Pn(t.tools),server_label:t.server_label,error:t.error}}if("mcp_approval_request"===e.providerData?.type||"mcp_approval_request"===e.name){const t=e.providerData;return{...Pn(e.providerData),type:"mcp_approval_request",id:t.id??e.id,name:t.name,arguments:t.arguments,server_label:t.server_label}}if("mcp_approval_response"===e.providerData?.type||"mcp_approval_response"===e.name){const t=e.providerData;return{...Pn(t),type:"mcp_approval_response",id:t.id,approve:t.approve,approval_request_id:t.approval_request_id,reason:t.reason}}if("mcp_call"===e.providerData?.type||"mcp_call"===e.name){const t=e.providerData;return{...Pn(t),type:"mcp_call",id:t.id??e.id,name:t.name,arguments:t.arguments,server_label:t.server_label,error:t.error}}throw new n.yo(`Unsupported built-in tool call type: ${JSON.stringify(e)}`)}if("unknown"===e.type)return{...Pn(e.providerData),id:e.id};const t=e;throw new n.yo(`Unsupported item ${JSON.stringify(t)}`)})}(e.input),{tools:r,include:o}=function(e,t){const s=[],n=[];for(const t of e){const{tool:e,include:r}=Ln(t);if(s.push(e),r&&r.length>0)for(const e of r)n.push(e)}return{tools:[...s,...t.map(Nn)],include:n}}(e.tools,e.handoffs),i=function(e){if(void 0===e)return;const t=qn.safeParse(e);if(t.success)return t.data;const s=Mn.safeParse(e);return s.success?{type:s.data}:{type:"function",name:e}}(e.modelSettings.toolChoice),{text:a,...l}=e.modelSettings.providerData??{};e.modelSettings.reasoning&&(l.reasoning={...e.modelSettings.reasoning,...l.reasoning});let c=a;e.modelSettings.text&&(c={...e.modelSettings.text,...a});const u=(p=c,"text"===(d=e.outputType)?p:{...p,format:d});var d,p;const h=function(e){if(!e)return;const t={};for(const[s,n]of Object.entries(e.variables??{}))"string"==typeof n?t[s]=n:"object"==typeof n&&(t[s]=jn(n));return{id:e.promptId,version:e.version,variables:t}}(e.prompt);let f;if("boolean"==typeof e.modelSettings.parallelToolCalls){if(e.modelSettings.parallelToolCalls&&0===r.length)throw new Error("Parallel tool calls are not supported without tools");f=e.modelSettings.parallelToolCalls}const m={model:this.#t,instructions:Jn(e.systemInstructions),input:s,include:o,tools:r,previous_response_id:e.previousResponseId,conversation:e.conversationId,prompt:h,temperature:e.modelSettings.temperature,top_p:e.modelSettings.topP,truncation:e.modelSettings.truncation,max_output_tokens:e.modelSettings.maxTokens,tool_choice:i,parallel_tool_calls:f,stream:t,text:u,store:e.modelSettings.store,...l};An.dontLogModelData?An.debug("Calling LLM"):An.debug(`Calling LLM. Request data: ${JSON.stringify(m,null,2)}`);const g=await this.#e.responses.create(m,{headers:Sn,signal:e.signal});return An.dontLogModelData?An.debug("Response received"):An.debug(`Response received: ${JSON.stringify(g,null,2)}`),g}async getResponse(e){const t=await(0,n.Cp)(async t=>{const s=await this.#s(e,!1);return e.tracing&&(t.spanData.response_id=s.id,t.spanData._input=e.input,t.spanData._response=s),s});return{usage:new n._U({inputTokens:t.usage?.input_tokens??0,outputTokens:t.usage?.output_tokens??0,totalTokens:t.usage?.total_tokens??0,inputTokensDetails:{...t.usage?.input_tokens_details},outputTokensDetails:{...t.usage?.output_tokens_details}}),output:Fn(t.output),responseId:t.id,providerData:t}}async*getStreamedResponse(e){const t=e.tracing?(0,n.UI)():void 0;try{t&&(t.start(),(0,n.mq)(t),!0===e.tracing&&(t.spanData._input=e.input));const s=await this.#s(e,!0);let r;for await(const e of s){if("response.created"===e.type)yield{type:"response_started",providerData:{...e}};else if("response.completed"===e.type){r=e.response;const{response:t,...s}=e,{output:n,usage:o,id:i,...a}=t;yield{type:"response_done",response:{id:i,output:Fn(n),usage:{inputTokens:o?.input_tokens??0,outputTokens:o?.output_tokens??0,totalTokens:o?.total_tokens??0,inputTokensDetails:{...o?.input_tokens_details},outputTokensDetails:{...o?.output_tokens_details}},providerData:a},providerData:s},yield{type:"model",event:e}}else if("response.output_text.delta"===e.type){const{delta:t,...s}=e;yield{type:"output_text_delta",delta:t,providerData:s}}yield{type:"model",event:e}}e.tracing&&t&&r&&(t.spanData.response_id=r.id,t.spanData._response=r)}catch(s){throw t&&t.setError({message:"Error streaming response",data:{error:e.tracing?String(s):s instanceof Error?s.name:void 0}}),s}finally{t&&(t.end(),(0,n.h6)())}}}function Jn(e){if("string"==typeof e){if(""===e.trim())return;return e}}function Kn(e){if(null!=e&&null!=e)return"auto"===e||"required"===e||"none"===e?e:{type:"function",function:{name:e}}}function Xn(e){if("string"==typeof e)return e;const t=[];for(const s of e)if("output_text"===s.type)t.push({type:"text",text:s.text,...s.providerData});else{if("refusal"!==s.type){if("audio"===s.type||"image"===s.type)continue;{const e=s;throw new Error(`Unknown content: ${JSON.stringify(e)}`)}}t.push({type:"refusal",refusal:s.refusal,...s.providerData})}return t}function zn(e){if("string"==typeof e)return e;const t=[];for(const s of e)if("input_text"===s.type)t.push({type:"text",text:s.text,...s.providerData});else if("input_image"===s.type){if("string"!=typeof s.image)throw new Error(`Only image URLs are supported for input_image: ${JSON.stringify(s)}`);const{image_url:e,...n}=s.providerData||{};t.push({type:"image_url",image_url:{url:s.image,...e},...n})}else{if("input_file"===s.type)throw new Error(`File uploads are not supported for chat completions: ${JSON.stringify(s)}`);if("audio"!==s.type){const e=s;throw new Error(`Unknown content: ${JSON.stringify(e)}`)}{const{input_audio:e,...n}=s.providerData||{};t.push({type:"input_audio",input_audio:{data:s.audio,...e},...n})}}return t}function Gn(e){return"message"===e.type||void 0===e.type&&"string"==typeof e.role}function Vn(e){if("function"===e.type)return{type:"function",function:{name:e.name,description:e.description||"",parameters:e.parameters,strict:e.strict}};throw new Error(`Hosted tools are not supported with the ChatCompletions API. Got tool type: ${e.type}, tool: ${JSON.stringify(e)}`)}function Qn(e){return{type:"function",function:{name:e.toolName,description:e.toolDescription||"",parameters:e.inputJsonSchema}}}const Zn="FAKE_ID";class Yn{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async getResponse(e){const t=await(0,n.hn)(async t=>{t.spanData.model=this.#t,t.spanData.model_config=e.modelSettings?{temperature:e.modelSettings.temperature,top_p:e.modelSettings.topP,frequency_penalty:e.modelSettings.frequencyPenalty,presence_penalty:e.modelSettings.presencePenalty,reasoning_effort:e.modelSettings.reasoning?.effort,verbosity:e.modelSettings.text?.verbosity}:{base_url:this.#e.baseURL};const s=await this.#s(e,t,!1);return t&&!0===e.tracing&&(t.spanData.output=[s]),s}),s=[];if(t.choices&&t.choices[0]){const e=t.choices[0].message;if(function(e){return"reasoning"in e&&"string"==typeof e.reasoning&&""!==e.reasoning}(e)&&s.push({type:"reasoning",content:[],rawContent:[{type:"reasoning_text",text:e.reasoning}]}),void 0===e.content||null===e.content||e.tool_calls&&""===e.content){if(e.refusal){const{refusal:n,...r}=e;s.push({id:t.id,type:"message",role:"assistant",content:[{type:"refusal",refusal:n||"",providerData:r}],status:"completed"})}else if(e.audio){const{data:n,...r}=e.audio;s.push({id:t.id,type:"message",role:"assistant",content:[{type:"audio",audio:n,providerData:r}],status:"completed"})}else if(e.tool_calls)for(const n of e.tool_calls)if("function"===n.type){const{id:e,...r}=n,{arguments:o,name:i,...a}=n.function;s.push({id:t.id,type:"function_call",arguments:o,name:i,callId:e,status:"completed",providerData:{...r,...a}})}}else{const{content:n,...r}=e;s.push({id:t.id,type:"message",role:"assistant",content:[{type:"output_text",text:n||"",providerData:r}],status:"completed"})}}var r;return{usage:t.usage?new n._U((r=t.usage,{requests:1,input_tokens:r.prompt_tokens,output_tokens:r.completion_tokens,total_tokens:r.total_tokens,input_tokens_details:{cached_tokens:r.prompt_tokens_details?.cached_tokens||0},output_tokens_details:{reasoning_tokens:r.completion_tokens_details?.reasoning_tokens||0}})):new n._U,output:s,responseId:t.id,providerData:t}}async*getStreamedResponse(e){const t=e.tracing?(0,n.Xq)():void 0;try{t&&(t.start(),(0,n.mq)(t));const s=await this.#s(e,t,!0),r={id:Zn,created:Math.floor(Date.now()/1e3),model:this.#t,object:"chat.completion",choices:[],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}};for await(const e of async function*(e,t){let s;const n={started:!1,text_content_index_and_output:null,refusal_content_index_and_output:null,function_calls:{},reasoning:""};for await(const e of t){if(n.started||(n.started=!0,yield{type:"response_started",providerData:{...e}}),yield{type:"model",event:e},s=e.usage||void 0,!e.choices?.[0]?.delta)continue;const t=e.choices[0].delta;if(t.content&&(n.text_content_index_and_output||(n.text_content_index_and_output=[n.refusal_content_index_and_output?1:0,{text:"",type:"output_text",providerData:{annotations:[]}}]),yield{type:"output_text_delta",delta:t.content,providerData:{...e}},n.text_content_index_and_output[1].text+=t.content),"reasoning"in t&&t.reasoning&&"string"==typeof t.reasoning&&(n.reasoning+=t.reasoning),"refusal"in t&&t.refusal&&(n.refusal_content_index_and_output||(n.refusal_content_index_and_output=[n.text_content_index_and_output?1:0,{refusal:"",type:"refusal"}]),n.refusal_content_index_and_output[1].refusal+=t.refusal),t.tool_calls)for(const e of t.tool_calls){e.index in n.function_calls||(n.function_calls[e.index]={id:Zn,arguments:"",name:"",type:"function_call",callId:""});const t=e.function;n.function_calls[e.index].arguments+=t?.arguments||"",n.function_calls[e.index].name+=t?.name||"",n.function_calls[e.index].callId+=e.id||""}}const r=[];if(n.reasoning&&r.push({type:"reasoning",content:[],rawContent:[{type:"reasoning_text",text:n.reasoning}]}),n.text_content_index_and_output||n.refusal_content_index_and_output){const e={id:Zn,content:[],role:"assistant",type:"message",status:"completed"};n.text_content_index_and_output&&e.content.push(n.text_content_index_and_output[1]),n.refusal_content_index_and_output&&e.content.push(n.refusal_content_index_and_output[1]),r.push(e)}for(const e of Object.values(n.function_calls))r.push(e);const o={type:"response_done",response:{id:e.id,usage:{inputTokens:s?.prompt_tokens??0,outputTokens:s?.completion_tokens??0,totalTokens:s?.total_tokens??0,inputTokensDetails:{cached_tokens:s?.prompt_tokens_details?.cached_tokens??0},outputTokensDetails:{reasoning_tokens:s?.completion_tokens_details?.reasoning_tokens??0}},output:r}};yield o}(r,s))yield e;t&&r&&!0===e.tracing&&(t.spanData.output=[r])}catch(s){throw t&&t.setError({message:"Error streaming response",data:{error:!0===e.tracing?String(s):s instanceof Error?s.name:void 0}}),s}finally{t&&(t.end(),(0,n.h6)())}}async#s(e,t,s){const r=[];if(e.tools)for(const t of e.tools)r.push(Vn(t));if(e.handoffs)for(const t of e.handoffs)r.push(Qn(t));const o="text"===(i=e.outputType)?{type:"text"}:"json_schema"===i.type?{type:"json_schema",json_schema:{name:i.name,strict:i.strict,schema:i.schema}}:{type:"json_object"};var i;let a;if("boolean"==typeof e.modelSettings.parallelToolCalls){if(e.modelSettings.parallelToolCalls&&0===r.length)throw new Error("Parallel tool calls are not supported without tools");a=e.modelSettings.parallelToolCalls}const l=function(e){if("string"==typeof e)return[{role:"user",content:e}];const t=[];let s=null;const r=()=>{s&&(s.tool_calls&&0!==s.tool_calls.length||delete s.tool_calls,t.push(s),s=null)},o=()=>(s||(s={role:"assistant",tool_calls:[]}),s);for(const s of e)if(Gn(s)){const{content:e,role:n,providerData:o}=s;if(r(),"assistant"===n){const s={role:"assistant",content:Xn(e),...o};if(Array.isArray(e)){const t=e.find(e=>"audio"===e.type);t&&(s.audio={id:"",...t.providerData})}t.push(s)}else"user"===n?t.push({role:n,content:zn(e),...o}):"system"===n&&t.push({role:"system",content:e,...o})}else{if("reasoning"===s.type){o().reasoning=s.rawContent?.[0]?.text;continue}if("hosted_tool_call"===s.type){if("file_search_call"===s.name){const e=o(),t=e.tool_calls??[],n=s,{function:r,...i}=n.providerData??{},{arguments:a,...l}=r??{};t.push({id:n.id||"",type:"function",function:{name:"file_search_call",arguments:JSON.stringify({queries:n.providerData?.queries??[],status:n.status,...a}),...l},...i}),e.tool_calls=t;continue}throw new n.yo("Hosted tool calls are not supported for chat completions. Got item: "+JSON.stringify(s))}if("computer_call"===s.type||"computer_call_result"===s.type)throw new n.yo("Computer use calls are not supported for chat completions. Got item: "+JSON.stringify(s));if("function_call"===s.type){const e=o(),t=e.tool_calls??[],n=s;t.push({id:n.callId,type:"function",function:{name:n.name,arguments:n.arguments??"{}"}}),e.tool_calls=t}else if("function_call_result"===s.type){r();const e=s;if("text"!==e.output.type)throw new n.yo("Only text output is supported for chat completions. Got item: "+JSON.stringify(s));t.push({role:"tool",tool_call_id:e.callId,content:e.output.text,...e.providerData})}else{if("unknown"!==s.type){const e=s;throw new Error(`Unknown item type: ${JSON.stringify(e)}`)}t.push({...s.providerData})}}return r(),t}(e.input);e.systemInstructions&&l.unshift({content:e.systemInstructions,role:"system"}),t&&!0===e.tracing&&(t.spanData.input=l);const c=e.modelSettings.providerData??{};e.modelSettings.reasoning&&e.modelSettings.reasoning.effort&&(c.reasoning_effort=e.modelSettings.reasoning.effort),e.modelSettings.text&&e.modelSettings.text.verbosity&&(c.verbosity=e.modelSettings.text.verbosity);const u={model:this.#t,messages:l,tools:r.length?r:void 0,temperature:e.modelSettings.temperature,top_p:e.modelSettings.topP,frequency_penalty:e.modelSettings.frequencyPenalty,presence_penalty:e.modelSettings.presencePenalty,max_tokens:e.modelSettings.maxTokens,tool_choice:Kn(e.modelSettings.toolChoice),response_format:o,parallel_tool_calls:a,stream:s,store:e.modelSettings.store,...c};An.dontLogModelData?An.debug("Calling LLM"):An.debug(`Calling LLM. Request data: ${JSON.stringify(u,null,2)}`);const d=await this.#e.chat.completions.create(u,{headers:Sn,signal:e.signal});return An.dontLogModelData?An.debug("Response received"):An.debug(`Response received: ${JSON.stringify(d,null,2)}`),d}}class er{#e;#n;#r;constructor(e={}){if(this.#r=e,this.#r.openAIClient){if(this.#r.apiKey)throw new Error("Cannot provide both apiKey and openAIClient");if(this.#r.baseURL)throw new Error("Cannot provide both baseURL and openAIClient");this.#e=this.#r.openAIClient}this.#n=this.#r.useResponses}#o(){return this.#e||(this.#e=mn??new hn({apiKey:this.#r.apiKey??gn??(0,fn.y)().OPENAI_API_KEY,baseURL:this.#r.baseURL,organization:this.#r.organization,project:this.#r.project})),this.#e}async getModel(e){const t=e||(0,n.fZ)();return this.#n??"responses"===yn?new Hn(this.#o(),t):new Yn(this.#o(),t)}}class tr{#r;constructor(e={}){this.#r={apiKey:e.apiKey??void 0,organization:e.organization??"",project:e.project??"",endpoint:e.endpoint??"https://api.openai.com/v1/traces/ingest",maxRetries:e.maxRetries??3,baseDelay:e.baseDelay??1e3,maxDelay:e.maxDelay??3e4}}async export(e,t){const s=this.#r.apiKey??_n??(0,fn.y)().OPENAI_API_KEY;if(!s)return void An.error("No API key provided for OpenAI tracing exporter. Exports will be skipped");const n={data:e.map(e=>e.toJSON()).filter(e=>!!e)};let r=0,o=this.#r.baseDelay;for(;r<this.#r.maxRetries;){try{const e=await fetch(this.#r.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"OpenAI-Beta":"traces=v1",...Sn},body:JSON.stringify(n),signal:t});if(e.ok)return void An.debug(`Exported ${n.data.length} items`);if(e.status>=400&&e.status<500)return void An.error(`[non-fatal] Tracing client error ${e.status}: ${await e.text()}`);An.warn(`[non-fatal] Tracing: server error ${e.status}, retrying.`)}catch(e){An.error("[non-fatal] Tracing: request failed: ",e)}if(t?.aborted)return void An.error("Tracing: request aborted");const e=o+.1*Math.random()*o;await new Promise(t=>setTimeout(t,e)),o=Math.min(2*o,this.#r.maxDelay),r++}An.error(`Tracing: failed to export traces after ${this.#r.maxRetries} attempts`)}}function sr(){const e=new tr,t=new n.AF(e);(0,n.JA)([t])}var nr=s(885);(0,n.MJ)(new er),sr()}}]);