@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.
- package/package.json +4 -3
- package/static/dist/_output/build/schemas/all_federated.json +1 -1
- package/static/dist/_output/extensions/@jupyterlite/ai/install.json +5 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/package.json +252 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/schemas/@jupyterlite/ai/settings-model.json +194 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/116.010504c67cccbe983101.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/155.33f38a7e48ddbeb5bb6e.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/180.96635ff74c0413e0c580.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/19.a1bb726875fe6561330e.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/306.17ff80cd7d3702012f98.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/313.e439dd0f4960f6e7585f.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/324.77487b82034275866b8c.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/340.e42ea25ea5b1b374a682.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/374.d7b4dcf29eb3d2ebfd70.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/472.05d097796e83ea9a22b4.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/529.600d1aebb2de2d73fecb.js +2 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/529.600d1aebb2de2d73fecb.js.LICENSE.txt +8 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/537.eb8d9ccd76231e36d75f.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/593.284fd5d2b50defc573f3.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/665.564d208c226b2753e13b.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/669.0094374ba6e3143702f7.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/692.911f4d7dca73b3737833.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/694.e439dd0f4960f6e7585f.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/709.7578153f9eed366ee430.js +2 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/709.7578153f9eed366ee430.js.LICENSE.txt +19 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/728.d7c2cb9a2f7fdd846b35.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/764.312b4b53ed50be5bf3f8.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/798.dca29a3fc3b23c555f6b.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/88.898492ebc5b41a4607c6.js +2 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/88.898492ebc5b41a4607c6.js.LICENSE.txt +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/885.1670a5138e0a13def795.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/918.e91fcd78edba173284a4.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/92.55c2fe71a33184c2e66d.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/952.003f03c751075980ac7f.js +183 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/remoteEntry.2f103c13fd640ab93eb9.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/style.js +4 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/third-party-licenses.json +352 -0
- package/static/dist/_output/extensions/jl-galaxy/extension.js +1 -1
- package/static/dist/_output/extensions/jupyter-secrets-manager/install.json +5 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/package.json +207 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/schemas/jupyter-secrets-manager/manager.json +14 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/728.69cdb8043c4eb7a36084.js +1 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/810.7ac328ef761c19894484.js +1 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/remoteEntry.6610dc2c9e0921c7f94a.js +1 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/third-party-licenses.json +16 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/install.json +5 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/package.json +90 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/374.f7ab05aeba5c1aa173c9.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/432.7cb3263d05824765a0d2.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/509.9384daafd8fb72a4ff3a.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/993.f7ab05aeba5c1aa173c9.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/remoteEntry.f80ac7a8e97b08d2a2fd.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/third-party-licenses.json +22 -0
- package/static/dist/_output/extensions/jupyterlab-diff/install.json +5 -0
- package/static/dist/_output/extensions/jupyterlab-diff/package.json +224 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/299.07069b808cb23f84a242.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/379.2e2a6add1111d74422d2.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/383.dbd292b18614d410ed4b.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/499.e9c141febe62f251e965.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/680.07069b808cb23f84a242.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/728.559a28b17e14994cba46.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/747.e3256716cc1134700a59.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/879.749253139a5186f32109.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/remoteEntry.4830528fbe7c3ca55989.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/third-party-licenses.json +94 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/install.json +5 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/package.json +90 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/432.57100b29bc9fea211a0e.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/509.d1cc43983763b6a85f45.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/666.84cadfe40c86b502f11d.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/remoteEntry.5577376b289c1f9e2dc2.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/third-party-licenses.json +22 -0
- package/static/dist/_output/jupyter-lite.json +43 -20
- package/static/dist/_output/pypi/attrs-25.4.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/gxy-0.0.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/jupyter_core-5.9.1-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/narwhals-2.13.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/{platformdirs-4.4.0-py3-none-any.whl → platformdirs-4.5.1-py3-none-any.whl} +0 -0
- package/static/dist/_output/pypi/referencing-0.37.0-py3-none-any.whl +0 -0
- package/static/dist/index.js +2 -2
- package/static/dist/_output/pypi/attrs-25.3.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/jupyter_core-5.8.1-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/narwhals-2.6.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/referencing-0.36.2-py3-none-any.whl +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[885],{26:(t,e,n)=>{"use strict";n.d(e,{Nn:()=>p,QL:()=>h,SZ:()=>l,YP:()=>u,eE:()=>g,h6:()=>m,j3:()=>i,mq:()=>d});var r=n(341),o=n(2618);let s;function a(){return s??=new r.TM,s}function i(){const t=a().getStore();return t?.trace?t.trace:null}function u(){const t=a().getStore();return t?.span?t.span:null}function c(t){return async()=>{const e=i();if(!e)throw new Error("No trace found");await e.start();const n=await t(e);return await e.end(),n}}async function l(t,e,n={}){const r="string"==typeof t?(0,o.A)().createTrace({...n,name:t}):t;return a().run({trace:r},c(e))}async function p(t,e={}){if(i())return await t();const n=(0,o.A)().createTrace(e);return a().run({trace:n},c(t))}function d(t){const e=a().getStore();if(!e)throw new Error("No existing trace found");e.span&&(e.span.previousSpan=e.previousSpan,e.previousSpan=e.span),e.span=t,a().enterWith(e)}function m(){const t=a().getStore();t&&(t.span=t.previousSpan,t.previousSpan=t.previousSpan?.previousSpan,a().enterWith(t))}function g(t){const e=u();e&&e.setError(t)}function h(t){const e=a().getStore();if(!e)throw new Error("No existing trace found");const n=(r=e,{trace:r.trace?.clone(),span:r.span?.clone(),previousSpan:r.previousSpan?.clone()});var r;return a().run(n,t)}},341:(t,e,n)=>{"use strict";n.d(e,{TM:()=>m,p2:()=>a,l6:()=>o,Wm:()=>s,$p:()=>l,ZY:()=>p,j3:()=>u,Rv:()=>d,Iz:()=>g,am:()=>h,y:()=>i,N4:()=>c,O1:()=>f});var r=n(7788);class o extends r.Ar{constructor(t){super(t)}get name(){return"MCPServerStdio"}connect(){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}listTools(){throw new Error("Method not implemented.")}callTool(t,e){throw new Error("Method not implemented.")}invalidateToolsCache(){throw new Error("Method not implemented.")}}class s extends r.Dg{constructor(t){super(t)}get name(){return"MCPServerStdio"}connect(){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}listTools(){throw new Error("Method not implemented.")}callTool(t,e){throw new Error("Method not implemented.")}invalidateToolsCache(){throw new Error("Method not implemented.")}}class a extends r.W4{constructor(t){super(t)}get name(){return"MCPServerSSE"}connect(){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}listTools(){throw new Error("Method not implemented.")}callTool(t,e){throw new Error("Method not implemented.")}invalidateToolsCache(){throw new Error("Method not implemented.")}}function i(){return{}}class u{#t=new EventTarget;#e=new Map;on(t,e){const n=t;let r=this.#e.get(n);r||(r=new Map,this.#e.set(n,r));let o=r.get(e);o||(o=new Set,r.set(e,o));const s=t=>e(...t.detail??[]);return o.add(s),this.#t.addEventListener(n,s),this}off(t,e){const n=t,r=this.#e.get(n),o=r?.get(e);if(o?.size){for(const t of o)this.#t.removeEventListener(n,t);r?.delete(e),0===r?.size&&this.#e.delete(n)}return this}emit(t,...e){const n=new CustomEvent(t,{detail:e});return this.#t.dispatchEvent(n)}once(t,e){const n=(...r)=>{this.off(t,n),e(...r)};return this.on(t,n),this}}const c=()=>"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}),l=class{constructor(){}pipeTo(t,e){}pipeThrough(t,e){}},p=globalThis.ReadableStream,d=(globalThis.ReadableStreamDefaultController,globalThis.TransformStream);class m{context=null;constructor(){}run(t,e){return this.context=t,e()}getStore(){return this.context}enterWith(t){this.context=t}}function g(){return!0}function h(){return!1}const f=new class{constructor(){}setTimeout(t,e){const n=setTimeout(t,e);return n.ref="function"==typeof n.ref?n.ref:()=>n,n.unref="function"==typeof n.unref?n.unref:()=>n,n.hasRef="function"==typeof n.hasRef?n.hasRef:()=>!0,n.refresh="function"==typeof n.refresh?n.refresh:()=>n,n}clearTimeout(t){window.clearTimeout(t)}}},476:(t,e,n)=>{"use strict";n.d(e,{$t:()=>m,B9:()=>b,Cp:()=>i,DT:()=>d,Ee:()=>y,Eu:()=>_,L0:()=>x,LG:()=>w,M6:()=>u,PJ:()=>p,UC:()=>I,UI:()=>a,Xq:()=>g,cS:()=>v,cW:()=>S,hn:()=>h,it:()=>A,mp:()=>c,tL:()=>z,tQ:()=>l,ub:()=>f,ux:()=>T});var r=n(26),o=n(2618);function s(t){return async(e,...n)=>(0,r.QL)(async()=>{const o=t(...n);(0,r.mq)(o);try{return o.start(),await e(o)}catch(t){throw o.setError({message:t.message,data:t.data}),t}finally{o.end(),(0,r.h6)()}})}function a(t,e){return t={},(0,o.A)().createSpan({...t,data:{type:"response",...t.data}},e)}const i=s(a);function u(t,e){return(0,o.A)().createSpan({...t,data:{type:"agent",name:t?.data?.name??"Agent",...t?.data}},e)}const c=s(u);function l(t,e){return(0,o.A)().createSpan({...t,data:{type:"function",input:t?.data?.input??"",output:t?.data?.output??"",...t?.data}},e)}const p=s(l);function d(t,e){return(0,o.A)().createSpan({...t,data:{type:"handoff",...t?.data}},e)}const m=s(d);function g(t,e){return(0,o.A)().createSpan({...t,data:{type:"generation",...t?.data}},e)}const h=s(g);function f(t,e){return(0,o.A)().createSpan({...t,data:{type:"custom",data:{},...t?.data}},e)}const y=s(f);function _(t,e){return(0,o.A)().createSpan({...t,data:{type:"guardrail",triggered:!1,...t?.data}},e)}const v=s(_);function b(t,e){return(0,o.A)().createSpan({...t,data:{type:"transcription",...t.data}},e)}const w=s(b);function z(t,e){return(0,o.A)().createSpan({...t,data:{type:"speech",...t.data}},e)}const x=s(z);function A(t,e){return(0,o.A)().createSpan({...t,data:{type:"speech_group",...t?.data}},e)}const I=s(A);function T(t,e){return(0,o.A)().createSpan({...t,data:{type:"mcp_tools",...t?.data}},e)}const S=s(T)},736:(t,e,n)=>{t.exports=function(t){function e(t){let n,o,s,a=null;function i(...t){if(!i.enabled)return;const r=i,o=Number(new Date),s=o-(n||o);r.diff=s,r.prev=n,r.curr=o,n=o,t[0]=e.coerce(t[0]),"string"!=typeof t[0]&&t.unshift("%O");let a=0;t[0]=t[0].replace(/%([a-zA-Z%])/g,(n,o)=>{if("%%"===n)return"%";a++;const s=e.formatters[o];if("function"==typeof s){const e=t[a];n=s.call(r,e),t.splice(a,1),a--}return n}),e.formatArgs.call(r,t),(r.log||e.log).apply(r,t)}return i.namespace=t,i.useColors=e.useColors(),i.color=e.selectColor(t),i.extend=r,i.destroy=e.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(o!==e.namespaces&&(o=e.namespaces,s=e.enabled(t)),s),set:t=>{a=t}}),"function"==typeof e.init&&e.init(i),i}function r(t,n){const r=e(this.namespace+(void 0===n?":":n)+t);return r.log=this.log,r}function o(t,e){let n=0,r=0,o=-1,s=0;for(;n<t.length;)if(r<e.length&&(e[r]===t[n]||"*"===e[r]))"*"===e[r]?(o=r,s=n,r++):(n++,r++);else{if(-1===o)return!1;r=o+1,s++,n=s}for(;r<e.length&&"*"===e[r];)r++;return r===e.length}return e.debug=e,e.default=e,e.coerce=function(t){return t instanceof Error?t.stack||t.message:t},e.disable=function(){const t=[...e.names,...e.skips.map(t=>"-"+t)].join(",");return e.enable(""),t},e.enable=function(t){e.save(t),e.namespaces=t,e.names=[],e.skips=[];const n=("string"==typeof t?t:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const t of n)"-"===t[0]?e.skips.push(t.slice(1)):e.names.push(t)},e.enabled=function(t){for(const n of e.skips)if(o(t,n))return!1;for(const n of e.names)if(o(t,n))return!0;return!1},e.humanize=n(6585),e.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(t).forEach(n=>{e[n]=t[n]}),e.names=[],e.skips=[],e.formatters={},e.selectColor=function(t){let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n|=0;return e.colors[Math.abs(n)%e.colors.length]},e.enable(e.load()),e}},839:(t,e,n)=>{"use strict";n.d(e,{J4:()=>o,aD:()=>c,bi:()=>i,xp:()=>s}),n(7036);var r=n(9731);function o(t,e){return e&&function(t){return!!(0,r.U)(t.text?.format)}(e)?s(t,e):{...t,output_parsed:null,output:t.output.map(t=>"function_call"===t.type?{...t,parsed_arguments:null}:"message"===t.type?{...t,content:t.content.map(t=>({...t,parsed:null}))}:t)}}function s(t,e){const n=t.output.map(t=>{if("function_call"===t.type)return{...t,parsed_arguments:u(e,t)};if("message"===t.type){const n=t.content.map(t=>"output_text"===t.type?{...t,parsed:a(e,t.text)}:t);return{...t,content:n}}return t}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||c(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const t of r.output)if("message"===t.type)for(const e of t.content)if("output_text"===e.type&&null!==e.parsed)return e.parsed;return null}}),r}function a(t,e){if("json_schema"!==t.text?.format?.type)return null;if("$parseRaw"in t.text?.format){const n=t.text?.format;return n.$parseRaw(e)}return JSON.parse(e)}function i(t,{parser:e,callback:n}){const r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-tool",enumerable:!1},$parseRaw:{value:e,enumerable:!1},$callback:{value:n,enumerable:!1}}),r}function u(t,e){const n=(r=t.tools??[],o=e.name,r.find(t=>"function"===t.type&&t.name===o));var r,o,s;return{...e,...e,parsed_arguments:(s=n,"auto-parseable-tool"===s?.$brand?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null)}}function c(t){const e=[];for(const n of t.output)if("message"===n.type)for(const t of n.content)"output_text"===t.type&&e.push(t.text);t.output_text=e.join("")}},885:(t,e,n)=>{"use strict";n.r(e),n.d(e,{DEFAULT_OPENAI_REALTIME_MODEL:()=>kt,DEFAULT_OPENAI_REALTIME_SESSION_CONFIG:()=>Pt,ModelBehaviorError:()=>o.af,OpenAIRealtimeBase:()=>Et,OpenAIRealtimeWebRTC:()=>jt,OpenAIRealtimeWebSocket:()=>Rt,OutputGuardrailTripwireTriggered:()=>o.K6,RealtimeAgent:()=>g,RealtimeSession:()=>$t,UserError:()=>o.yo,backgroundResult:()=>Mt,isBackgroundResult:()=>Dt,tool:()=>o.z6,utils:()=>Zt});const r="0.1.8";var o=n(6162);function s(t){const e=atob(t),n=e.length,r=new Uint8Array(n);for(let t=0;t<n;t++)r[t]=e.charCodeAt(t);return r.buffer}function a(t){const e=String.fromCharCode(...new Uint8Array(t));return btoa(e)}function i(t){if(null==t||"object"!=typeof t||!("type"in t)||"string"!=typeof t.type||!t.type)return;if("message"!==t.type)return;if(!("content"in t)||!Array.isArray(t.content)||t.content.length<1)return;const e=t.content[t.content.length-1];return"type"in e&&"string"==typeof e.type?"output_text"===e.type?"string"==typeof e.text?e.text:void 0:"output_audio"===e.type&&"string"==typeof e.transcript?e.transcript:void 0:void 0}function u(t){return"system"===t.role?t:"assistant"===t.role?{...t,content:t.content.map(t=>"output_audio"===t.type?{...t,audio:null}:t)}:"user"===t.role?{...t,content:t.content.map(t=>"input_audio"===t.type?{...t,audio:null}:t)}:t}function c(t,e,n){if("conversation.item.input_audio_transcription.completed"===e.type)return t.map(t=>{if(t.itemId===e.item_id&&"message"===t.type&&"role"in t&&"user"===t.role){const n=t.content.map(t=>"input_audio"===t.type?{...t,transcript:e.transcript}:t);return{...t,content:n,status:"completed"}}return t});const r=n||"message"!==e.type?e:u(e),o=t.findIndex(t=>t.itemId===e.itemId);if(-1!==o)return t.map((t,e)=>e===o?r:n||"message"!==t.type?t:u(t));if(e.previousItemId){const n=t.findIndex(t=>t.itemId===e.previousItemId);return-1!==n?[...t.slice(0,n+1),r,...t.slice(n+1)]:[...t,r]}return[...t,r]}const l={"User-Agent":`Agents/JavaScript ${r}`,"X-OpenAI-Agents-SDK":`openai-agents-sdk.${r}`},p=`openai-agents-sdk.${r}`;function d(t,e){const{name:n,arguments:r,...s}=e;return new o.A9({type:"hosted_tool_call",name:n,arguments:JSON.stringify(r),status:"in_progress",providerData:{...s}},t)}function m(t){const{name:e,arguments:n,providerData:r}=t.rawItem,{itemId:o,serverLabel:s,...a}=r??{};if(!o||!s)throw new Error("Invalid approval item for Realtime MCP approval request");return{type:"mcp_approval_request",itemId:o,serverLabel:s,...a,name:e,arguments:n?JSON.parse(n):{},approved:null}}class g extends o.g6{voice;constructor(t){super(t),this.voice=t.voice}}var h=n(341),f=n(7962);function y({policyHint:t,...e}){const n=(0,o._o)(e),r=t??n.name;return{...n,policyHint:r,run:async t=>{const e=await n.run(t);return{...e,guardrail:{...e.guardrail,policyHint:r}}}}}function _(t,e){return t in e&&void 0!==e[t]}function v(t){if(!t)return;if("object"==typeof t)return t;const e=String(t);return"pcm16"===e?{type:"audio/pcm",rate:24e3}:"g711_ulaw"===e?{type:"audio/pcmu"}:"g711_alaw"===e?{type:"audio/pcma"}:{type:"audio/pcm",rate:24e3}}var b=n(4231);b.z.object({itemId:b.z.string()});const w=b.z.discriminatedUnion("role",[b.z.object({itemId:b.z.string(),previousItemId:b.z.string().nullable().optional(),type:b.z.literal("message"),role:b.z.literal("system"),content:b.z.array(b.z.object({type:b.z.literal("input_text"),text:b.z.string()}))}),b.z.object({itemId:b.z.string(),previousItemId:b.z.string().nullable().optional(),type:b.z.literal("message"),role:b.z.literal("user"),status:b.z.enum(["in_progress","completed"]),content:b.z.array(b.z.object({type:b.z.literal("input_text"),text:b.z.string()}).or(b.z.object({type:b.z.literal("input_audio"),audio:b.z.string().nullable().optional(),transcript:b.z.string().nullable()})))}),b.z.object({itemId:b.z.string(),previousItemId:b.z.string().nullable().optional(),type:b.z.literal("message"),role:b.z.literal("assistant"),status:b.z.enum(["in_progress","completed","incomplete"]),content:b.z.array(b.z.object({type:b.z.literal("output_text"),text:b.z.string()}).or(b.z.object({type:b.z.literal("output_audio"),audio:b.z.string().nullable().optional(),transcript:b.z.string().nullable().optional()})))})]),z=b.z.object({itemId:b.z.string(),previousItemId:b.z.string().nullable().optional(),type:b.z.literal("function_call"),status:b.z.enum(["in_progress","completed","incomplete"]),arguments:b.z.string(),name:b.z.string(),output:b.z.string().nullable()}),x=b.z.object({itemId:b.z.string(),previousItemId:b.z.string().nullable().optional(),type:b.z.enum(["mcp_call","mcp_tool_call"]),status:b.z.enum(["in_progress","completed","incomplete"]),arguments:b.z.string(),name:b.z.string(),output:b.z.string().nullable()}),A=b.z.object({itemId:b.z.string(),type:b.z.literal("mcp_approval_request"),serverLabel:b.z.string(),name:b.z.string(),arguments:b.z.record(b.z.string(),b.z.any()),approved:b.z.boolean().optional().nullable()}),I=(0,o.tZ)("openai-agents:realtime"),T=b.z.object({id:b.z.string().optional().nullable(),conversation_id:b.z.string().optional().nullable(),max_output_tokens:b.z.number().or(b.z.literal("inf")).optional().nullable(),metadata:b.z.record(b.z.string(),b.z.any()).optional().nullable(),output_modalities:b.z.array(b.z.string()).optional().nullable(),object:b.z.literal("realtime.response").optional().nullable(),output:b.z.array(b.z.any()).optional().nullable(),audio:b.z.object({output:b.z.object({format:b.z.any().optional().nullable(),voice:b.z.string().optional().nullable()}).optional().nullable()}).optional().nullable(),status:b.z.enum(["completed","incomplete","failed","cancelled","in_progress"]).optional().nullable(),status_details:b.z.record(b.z.string(),b.z.any()).optional().nullable(),usage:b.z.object({input_tokens:b.z.number().optional(),input_tokens_details:b.z.record(b.z.string(),b.z.any()).optional().nullable(),output_tokens:b.z.number().optional(),output_tokens_details:b.z.record(b.z.string(),b.z.any()).optional().nullable()}).optional().nullable()}),S=b.z.object({id:b.z.string().optional(),audio:b.z.string().nullable().optional(),text:b.z.string().nullable().optional(),transcript:b.z.string().nullable().optional(),type:b.z.union([b.z.literal("input_text"),b.z.literal("input_audio"),b.z.literal("item_reference"),b.z.literal("output_text"),b.z.literal("output_audio")])}),C=b.z.object({id:b.z.string().optional(),arguments:b.z.string().optional(),call_id:b.z.string().optional(),content:b.z.array(S).optional(),name:b.z.string().optional(),output:b.z.string().nullable().optional(),role:b.z.enum(["user","assistant","system"]).optional(),status:b.z.enum(["completed","incomplete","in_progress"]).optional(),type:b.z.enum(["message","function_call","function_call_output","mcp_list_tools","mcp_tool_call","mcp_call","mcp_approval_request","mcp_approval_response"]).optional(),approval_request_id:b.z.string().nullable().optional(),approve:b.z.boolean().nullable().optional(),reason:b.z.string().nullable().optional(),server_label:b.z.string().optional(),error:b.z.any().nullable().optional(),tools:b.z.array(b.z.object({name:b.z.string(),description:b.z.string(),input_schema:b.z.record(b.z.any()).optional()}).passthrough()).optional()}).passthrough(),k=b.z.object({type:b.z.literal("conversation.created"),event_id:b.z.string(),conversation:b.z.object({id:b.z.string().optional(),object:b.z.literal("realtime.conversation").optional()})}),P=b.z.object({type:b.z.literal("conversation.item.added"),event_id:b.z.string(),item:C,previous_item_id:b.z.string().nullable().optional()}),E=b.z.object({type:b.z.literal("conversation.item.done"),event_id:b.z.string(),item:C,previous_item_id:b.z.string().nullable().optional()}),j=b.z.object({type:b.z.literal("conversation.item.deleted"),event_id:b.z.string(),item_id:b.z.string()}),O=b.z.object({type:b.z.literal("conversation.item.input_audio_transcription.completed"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),transcript:b.z.string(),logprobs:b.z.array(b.z.any()).nullable().optional()}),R=b.z.object({type:b.z.literal("conversation.item.input_audio_transcription.delta"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number().optional(),delta:b.z.string().optional(),logprobs:b.z.array(b.z.any()).nullable().optional()}),N=b.z.object({type:b.z.literal("conversation.item.input_audio_transcription.failed"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),error:b.z.object({code:b.z.string().optional(),message:b.z.string().optional(),param:b.z.string().optional(),type:b.z.string().optional()})}),M=b.z.object({type:b.z.literal("conversation.item.retrieved"),event_id:b.z.string(),item:C}),D=b.z.object({type:b.z.literal("conversation.item.truncated"),event_id:b.z.string(),item_id:b.z.string(),audio_end_ms:b.z.number(),content_index:b.z.number()}),F=b.z.object({type:b.z.literal("conversation.item.create"),item:C,event_id:b.z.string().optional(),previous_item_id:b.z.string().nullable().optional()}),L=b.z.object({type:b.z.literal("conversation.item.delete"),item_id:b.z.string(),event_id:b.z.string().optional()}),$=b.z.object({type:b.z.literal("conversation.item.retrieve"),item_id:b.z.string(),event_id:b.z.string().optional()}),Z=b.z.object({type:b.z.literal("conversation.item.truncate"),item_id:b.z.string(),audio_end_ms:b.z.number(),content_index:b.z.number(),event_id:b.z.string().optional()}),q=b.z.object({type:b.z.literal("error"),event_id:b.z.string().optional(),error:b.z.any().optional()}),U=b.z.object({type:b.z.literal("input_audio_buffer.cleared"),event_id:b.z.string()}),J=b.z.object({type:b.z.literal("input_audio_buffer.append"),audio:b.z.string(),event_id:b.z.string().optional()}),G=b.z.object({type:b.z.literal("input_audio_buffer.clear"),event_id:b.z.string().optional()}),K=b.z.object({type:b.z.literal("input_audio_buffer.commit"),event_id:b.z.string().optional()}),B=b.z.object({type:b.z.literal("input_audio_buffer.committed"),event_id:b.z.string(),item_id:b.z.string(),previous_item_id:b.z.string().nullable().optional()}),W=b.z.object({type:b.z.literal("input_audio_buffer.speech_started"),event_id:b.z.string(),item_id:b.z.string(),audio_start_ms:b.z.number()}),H=b.z.object({type:b.z.literal("input_audio_buffer.speech_stopped"),event_id:b.z.string(),item_id:b.z.string(),audio_end_ms:b.z.number()}),V=b.z.object({type:b.z.literal("output_audio_buffer.started"),event_id:b.z.string()}).passthrough(),Q=b.z.object({type:b.z.literal("output_audio_buffer.stopped"),event_id:b.z.string()}).passthrough(),Y=b.z.object({type:b.z.literal("output_audio_buffer.cleared"),event_id:b.z.string()}),X=b.z.object({type:b.z.literal("rate_limits.updated"),event_id:b.z.string(),rate_limits:b.z.array(b.z.object({limit:b.z.number().optional(),name:b.z.enum(["requests","tokens"]).optional(),remaining:b.z.number().optional(),reset_seconds:b.z.number().optional()}))}),tt=b.z.object({type:b.z.literal("response.output_audio.delta"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),delta:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),et=b.z.object({type:b.z.literal("response.output_audio.done"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),output_index:b.z.number(),response_id:b.z.string()}),nt=b.z.object({type:b.z.literal("response.output_audio_transcript.delta"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),delta:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),rt=b.z.object({type:b.z.literal("response.output_audio_transcript.done"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),transcript:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),ot=b.z.object({type:b.z.literal("response.content_part.added"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),output_index:b.z.number(),response_id:b.z.string(),part:b.z.object({audio:b.z.string().optional(),text:b.z.string().optional(),transcript:b.z.string().optional(),type:b.z.enum(["text","audio"]).optional()})}),st=b.z.object({type:b.z.literal("response.content_part.done"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),output_index:b.z.number(),response_id:b.z.string(),part:b.z.object({audio:b.z.string().optional(),text:b.z.string().optional(),transcript:b.z.string().optional(),type:b.z.enum(["text","audio"]).optional()})}),at=b.z.object({type:b.z.literal("response.created"),event_id:b.z.string(),response:T}),it=b.z.object({type:b.z.literal("response.done"),event_id:b.z.string(),response:T}),ut=b.z.object({type:b.z.literal("response.function_call_arguments.delta"),event_id:b.z.string(),item_id:b.z.string(),call_id:b.z.string(),delta:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),ct=b.z.object({type:b.z.literal("response.function_call_arguments.done"),event_id:b.z.string(),item_id:b.z.string(),call_id:b.z.string(),arguments:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),lt=b.z.object({type:b.z.literal("response.output_item.added"),event_id:b.z.string(),item:C,output_index:b.z.number(),response_id:b.z.string()}),pt=b.z.object({type:b.z.literal("response.output_item.done"),event_id:b.z.string(),item:C,output_index:b.z.number(),response_id:b.z.string()}),dt=b.z.object({type:b.z.literal("response.output_text.delta"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),delta:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),mt=b.z.object({type:b.z.literal("response.output_text.done"),event_id:b.z.string(),item_id:b.z.string(),content_index:b.z.number(),text:b.z.string(),output_index:b.z.number(),response_id:b.z.string()}),gt=b.z.object({type:b.z.literal("session.created"),event_id:b.z.string(),session:b.z.any()}),ht=b.z.object({type:b.z.literal("session.updated"),event_id:b.z.string(),session:b.z.any()}),ft=b.z.object({type:b.z.literal("response.cancel"),event_id:b.z.string().optional(),response_id:b.z.string().optional()}),yt=b.z.object({type:b.z.literal("response.create"),event_id:b.z.string().optional(),response:b.z.any().optional()}),_t=b.z.object({type:b.z.literal("session.update"),event_id:b.z.string().optional(),session:b.z.any()}),vt=b.z.object({type:b.z.literal("mcp_list_tools.in_progress"),event_id:b.z.string().optional(),item_id:b.z.string().optional()}),bt=b.z.object({type:b.z.literal("mcp_list_tools.completed"),event_id:b.z.string().optional(),item_id:b.z.string().optional()}),wt=b.z.object({type:b.z.literal("response.mcp_call_arguments.delta"),event_id:b.z.string(),response_id:b.z.string(),item_id:b.z.string(),output_index:b.z.number(),delta:b.z.string(),obfuscation:b.z.string()}),zt=b.z.object({type:b.z.literal("response.mcp_call_arguments.done"),event_id:b.z.string(),response_id:b.z.string(),item_id:b.z.string(),output_index:b.z.number(),arguments:b.z.string()}),xt=b.z.object({type:b.z.literal("response.mcp_call.in_progress"),event_id:b.z.string(),output_index:b.z.number(),item_id:b.z.string()}),At=b.z.object({type:b.z.literal("response.mcp_call.completed"),event_id:b.z.string(),output_index:b.z.number(),item_id:b.z.string()}),It=b.z.object({type:b.z.literal("mcp_list_tools.failed"),event_id:b.z.string().optional(),item_id:b.z.string().optional()}),Tt=b.z.object({type:b.z.string(),event_id:b.z.string().optional().nullable()}).passthrough(),St=b.z.discriminatedUnion("type",[k,P,E,j,O,R,N,M,D,q,U,B,W,H,V,Q,Y,X,tt,et,nt,rt,ot,st,at,it,ut,ct,lt,pt,dt,mt,gt,ht,vt,bt,It,wt,zt,xt,At]);function Ct(t){const e=JSON.parse(t.data.toString()),n=St.safeParse(e);if(!n.success){const t=Tt.safeParse(e);return t.success?{data:t.data,isGeneric:!0}:{data:null,isGeneric:!0}}return{data:n.data,isGeneric:!1}}b.z.discriminatedUnion("type",[F,L,$,Z,J,G,K,ft,yt,_t]);const kt="gpt-realtime",Pt={outputModalities:["audio"],audio:{input:{format:{type:"audio/pcm",rate:24e3},transcription:{model:"gpt-4o-mini-transcribe"},turnDetection:{type:"semantic_vad"},noiseReduction:null},output:{format:{type:"audio/pcm",rate:24e3},speed:1}}};class Et extends f.Ko{#n;#r;#o=null;#s=null;eventEmitter=new o.j3;constructor(t={}){super(),this.#n=t.model??kt,this.#r=t.apiKey}get currentModel(){return this.#n}set currentModel(t){this.#n=t}get _rawSessionConfig(){return this.#s??null}async _getApiKey(t){const e=t.apiKey??this.#r;return"function"==typeof e?await e():e}_onMessage(t){const{data:e,isGeneric:n}=Ct(t);if(null!==e&&(this.emit("*",e),!n))if("error"===e.type?this.emit("error",{type:"error",error:e}):this.emit(e.type,e),"response.created"!==e.type){if("session.updated"===e.type&&(this.#s=e.session),"response.done"===e.type){const t=it.safeParse(e);if(!t.success)return void I.error("Error parsing response done event",t.error);const n=t.data.response.usage?.input_tokens??0,r=t.data.response.usage?.output_tokens??0,s=n+r,a=new o._U({inputTokens:n,inputTokensDetails:t.data.response.usage?.input_tokens_details??{},outputTokens:r,outputTokensDetails:t.data.response.usage?.output_tokens_details??{},totalTokens:s});return this.emit("usage_update",a),void this.emit("turn_done",{type:"response_done",response:{id:t.data.response.id??"",output:t.data.response.output??[],usage:{inputTokens:n,inputTokensDetails:t.data.response.usage?.input_tokens_details??{},outputTokens:r,outputTokensDetails:t.data.response.usage?.output_tokens_details??{},totalTokens:s}}})}if("response.output_audio.done"!==e.type)if("conversation.item.deleted"!==e.type)if("conversation.item.input_audio_transcription.completed"!==e.type&&"conversation.item.truncated"!==e.type)if("conversation.item.input_audio_transcription.delta"!==e.type&&"response.output_text.delta"!==e.type&&"response.output_audio_transcript.delta"!==e.type&&"response.function_call_arguments.delta"!==e.type){if("conversation.item.added"===e.type||"conversation.item.done"===e.type||"conversation.item.retrieved"===e.type){if("mcp_list_tools"===e.item.type&&"conversation.item.done"===e.type){const t=e.item.server_label??"",n=e.item.tools??[];try{this.emit("mcp_tools_listed",{serverLabel:t,tools:n})}catch(t){I.error("Error emitting mcp_tools_listed",t,e.item)}return}if("message"===e.item.type){const t="conversation.item.added"===e.type||"conversation.item.done"===e.type?e.previous_item_id:null,n=w.parse({itemId:e.item.id,previousItemId:t,type:e.item.type,role:e.item.role,content:e.item.content,status:e.item.status});return void this.emit("item_update",n)}if("mcp_approval_request"===e.item.type&&"conversation.item.done"===e.type){const t=e.item,n=A.parse({itemId:t.id,type:t.type,serverLabel:t.server_label,name:t.name,arguments:JSON.parse(t.arguments||"{}"),approved:t.approved});return this.emit("item_update",n),void this.emit("mcp_approval_request",n)}if("mcp_tool_call"===e.item.type||"mcp_call"===e.item.type){const t="conversation.item.done"===e.type?"completed":"in_progress",n=x.parse({itemId:e.item.id,type:e.item.type,status:t,arguments:e.item.arguments,name:e.item.name,output:e.item.output});return this.emit("item_update",n),void("conversation.item.done"===e.type&&this.emit("mcp_tool_call_completed",n))}}if("response.mcp_call.in_progress"===e.type){const t=e;return void this.sendEvent({type:"conversation.item.retrieve",item_id:t.item_id})}if("mcp_list_tools.in_progress"===e.type){const t=e;return void(t.item_id&&this.sendEvent({type:"conversation.item.retrieve",item_id:t.item_id}))}if("response.output_item.done"===e.type||"response.output_item.added"===e.type){const t=e.item;if("function_call"===t.type&&"completed"===t.status){const e=z.parse({itemId:t.id,type:t.type,status:"in_progress",arguments:t.arguments,name:t.name,output:null});return this.emit("item_update",e),void this.emit("function_call",{id:t.id,type:"function_call",callId:t.call_id??"",arguments:t.arguments??"",name:t.name??""})}if("mcp_tool_call"===t.type||"mcp_call"===t.type){const n=x.parse({itemId:t.id,type:t.type,status:"response.output_item.done"===e.type?"completed":"in_progress",arguments:t.arguments,name:t.name,output:t.output});return void this.emit("item_update",n)}if("message"===t.type){const n=w.parse({itemId:e.item.id,type:e.item.type,role:e.item.role,content:e.item.content,status:"response.output_item.done"===e.type?t.status??"completed":t.status??"in_progress"});return void this.emit("item_update",n)}}}else"response.output_audio_transcript.delta"===e.type&&this.emit("audio_transcript_delta",{type:"transcript_delta",delta:e.delta,itemId:e.item_id,responseId:e.response_id});else this.sendEvent({type:"conversation.item.retrieve",item_id:e.item_id});else this.emit("item_deleted",{itemId:e.item_id});else this.emit("audio_done")}else this.emit("turn_started",{type:"response_started",providerData:{...e}})}_onError(t){this.emit("error",{type:"error",error:t})}_onOpen(){this.emit("connected")}_onClose(){this.emit("disconnected")}sendMessage(t,e,{triggerResponse:n=!0}={}){const r="string"==typeof t?[{type:"input_text",text:t}]:t.content.map(t=>"input_image"===t.type?{type:"input_image",image_url:t.image,...t.providerData??{}}:t);this.sendEvent({type:"conversation.item.create",item:{type:"message",role:"user",content:r},...e}),n&&this.sendEvent({type:"response.create"})}addImage(t,{triggerResponse:e=!0}={}){this.sendMessage({type:"message",role:"user",content:[{type:"input_image",image:t}]},{},{triggerResponse:e})}_getMergedSessionConfig(t){const e=function(t){if(!function(t){return _("modalities",t)||_("inputAudioFormat",t)||_("outputAudioFormat",t)||_("inputAudioTranscription",t)||_("turnDetection",t)||_("inputAudioNoiseReduction",t)||_("speed",t)}(t)){const e=t.audio?.input?{format:v(t.audio.input.format),noiseReduction:t.audio.input.noiseReduction??null,transcription:t.audio.input.transcription,turnDetection:t.audio.input.turnDetection}:void 0,n=t.audio?.output?.voice??t.voice,r=t.audio?.output||void 0!==n?{format:v(t.audio?.output?.format),voice:n,speed:t.audio?.output?.speed}:void 0;return{model:t.model,instructions:t.instructions,toolChoice:t.toolChoice,tools:t.tools,tracing:t.tracing,providerData:t.providerData,prompt:t.prompt,outputModalities:t.outputModalities,audio:e||r?{input:e,output:r}:void 0}}return{model:t.model,instructions:t.instructions,toolChoice:t.toolChoice,tools:t.tools,tracing:t.tracing,providerData:t.providerData,prompt:t.prompt,outputModalities:t.modalities,audio:{input:{format:v(t.inputAudioFormat),noiseReduction:t.inputAudioNoiseReduction??null,transcription:t.inputAudioTranscription,turnDetection:t.turnDetection},output:{format:v(t.outputAudioFormat),voice:t.voice,speed:t.speed}}}}(t),n={type:"realtime",instructions:e.instructions,model:e.model??this.#n,output_modalities:e.outputModalities??Pt.outputModalities,audio:{input:{format:e.audio?.input?.format??Pt.audio?.input?.format,noise_reduction:e.audio?.input?.noiseReduction??Pt.audio?.input?.noiseReduction,transcription:e.audio?.input?.transcription??Pt.audio?.input?.transcription,turn_detection:Et.buildTurnDetectionConfig(e.audio?.input?.turnDetection)??Pt.audio?.input?.turnDetection},output:{format:e.audio?.output?.format??Pt.audio?.output?.format,voice:e.audio?.output?.voice??Pt.audio?.output?.voice,speed:e.audio?.output?.speed??Pt.audio?.output?.speed}},tool_choice:e.toolChoice??Pt.toolChoice,...e.providerData??{}};return e.prompt&&(n.prompt={id:e.prompt.promptId,version:e.prompt.version,variables:e.prompt.variables}),e.tools&&e.tools.length>0&&(n.tools=e.tools.map(t=>({...t,strict:void 0}))),n}static buildTurnDetectionConfig(t){if(void 0===t)return;const{type:e,createResponse:n,create_response:r,eagerness:o,interruptResponse:s,interrupt_response:a,prefixPaddingMs:i,prefix_padding_ms:u,silenceDurationMs:c,silence_duration_ms:l,threshold:p,idleTimeoutMs:d,idle_timeout_ms:m,...g}=t,h={type:e,create_response:n||r,eagerness:o,interrupt_response:s||a,prefix_padding_ms:i||u,silence_duration_ms:c||l,idle_timeout_ms:d||m,threshold:p,...g};return Object.keys(h).forEach(t=>{void 0===h[t]&&delete h[t]}),Object.keys(h).length>0?h:void 0}set _tracingConfig(t){this.#o=t}_updateTracingConfig(t){if(void 0===this.#o&&(this.#o=null),"auto"!==t){if(null===this.#o||"string"==typeof this.#o||"string"==typeof t)return null===t?(I.debug("Disabling tracing for this session. It cannot be turned on for this session from this point on."),void this.sendEvent({type:"session.update",session:{type:"realtime",tracing:null}})):void(null!==this.#o&&"string"!=typeof this.#o?t?.group_id===this.#o?.group_id&&t?.metadata===this.#o?.metadata&&t?.workflow_name===this.#o?.workflow_name?this.sendEvent({type:"session.update",session:{type:"realtime",tracing:t}}):I.warn("Mismatch in tracing config. Ignoring the new tracing config. This likely happens when you already set a tracing config on session creation. Current tracing config: %s, new tracing config: %s",JSON.stringify(this.#o),JSON.stringify(t)):this.sendEvent({type:"session.update",session:{type:"realtime",tracing:t}}));I.warn("Tracing config is already set, skipping setting it again. This likely happens when you already set a tracing config on session creation.")}else this.sendEvent({type:"session.update",session:{type:"realtime",tracing:"auto"}})}updateSessionConfig(t){const e=this._getMergedSessionConfig(t);this.sendEvent({type:"session.update",session:e})}sendFunctionCallOutput(t,e,n=!0){this.sendEvent({type:"conversation.item.create",item:{type:"function_call_output",output:e,call_id:t.callId}});try{const n=z.parse({itemId:t.id,previousItemId:t.previousItemId,type:"function_call",status:"completed",arguments:t.arguments,name:t.name,output:e});this.emit("item_update",n)}catch(e){I.error("Error parsing tool call item",e,t)}n&&this.sendEvent({type:"response.create"})}sendAudio(t,{commit:e=!1}={}){this.sendEvent({type:"input_audio_buffer.append",audio:a(t)}),e&&this.sendEvent({type:"input_audio_buffer.commit"})}resetHistory(t,e){const{removals:n,additions:r,updates:o}=function(t,e){return{removals:t.filter(t=>!e.some(e=>e.itemId===t.itemId)),additions:e.filter(e=>!t.some(t=>t.itemId===e.itemId)),updates:e.filter(e=>t.some(t=>t.itemId===e.itemId&&JSON.stringify(t)!==JSON.stringify(e)))}}(t,e),s=new Set(n.map(t=>t.itemId));for(const t of o)s.add(t.itemId);if(s.size>0)for(const t of s)this.sendEvent({type:"conversation.item.delete",item_id:t});const a=[...r,...o];for(const t of a)if("message"===t.type){const e={type:"message",role:t.role,content:t.content,id:t.itemId};"system"!==t.role&&t.status&&(e.status=t.status),this.sendEvent({type:"conversation.item.create",item:e})}else"function_call"===t.type&&I.warn("Function calls cannot be manually added or updated at the moment. Ignoring.")}sendMcpResponse(t,e){this.sendEvent({type:"conversation.item.create",previous_item_id:t.itemId,item:{type:"mcp_approval_response",approval_request_id:t.itemId,approve:e}})}}class jt extends Et{options;#a;#i={status:"disconnected",peerConnection:void 0,dataChannel:void 0,callId:void 0};#u;#c=!1;#l=!1;constructor(t={}){if("undefined"==typeof RTCPeerConnection)throw new Error("WebRTC is not supported in this environment");super(t),this.options=t,this.#a=t.baseUrl??"https://api.openai.com/v1/realtime/calls",this.#u=t.useInsecureApiKey??!1}get callId(){return this.#i.callId}get status(){return this.#i.status}get connectionState(){return this.#i}get muted(){return this.#l}async connect(t){if("connected"===this.#i.status)return;"connecting"===this.#i.status&&I.warn("Realtime connection already in progress. Please await original promise");const e=t.model??this.currentModel;this.currentModel=e;const n=t.url??this.#a,r=await this._getApiKey(t),s="string"==typeof r&&r.startsWith("ek_");if((0,h.Iz)()&&!this.#u&&!s)throw new o.yo("Using the WebRTC connection in a browser environment requires an ephemeral client key. If you need to use a regular API key, use the WebSocket transport or set the `useInsecureApiKey` option to true.");return new Promise(async(e,o)=>{try{const s={...t.initialSessionConfig||{},model:this.currentModel},a=new URL(n);let i=new RTCPeerConnection;const u=i.createDataChannel("oai-events");let c;this.#i={status:"connecting",peerConnection:i,dataChannel:u,callId:c},this.emit("connection_change",this.#i.status),u.addEventListener("open",()=>{this.#i={status:"connected",peerConnection:i,dataChannel:u,callId:c},this.updateSessionConfig(s),this.emit("connection_change",this.#i.status),this._onOpen(),e()}),u.addEventListener("error",t=>{this.close(),this._onError(t),o(t)}),u.addEventListener("message",t=>{this._onMessage(t);const{data:e,isGeneric:n}=Ct(t);e&&!n&&("response.created"===e.type?this.#c=!0:"response.done"===e.type&&(this.#c=!1),"session.created"===e.type&&(this._tracingConfig=e.session.tracing,this._updateTracingConfig(s.tracing??"auto")))});const p=this.options.audioElement??document.createElement("audio");p.autoplay=!0,i.ontrack=t=>{p.srcObject=t.streams[0]};const d=this.options.mediaStream??await navigator.mediaDevices.getUserMedia({audio:!0});i.addTrack(d.getAudioTracks()[0]),this.options.changePeerConnection&&(i=await this.options.changePeerConnection(i),this.#i={...this.#i,peerConnection:i});const m=await i.createOffer();if(await i.setLocalDescription(m),!m.sdp)throw new Error("Failed to create offer");const g=await fetch(a,{method:"POST",body:m.sdp,headers:{"Content-Type":"application/sdp",Authorization:`Bearer ${r}`,"X-OpenAI-Agents-SDK":l["X-OpenAI-Agents-SDK"]}});c=g.headers?.get("Location")?.split("/").pop(),this.#i={...this.#i,callId:c};const h={type:"answer",sdp:await g.text()};await i.setRemoteDescription(h)}catch(t){this.close(),this._onError(t),o(t)}})}sendEvent(t){if(!this.#i.dataChannel||"open"!==this.#i.dataChannel.readyState)throw new Error("WebRTC data channel is not connected. Make sure you call `connect()` before sending events.");this.#i.dataChannel.send(JSON.stringify(t))}mute(t){this.#l=t,this.#i.peerConnection&&this.#i.peerConnection.getSenders().forEach(e=>{e.track&&(e.track.enabled=!t)})}close(){if(this.#i.dataChannel&&this.#i.dataChannel.close(),this.#i.peerConnection){const t=this.#i.peerConnection;t.getSenders().forEach(t=>{t.track?.stop()}),t.close()}"disconnected"!==this.#i.status&&(this.#i={status:"disconnected",peerConnection:void 0,dataChannel:void 0,callId:void 0},this.emit("connection_change",this.#i.status),this._onClose())}interrupt(){this.#c&&(this.sendEvent({type:"response.cancel"}),this.#c=!1),this.sendEvent({type:"output_audio_buffer.clear"})}}const Ot=globalThis.WebSocket;class Rt extends Et{#r;#a;#i={status:"disconnected",websocket:void 0};#u;#p;#d;_firstAudioTimestamp;_audioLengthMs=0;#c=!1;#m;#g;constructor(t={}){super(t),this.#a=t.url,this.#u=t.useInsecureApiKey??!1,this.#m=t.createWebSocket,this.#g=t.skipOpenEventListeners??!1}getCommonRequestHeaders(){return l}get status(){return this.#i.status}get connectionState(){return this.#i}get muted(){return null}get currentItemId(){return this.#p}_onAudio(t){this.emit("audio",t)}async#h(t,e,n){if(this.#i.websocket)return void t();if(!this.#r)throw new o.yo("API key is not set. Please call `connect()` with an API key first.");if(!this.#r.startsWith("ek_")&&!this.#u)throw new o.yo("Using the WebSocket connection in a browser environment requires an ephemeral client key. If you have to use a regular API key, set the `useInsecureApiKey` option to true.");let r=null;if(this.#m)r=await this.#m({url:this.#a,apiKey:this.#r});else{const t=["realtime","openai-insecure-api-key."+this.#r,p];r=new Ot(this.#a,t)}this.#i={status:"connecting",websocket:r},this.emit("connection_change",this.#i.status);const a=()=>{this.#i={status:"connected",websocket:r},this.emit("connection_change",this.#i.status),this._onOpen(),t()};!0===this.#g?a():r.addEventListener("open",a),r.addEventListener("error",t=>{this._onError(t),this.#i={status:"disconnected",websocket:void 0},this.emit("connection_change",this.#i.status),e(t)}),r.addEventListener("message",t=>{this._onMessage(t);const{data:e,isGeneric:r}=Ct(t);if(e&&!r)if("response.output_audio.delta"===e.type){this.#d=e.content_index,this.#p=e.item_id,void 0===this._firstAudioTimestamp&&(this._firstAudioTimestamp=Date.now(),this._audioLengthMs=0);const t=s(e.delta),n=this._rawSessionConfig?.audio?.output?.format;if(n&&"object"==typeof n){const e=n.type;if("audio/pcmu"===e||"audio/pcma"===e)this._audioLengthMs+=t.byteLength/8;else if("audio/pcm"===e){const e=n.rate??24e3;this._audioLengthMs+=t.byteLength/2/e*1e3}else this._audioLengthMs+=t.byteLength/24/2}else"string"==typeof n&&n.startsWith("g711_")?this._audioLengthMs+=t.byteLength/8:this._audioLengthMs+=t.byteLength/24/2;const r={type:"audio",data:t,responseId:e.response_id};this._onAudio(r)}else if("input_audio_buffer.speech_started"===e.type){const t=this._rawSessionConfig?.audio?.input?.turn_detection?.interrupt_response??!1;this.interrupt(!t)}else"response.created"===e.type?this.#c=!0:"response.done"===e.type?this.#c=!1:"session.created"===e.type&&(this._tracingConfig=e.session.tracing,this._updateTracingConfig(n.tracing??"auto"))}),r.addEventListener("close",()=>{this.#i={status:"disconnected",websocket:void 0},this.emit("connection_change",this.#i.status),this._onClose()})}async connect(t){const e=t.model??this.currentModel;this.currentModel=e,this.#r=await this._getApiKey(t);const n=t.url??this.#a??`wss://api.openai.com/v1/realtime?model=${this.currentModel}`;this.#a=n;const r={...t.initialSessionConfig||{},model:this.currentModel};await new Promise((t,e)=>{this.#h(t,e,r).catch(e)}),await this.updateSessionConfig(r)}sendEvent(t){if(!this.#i.websocket)throw new Error("WebSocket is not connected. Make sure you call `connect()` before sending events.");this.#i.websocket.send(JSON.stringify(t))}close(){this.#i.websocket?.close(),this.#p=void 0,this._firstAudioTimestamp=void 0,this._audioLengthMs=0,this.#d=void 0}mute(t){throw new Error("Mute is not supported for the WebSocket transport. You have to mute the audio input yourself.")}sendAudio(t,e={}){"connected"===this.#i.status&&super.sendAudio(t,e)}_cancelResponse(){this.#c&&(this.sendEvent({type:"response.cancel"}),this.#c=!1)}_interrupt(t,e=!0){if(t<0)return;e&&this._cancelResponse();const n=this._audioLengthMs??Number.POSITIVE_INFINITY,r=Math.max(0,Math.floor(Math.min(t,n)));this.emit("audio_interrupted"),this.sendEvent({type:"conversation.item.truncate",item_id:this.#p,content_index:this.#d,audio_end_ms:r})}interrupt(t=!0){if(!this.#p||"number"!=typeof this._firstAudioTimestamp)return;const e=Date.now()-this._firstAudioTimestamp;e>=0&&this._interrupt(e,t),this.#p=void 0,this._firstAudioTimestamp=void 0,this._audioLengthMs=0,this.#d=void 0}}const Nt=Symbol("backgroundResult");function Mt(t){return{[Nt]:!0,content:t}}function Dt(t){return"object"==typeof t&&null!==t&&Nt in t}function Ft(t){return"function"===t.type||"hosted_tool"===t.type&&"hosted_mcp"===t.name}function Lt(t){if("function"===t.type)return t;if("hosted_tool"===t.type&&"hosted_mcp"===t.name){const e=t.providerData.server_url&&t.providerData.server_url.length>0?t.providerData.server_url:void 0;return{type:"mcp",server_label:t.providerData.server_label,server_url:e,headers:t.providerData.headers,allowed_tools:t.providerData.allowed_tools,require_approval:t.providerData.require_approval}}throw new o.yo(`Invalid tool type: ${t}`)}class $t extends h.j3{initialAgent;options;#f;#y;#_;#v;#b=[];#w;#z={};#x=[];#A;#I={};#T=!1;#S=new Map;#C=[];#k=function(){return JSON.parse(JSON.stringify(Pt))}();#P=!0;constructor(t,e={}){super(),this.initialAgent=t,this.options=e,void 0===e.transport&&"undefined"!=typeof window&&void 0!==window.RTCPeerConnection||"webrtc"===e.transport?this.#f=new jt:"websocket"===e.transport||void 0===e.transport?this.#f=new Rt:this.#f=e.transport,this.#y=t,this.#v=new o.ZI({...e.context??{},history:this.#x}),this.#b=(e.outputGuardrails??[]).map(y),this.#w={debounceTextLength:(e.outputGuardrailSettings??{}).debounceTextLength??100},this.#A=e.historyStoreAudio??!1,this.#P=e.automaticallyTriggerResponseForMcpToolCalls??!0}get transport(){return this.#f}get currentAgent(){return this.#y}get usage(){return this.#v.usage}get context(){return this.#v}get muted(){return this.#f.muted}get history(){return this.#x}get availableMcpTools(){return this.#C}async#E(t){this.#y=t;const e=await this.#y.getEnabledHandoffs(this.#v),n=e.map(t=>t.getHandoffAsFunctionTool()),r=(await this.#y.getAllTools(this.#v)).filter(Ft).map(Lt),o=void 0!==this.#y.tools||void 0!==this.#y.mcpServers,s=e.length>0;this.#_=o||s?[...r,...n]:void 0,this.#j()}async#O(t={}){const e=await this.#y.getSystemPrompt(this.#v),n=this.options.tracingDisabled?null:this.options.workflowName?{workflow_name:this.options.workflowName}:"auto";null!==n&&"auto"!==n?(this.options.groupId&&(n.group_id=this.options.groupId),this.options.traceMetadata&&(n.metadata=this.options.traceMetadata)):(this.options.groupId||this.options.traceMetadata)&&I.warn("In order to set traceMetadata or a groupId you need to specify a workflowName.");const r={...{...this.#k??{},...this.options.config??{},...t??{}},instructions:e,voice:this.#y.voice,model:this.options.model,tools:this.#_,tracing:n,prompt:"function"==typeof this.#y.prompt?await this.#y.prompt(this.#v,this.#y):this.#y.prompt};return this.#k=r,r}async updateAgent(t){return this.#y.emit("agent_handoff",this.#v,t),this.emit("agent_handoff",this.#v,this.#y,t),await this.#E(t),await this.#f.updateSessionConfig(await this.#O()),t}async#R(t,e){const n=await e.onInvokeHandoff(this.#v,t.arguments);this.#y.emit("agent_handoff",this.#v,n),this.emit("agent_handoff",this.#v,this.#y,n),await this.#E(n),await this.#f.updateSessionConfig(await this.#O());const r=(0,o.Nx)(n);return this.#f.sendFunctionCallOutput(t,r,!0),n}async#N(t,e){this.#v.context.history=JSON.parse(JSON.stringify(this.#x));let n=t.arguments;if(e.parameters&&(n=(0,f.f3)(e.parameters)?e.parameters.parse(n):JSON.parse(n)),await e.needsApproval(this.#v,n,t.callId)){const n=this.context.isToolApproved({toolName:e.name,callId:t.callId});if(!1===n){this.emit("agent_tool_start",this.#v,this.#y,e,{toolCall:t}),this.#y.emit("agent_tool_start",this.#v,e,{toolCall:t});const n="Tool execution was not approved.";return this.#f.sendFunctionCallOutput(t,n,!0),this.emit("agent_tool_end",this.#v,this.#y,e,n,{toolCall:t}),void this.#y.emit("agent_tool_end",this.#v,e,n,{toolCall:t})}if(void 0===n)return void this.emit("tool_approval_requested",this.#v,this.#y,{type:"function_approval",tool:e,approvalItem:new o.A9(t,this.#y)})}this.emit("agent_tool_start",this.#v,this.#y,e,{toolCall:t}),this.#y.emit("agent_tool_start",this.#v,e,{toolCall:t}),this.#v.context.history=JSON.parse(JSON.stringify(this.#x));const r=await e.invoke(this.#v,t.arguments,{toolCall:t});let s;Dt(r)?(s=(0,f.ID)(r.content),this.#f.sendFunctionCallOutput(t,s,!1)):(s=(0,f.ID)(r),this.#f.sendFunctionCallOutput(t,s,!0)),this.emit("agent_tool_end",this.#v,this.#y,e,s,{toolCall:t}),this.#y.emit("agent_tool_end",this.#v,e,s,{toolCall:t})}async#M(t){const e=await this.#y.getEnabledHandoffs(this.#v),n=new Map(e.map(t=>[t.toolName,t])),r=await this.#y.getAllTools(this.#v),s=new Map(r.map(t=>[t.name,t])),a=n.get(t.name);if(a)await this.#R(t,a);else{const e=s.get(t.name);if(!e||"function"!==e.type)throw new o.af(`Tool ${t.name} not found`);await this.#N(t,e)}}async#D(t,e,n){if(0===this.#b.length)return;const r={agent:this.#y,agentOutput:t,context:this.#v},s=(await Promise.all(this.#b.map(t=>t.run(r)))).find(t=>t.output.tripwireTriggered);if(s){if(this.#I[e])return;this.#I[e]=!0;const t=new o.K6(`Output guardrail triggered: ${JSON.stringify(s.output.outputInfo)}`,s);this.emit("guardrail_tripped",this.#v,this.#y,t,{itemId:n}),this.interrupt();const r=`\n⚠️ Your last answer was blocked. \nFailed Guardrail Reason: ${(a=s).guardrail.policyHint}. \nFailure Details: ${JSON.stringify(a.output.outputInfo??{})}. \nPlease respond again following policy. Apologize for not being able to answer the question (while avoiding the specific reason) and divert discussion back to an approved topic immediately and not invite more discussion.\n`.trim();return void this.sendMessage(r)}var a}#F(){this.#f.on("*",t=>{if(this.emit("transport_event",t),"conversation.item.input_audio_transcription.completed"===t.type)try{const e=t;this.#x=c(this.#x,e,this.#A),this.#v.context.history=this.#x,this.emit("history_updated",this.#x)}catch(t){this.emit("error",{type:"error",error:t})}}),this.#f.on("mcp_tools_listed",({serverLabel:t,tools:e})=>{try{this.#S.set(t,e??[]),this.#j()}catch(t){this.emit("error",{type:"error",error:t})}}),this.#f.on("audio",t=>{this.#T||(this.#T=!0,this.emit("audio_start",this.#v,this.#y)),this.emit("audio",t)}),this.#f.on("turn_started",()=>{this.#T=!1,this.emit("agent_start",this.#v,this.#y),this.#y.emit("agent_start",this.#v,this.#y)}),this.#f.on("turn_done",t=>{const e=t.response.output[t.response.output.length-1],n=i(e)??"",r=e?.id??"";this.emit("agent_end",this.#v,this.#y,n),this.#y.emit("agent_end",this.#v,n),this.#D(n,t.response.id,r)}),this.#f.on("audio_done",()=>{this.#T&&(this.#T=!1),this.emit("audio_stopped",this.#v,this.#y)});let t,e=0;this.#f.on("audio_transcript_delta",n=>{try{const r=n.delta,o=n.itemId,s=n.responseId;t!==o&&(t=o,e=0);const a=(this.#z[o]??"")+r;if(this.#z[o]=a,this.#w.debounceTextLength<0)return;const i=Math.floor(a.length/this.#w.debounceTextLength);i>e&&(e=i,this.#D(a,s,o))}catch(t){this.emit("error",{type:"error",error:t})}}),this.#f.on("item_update",t=>{try{const e=!this.#x.some(e=>e.itemId===t.itemId);if(this.#x=c(this.#x,t,this.#A),this.#v.context.history=this.#x,e){const e=this.#x.find(e=>e.itemId===t.itemId);e&&this.emit("history_added",e)}this.emit("history_updated",this.#x)}catch(t){this.emit("error",{type:"error",error:t})}}),this.#f.on("item_deleted",t=>{try{this.#x=this.#x.filter(e=>e.itemId!==t.itemId),this.#v.context.history=this.#x,this.emit("history_updated",this.#x)}catch(t){this.emit("error",{type:"error",error:t})}}),this.#f.on("function_call",async t=>{try{await this.#M(t)}catch(t){I.error("Error handling function call",t),this.emit("error",{type:"error",error:t})}}),this.#f.on("usage_update",t=>{this.#v.usage.add(t)}),this.#f.on("audio_interrupted",()=>{this.#T&&(this.#T=!1),this.emit("audio_interrupted",this.#v,this.#y)}),this.#f.on("error",t=>{this.emit("error",t)}),this.#f.on("mcp_tool_call_completed",t=>{this.emit("mcp_tool_call_completed",this.#v,this.#y,t),this.#P&&this.#f.sendEvent({type:"response.create"})}),this.#f.on("mcp_approval_request",t=>{this.emit("tool_approval_requested",this.#v,this.#y,{type:"mcp_approval_request",approvalItem:d(this.#y,t)})})}#j(){const t=this.#_?.filter(t=>"mcp"===t.type),e=t=>{const e=t.allowed_tools;if(e)return Array.isArray(e)?e:e&&Array.isArray(e.tool_names)?e.tool_names:void 0},n=new Map;for(const r of t){const t=this.#S.get(r.server_label)??[],o=e(r);for(const e of t)o&&!o.includes(e.name)||n.has(e.name)||n.set(e.name,e)}const r=Array.from(n.values()),o=this.#C;(o.length!==r.length||JSON.stringify(o.map(t=>t.name).sort())!==JSON.stringify(r.map(t=>t.name).sort()))&&(this.#C=r,this.emit("mcp_tools_changed",this.#C))}async connect(t){await this.#E(this.initialAgent),this.#F(),await this.#f.connect({apiKey:t.apiKey??this.options.apiKey,model:this.options.model,url:t.url,initialSessionConfig:await this.#O(this.options.config)}),this.#x=[],this.emit("history_updated",this.#x)}updateHistory(t){let e;e="function"==typeof t?t(this.#x):t,this.#f.resetHistory(this.#x,e)}sendMessage(t,e={}){this.#f.sendMessage(t,e)}addImage(t,{triggerResponse:e=!0}={}){this.#f.addImage(t,{triggerResponse:e})}mute(t){this.#f.mute(t)}close(){this.#I={},this.#f.close()}sendAudio(t,e={}){this.#f.sendAudio(t,e)}interrupt(){this.#f.interrupt()}async approve(t,e={alwaysApprove:!1}){this.#v.approveTool(t,e);const n=this.#y.tools.find(e=>e.name===t.rawItem.name);if(n&&"function"===n.type&&"function_call"===t.rawItem.type)await this.#N(t.rawItem,n);else{if("hosted_tool_call"!==t.rawItem.type)throw new o.af(`Tool ${t.rawItem.name} not found`);{e.alwaysApprove&&I.warn("Always approving MCP tools is not supported. Use the allowed tools configuration instead.");const n=m(t);this.#f.sendMcpResponse(n,!0)}}}async reject(t,e={alwaysReject:!1}){this.#v.rejectTool(t,e);const n=this.#y.tools.find(e=>e.name===t.rawItem.name);if(n&&"function"===n.type&&"function_call"===t.rawItem.type)await this.#N(t.rawItem,n);else{if("hosted_tool_call"!==t.rawItem.type)throw new o.af(`Tool ${t.rawItem.name} not found`);{e.alwaysReject&&I.warn("Always rejecting MCP tools is not supported. Use the allowed tools configuration instead.");const n=m(t);this.#f.sendMcpResponse(n,!1)}}}}const Zt={base64ToArrayBuffer:s,arrayBufferToBase64:a,getLastTextFromAudioOutputMessage:i}},921:(t,e,n)=>{"use strict";function r(t){return"object"==typeof t&&null!==t&&("name"in t&&"AbortError"===t.name||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}n.d(e,{r:()=>o,z:()=>r});const o=t=>{if(t instanceof Error)return t;if("object"==typeof t&&null!==t){try{if("[object Error]"===Object.prototype.toString.call(t)){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}},2588:(t,e,n)=>{"use strict";n.d(e,{Is:()=>g,LG:()=>s,Ll:()=>p,OE:()=>h,PO:()=>f,RA:()=>v,cH:()=>a,fK:()=>m,k5:()=>y,m_:()=>d,pf:()=>_,qA:()=>u,v3:()=>l,v7:()=>c,vc:()=>o,xX:()=>i});var r=n(921);class o extends Error{}class s extends o{constructor(t,e,n,r){super(`${s.makeMessage(t,e,n)}`),this.status=t,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=e;const o=e;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(t,e,n){const r=e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):e?JSON.stringify(e):n;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,e,n,o){if(!t||!o)return new i({message:n,cause:(0,r.r)(e)});const a=e?.error;return 400===t?new c(t,a,n,o):401===t?new l(t,a,n,o):403===t?new p(t,a,n,o):404===t?new d(t,a,n,o):409===t?new m(t,a,n,o):422===t?new g(t,a,n,o):429===t?new h(t,a,n,o):t>=500?new f(t,a,n,o):new s(t,a,n,o)}}class a extends s{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class i extends s{constructor({message:t,cause:e}){super(void 0,void 0,t||"Connection error.",void 0),e&&(this.cause=e)}}class u extends i{constructor({message:t}={}){super({message:t??"Request timed out."})}}class c extends s{}class l extends s{}class p extends s{}class d extends s{}class m extends s{}class g extends s{}class h extends s{}class f extends s{}class y extends o{constructor(){super("Could not parse response content as the length limit was reached")}}class _ extends o{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class v extends Error{constructor(t){super(t)}}},2618:(t,e,n)=>{"use strict";n.d(e,{A:()=>g,h:()=>p});var r=n(26),o=n(5786),s=n(3004),a=n(7755),i=n(7780),u=n(4075),c=n(7020),l=n(5606);class p{#L;#$;constructor(){this.#L=new a.qQ,this.#$=o.zR.disabled,this.#Z()}registerProcessor(t){this.#L.addTraceProcessor(t)}setProcessors(t){this.#L.setProcessors(t)}getCurrentTrace(){return(0,r.j3)()}getCurrentSpan(){return(0,r.YP)()}setDisabled(t){this.#$=t}startExportLoop(){this.#L.start()}createTrace(t){if(this.#$)return s.Ay.debug("Tracing is disabled, Not creating trace %o",t),new u.i;const e=t.traceId??(0,c.el)(),n=t.name??"Agent workflow";return s.Ay.debug("Creating trace %s with name %s",e,n),new u.C({...t,name:n,traceId:e},this.#L)}createSpan(t,e){if(this.#$||t.disabled)return s.Ay.debug("Tracing is disabled, Not creating span %o",t),new i.f(t.data,this.#L);let n,o;if(e){if(e instanceof u.C){if(e instanceof u.i)return s.Ay.debug("Parent trace is no-op, returning NoopSpan"),new i.f(t.data,this.#L);o=e.traceId}else if(e instanceof i.L){if(e instanceof i.f)return s.Ay.debug("Parent span is no-op, returning NoopSpan"),new i.f(t.data,this.#L);n=e.spanId,o=e.traceId}}else{const e=(0,r.j3)(),a=(0,r.YP)();if(!e)return s.Ay.error("No active trace. Make sure to start a trace with `withTrace()` first. Returning NoopSpan."),new i.f(t.data,this.#L);if(a instanceof i.f||e instanceof u.i)return s.Ay.debug(`Parent ${a} or ${e} is no-op, returning NoopSpan`),new i.f(t.data,this.#L);o=e.traceId,a?(s.Ay.debug("Using parent span %s",a.spanId),n=a.spanId):s.Ay.debug("No parent span, using current trace %s",e.traceId)}return o?(s.Ay.debug(`Creating span ${JSON.stringify(t.data)} with id ${t.spanId??o}`),new i.L({...t,traceId:o,parentId:n},this.#L)):(s.Ay.error("No traceId found. Make sure to start a trace with `withTrace()` first. Returning NoopSpan."),new i.f(t.data,this.#L))}async shutdown(t){try{s.Ay.debug("Shutting down tracing provider"),await this.#L.shutdown(t)}catch(t){s.Ay.error("Error shutting down tracing provider %o",t)}}#Z(){if(void 0!==l&&"function"==typeof l.on){const t=async()=>{const t=setTimeout(()=>{console.warn("Cleanup timeout, forcing exit"),l.exit(1)},5e3);try{await this.shutdown()}finally{clearTimeout(t)}};l.on("beforeExit",t),l.on("SIGINT",async()=>{await t(),d("SIGINT")||l.exit(130)}),l.on("SIGTERM",async()=>{await t(),d("SIGTERM")||l.exit(0)}),l.on("unhandledRejection",async(e,n)=>{s.Ay.error("Unhandled rejection",e,n),await t(),l.listeners("unhandledRejection").length>1||l.exit(1)})}}async forceFlush(){await this.#L.forceFlush()}}function d(t){return l.listeners(t).length>1}let m;function g(){return m||(m=new p),m}},3004:(t,e,n)=>{"use strict";n.d(e,{Ay:()=>l,tZ:()=>u,vF:()=>c});var r=n(7833),o=n.n(r),s=n(5786);const a=s.m9.dontLogModelData,i=s.m9.dontLogToolData;function u(t="openai-agents"){return{namespace:t,debug:o()(t),error:console.error,warn:console.warn,dontLogModelData:a,dontLogToolData:i}}const c=u("openai-agents:core"),l=c},4075:(t,e,n)=>{"use strict";n.d(e,{C:()=>s,i:()=>a});var r=n(7755),o=n(7020);class s{type="trace";traceId;name;groupId=null;metadata;#q;#U;constructor(t,e){this.traceId=t.traceId??(0,o.el)(),this.name=t.name??"Agent workflow",this.groupId=t.groupId??null,this.metadata=t.metadata??{},this.#q=e??(0,r.mh)(),this.#U=t.started??!1}async start(){this.#U||(this.#U=!0,await this.#q.onTraceStart(this))}async end(){this.#U&&(this.#U=!1,await this.#q.onTraceEnd(this))}clone(){return new s({traceId:this.traceId,name:this.name,groupId:this.groupId??void 0,metadata:this.metadata,started:this.#U})}toJSON(){return{object:this.type,id:this.traceId,workflow_name:this.name,group_id:this.groupId,metadata:this.metadata}}}class a extends s{constructor(){super({})}async start(){}async end(){}toJSON(){return null}}},5316:(t,e,n)=>{"use strict";n.d(e,{Ko:()=>o,Um:()=>a,u9:()=>s});var r=n(341);class o{on(t,e){return this.eventEmitter.on(t,e),this.eventEmitter}off(t,e){return this.eventEmitter.off(t,e),this.eventEmitter}emit(t,...e){return this.eventEmitter.emit(t,...e)}once(t,e){return this.eventEmitter.once(t,e),this.eventEmitter}}class s extends o{eventEmitter=new r.j3}class a extends o{eventEmitter=new r.j3}},5606:t=>{var e,n,r=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(e===setTimeout)return setTimeout(t,0);if((e===o||!e)&&setTimeout)return e=setTimeout,setTimeout(t,0);try{return e(t,0)}catch(n){try{return e.call(null,t,0)}catch(n){return e.call(this,t,0)}}}!function(){try{e="function"==typeof setTimeout?setTimeout:o}catch(t){e=o}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(t){n=s}}();var i,u=[],c=!1,l=-1;function p(){c&&i&&(c=!1,i.length?u=i.concat(u):l=-1,u.length&&d())}function d(){if(!c){var t=a(p);c=!0;for(var e=u.length;e;){for(i=u,u=[];++l<e;)i&&i[l].run();l=-1,e=u.length}i=null,c=!1,function(t){if(n===clearTimeout)return clearTimeout(t);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(t);try{return n(t)}catch(e){try{return n.call(null,t)}catch(e){return n.call(this,t)}}}(t)}}function m(t,e){this.fun=t,this.array=e}function g(){}r.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];u.push(new m(t,e)),1!==u.length||c||a(d)},m.prototype.run=function(){this.fun.apply(null,this.array)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.versions={},r.on=g,r.addListener=g,r.once=g,r.off=g,r.removeListener=g,r.removeAllListeners=g,r.emit=g,r.prependListener=g,r.prependOnceListener=g,r.listeners=function(t){return[]},r.binding=function(t){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(t){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}},5738:(t,e,n)=>{"use strict";n.d(e,{ab:()=>l,cp:()=>p,z6:()=>m});var r=n(8326),o=n(9352),s=n(9520),a=n(6201),i=n(3004),u=n(9463),c=n(6170);function l(t){return{type:"computer",name:t.name??"computer_use_preview",computer:t.computer}}function p(t){return"serverUrl"in t?{type:"hosted_tool",name:"hosted_mcp",providerData:void 0===t.requireApproval||"never"===t.requireApproval?{type:"mcp",server_label:t.serverLabel,server_url:t.serverUrl,require_approval:"never",allowed_tools:h(t.allowedTools),headers:t.headers}:{type:"mcp",server_label:t.serverLabel,server_url:t.serverUrl,allowed_tools:h(t.allowedTools),headers:t.headers,require_approval:"string"==typeof t.requireApproval?"always":g(t.requireApproval),on_approval:t.onApproval}}:"connectorId"in t?{type:"hosted_tool",name:"hosted_mcp",providerData:void 0===t.requireApproval||"never"===t.requireApproval?{type:"mcp",server_label:t.serverLabel,connector_id:t.connectorId,authorization:t.authorization,require_approval:"never",allowed_tools:h(t.allowedTools),headers:t.headers}:{type:"mcp",server_label:t.serverLabel,connector_id:t.connectorId,authorization:t.authorization,allowed_tools:h(t.allowedTools),headers:t.headers,require_approval:"string"==typeof t.requireApproval?"always":g(t.requireApproval),on_approval:t.onApproval}}:{type:"hosted_tool",name:"hosted_mcp",providerData:void 0===t.requireApproval||"never"===t.requireApproval?{type:"mcp",server_label:t.serverLabel,require_approval:"never",allowed_tools:h(t.allowedTools)}:{type:"mcp",server_label:t.serverLabel,allowed_tools:h(t.allowedTools),require_approval:"string"==typeof t.requireApproval?"always":g(t.requireApproval),on_approval:t.onApproval}}}function d(t,e){return`An error occurred while running the tool. Please try again. Error: ${e instanceof Error?e.toString():String(e)}`}function m(t){const e=t.name?(0,o.Tl)(t.name):(0,o.Tl)(t.execute.name),n=void 0===t.errorFunction?d:t.errorFunction;if(!e)throw new Error("Tool name cannot be empty. Either name your function or provide a name in the options.");const l=t.strict??!0;if(!l&&(0,s.f)(t.parameters))throw new a.yo("Strict mode is required for Zod parameters");const{parser:p,schema:m}=(0,o.AW)(t.parameters,e),g="function"==typeof t.needsApproval?t.needsApproval:async()=>"boolean"==typeof t.needsApproval&&t.needsApproval,h="function"==typeof t.isEnabled?async(e,n)=>{const r=t.isEnabled,o=await r({runContext:e,agent:n});return Boolean(o)}:async()=>"boolean"!=typeof t.isEnabled||t.isEnabled;return{type:"function",name:e,description:t.description,parameters:m,strict:l,invoke:async function(o,s,l){return async function(n,o,s){const[u,l]=await(0,r.V)(()=>p(o));if(null!==u)throw i.Ay.dontLogToolData?i.Ay.debug(`Invalid JSON input for tool ${e}`):i.Ay.debug(`Invalid JSON input for tool ${e}: ${o}`),new a.af("Invalid JSON input for tool");i.Ay.dontLogToolData?i.Ay.debug(`Invoking tool ${e}`):i.Ay.debug(`Invoking tool ${e} with input ${o}`);const d=await t.execute(l,n,s),m=(0,c.I)(d);return i.Ay.dontLogToolData?i.Ay.debug(`Tool ${e} completed`):i.Ay.debug(`Tool ${e} returned: ${m}`),d}(o,s,l).catch(t=>{if(n){const r=(0,u.YP)();return r?.setError({message:"Error running tool (non-fatal)",data:{tool_name:e,error:t.toString()}}),n(o,t)}throw t})},needsApproval:g,isEnabled:h}}function g(t){const e={};return t.always&&(e.always={tool_names:t.always.toolNames}),t.never&&(e.never={tool_names:t.never.toolNames}),e}function h(t){if(void 0!==t)return Array.isArray(t)?{tool_names:t}:{tool_names:t?.toolNames??[]}}},5786:(t,e,n)=>{"use strict";n.d(e,{m9:()=>i,y:()=>o,zR:()=>a});var r=n(341);function o(){return(0,r.y)()}function s(t){const e=o();return void 0!==e&&("true"===e[t]||"1"===e[t])}const a={get disabled(){return!!(0,r.Iz)()||"test"===o().NODE_ENV||s("OPENAI_AGENTS_DISABLE_TRACING")}},i={get dontLogModelData(){return s("OPENAI_AGENTS_DONT_LOG_MODEL_DATA")},get dontLogToolData(){return s("OPENAI_AGENTS_DONT_LOG_TOOL_DATA")}}},6162:(t,e,n)=>{"use strict";n.d(e,{g6:()=>Se,u9:()=>u.u9,pf:()=>y.pf,AF:()=>o.AF,VD:()=>o.VD,yZ:()=>y.yZ,Pj:()=>z,Fb:()=>y.Fb,p2:()=>c.p2,l6:()=>c.l6,Wm:()=>c.Wm,MP:()=>y.MP,af:()=>y.af,fz:()=>o.fz,ih:()=>o.ih,ST:()=>p,K6:()=>y.K6,gm:()=>Nt,ZI:()=>gt,f_:()=>Tt,AU:()=>St,R1:()=>Rt,js:()=>zt,zG:()=>Ot,ZS:()=>It,ns:()=>ft,ll:()=>me,A9:()=>Ct,nM:()=>xt,KR:()=>At,by:()=>ve,j3:()=>a.j3,L9:()=>o.L9,A1:()=>yt,_N:()=>y._N,Du:()=>y.Du,Cn:()=>o.Cn,hh:()=>Xt.h,_U:()=>mt,yo:()=>y.yo,VP:()=>o.VP,h1:()=>Pe,ab:()=>f.ab,M6:()=>o.M6,ub:()=>o.ub,tQ:()=>o.tQ,Xq:()=>o.Xq,Eu:()=>o.Eu,DT:()=>o.DT,ux:()=>o.ux,V4:()=>Ee,UI:()=>o.UI,it:()=>o.it,tL:()=>o.tL,B9:()=>o.B9,_o:()=>T,ZV:()=>kt,uA:()=>o.uA,ZF:()=>o.ZF,el:()=>o.el,Ph:()=>c.Ph,YP:()=>o.YP,Co:()=>o.j3,fZ:()=>g,sL:()=>h,At:()=>Xt.A,Pu:()=>A,tZ:()=>b.tZ,Nn:()=>o.Nn,Nx:()=>w,Z5:()=>d,NS:()=>x,cp:()=>f.cp,qi:()=>c.qi,w_:()=>m,y6:()=>c.y6,TB:()=>r,h6:()=>o.h6,eF:()=>ze,mq:()=>o.mq,MJ:()=>C,JA:()=>o.JA,dr:()=>o.dr,Qv:()=>o.Qv,qU:()=>ke,z6:()=>f.z6,kQ:()=>Ce,mp:()=>o.mp,Ee:()=>o.Ee,PJ:()=>o.PJ,hn:()=>o.hn,cS:()=>o.cS,$t:()=>o.$t,cW:()=>o.cW,Cp:()=>o.Cp,UC:()=>o.UC,L0:()=>o.L0,SZ:()=>o.SZ,LG:()=>o.LG});var r={};n.r(r),n.d(r,{AssistantContent:()=>J,AssistantMessageItem:()=>K,AudioContent:()=>F,ComputerCallResultItem:()=>et,ComputerToolOutput:()=>q,ComputerUseCallItem:()=>tt,FunctionCallItem:()=>Y,FunctionCallResultItem:()=>X,HostedToolCallItem:()=>Q,ImageContent:()=>L,InputFile:()=>D,InputImage:()=>M,InputText:()=>R,ItemBase:()=>E,MessageItem:()=>V,ModelItem:()=>at,OutputModelItem:()=>st,OutputText:()=>O,ReasoningItem:()=>rt,ReasoningText:()=>N,Refusal:()=>j,SharedBase:()=>P,StreamEvent:()=>dt,StreamEventGenericItem:()=>pt,StreamEventResponseCompleted:()=>lt,StreamEventResponseStarted:()=>ct,StreamEventTextStream:()=>ut,ToolCallItem:()=>nt,ToolOutputImage:()=>Z,ToolOutputText:()=>$,UnknownItem:()=>ot,UsageData:()=>it,UserContent:()=>B,UserMessageItem:()=>W,computerActions:()=>U});var o=n(9463),s=n(7755),a=n(341),i=n(4231),u=n(5316),c=n(7788),l=n(5786);const p="OPENAI_DEFAULT_MODEL";function d(t){return!t.startsWith("gpt-5-chat")&&t.startsWith("gpt-5")}function m(){return d(g())}function g(){const t=(0,l.y)();return t[p]?.toLowerCase()??"gpt-4.1"}function h(t){return d(t??g())?{reasoning:{effort:"low"},text:{verbosity:"low"}}:{}}var f=n(5738),y=n(6201),_=n(9352),v=n(26),b=n(3004);function w(t){return JSON.stringify({assistant:t.name})}class z{toolName;toolDescription;inputJsonSchema={type:"object",properties:{},required:[],additionalProperties:!1};strictJsonSchema=!0;onInvokeHandoff;agentName;inputFilter;agent;getHandoffAsFunctionTool(){return{type:"function",name:this.toolName,description:this.toolDescription,parameters:this.inputJsonSchema,strict:this.strictJsonSchema}}isEnabled=async()=>!0;constructor(t,e){this.agentName=t.name,this.onInvokeHandoff=e,this.toolName=function(t){return`transfer_to_${(0,_.Tl)(t.name)}`}(t),this.toolDescription=function(t){return`Handoff to the ${t.name} agent to handle the request. ${t.handoffDescription??""}`}(t),this.agent=t}}function x(t,e={}){let n;if(!!e.onHandoff!=!!e.inputType)throw new y.yo("You must provide either both `onHandoff` and `inputType` or neither.");const r=new z(t,async function(r,o){if(n){if(!o)throw(0,v.eE)({message:`Handoff function expected non empty input but got: ${o}`,data:{details:"input is empty"}}),new y.af("Handoff function expected non empty input");try{const t=await n(o);e.onHandoff&&await e.onHandoff(r,t)}catch(t){throw(0,v.eE)({message:"Invalid JSON provided",data:{}}),b.Ay.dontLogToolData||b.Ay.error(`Invalid JSON when parsing: ${o}. Error: ${t}`),new y.af("Invalid JSON provided")}}else await(e.onHandoff?.(r));return t});if("function"==typeof e.isEnabled){const t=e.isEnabled;r.isEnabled=async({runContext:e,agent:n})=>{const r=await t({runContext:e,agent:n});return Boolean(r)}}else"boolean"==typeof e.isEnabled&&(r.isEnabled=async()=>e.isEnabled);if(e.inputType){const t=(0,_.AW)(e.inputType,r.toolName);r.inputJsonSchema=t.schema,r.strictJsonSchema=!0,n=t.parser}return e.toolNameOverride&&(r.toolName=e.toolNameOverride),e.toolDescriptionOverride&&(r.toolDescription=e.toolDescriptionOverride),e.inputFilter&&(r.inputFilter=e.inputFilter),r}function A(t){return t instanceof z?t:x(t)}function I({name:t,execute:e}){return{type:"input",name:t,guardrailFunction:e,run:async n=>({guardrail:{type:"input",name:t},output:await e(n)})}}function T({name:t,execute:e}){return{type:"output",name:t,guardrailFunction:e,run:async n=>({guardrail:{type:"output",name:t},agent:n.agent,agentOutput:n.agentOutput,output:await e(n)})}}let S;function C(t){S=t}function k(){if(void 0===S)throw new Error("No default model provider set. Make sure to set a provider using setDefaultModelProvider before calling getDefaultModelProvider or pass an explicit provider.");return S}const P=i.z.object({providerData:i.z.record(i.z.string(),i.z.any()).optional()}),E=P.extend({id:i.z.string().optional()}),j=P.extend({type:i.z.literal("refusal"),refusal:i.z.string()}),O=P.extend({type:i.z.literal("output_text"),text:i.z.string()}),R=P.extend({type:i.z.literal("input_text"),text:i.z.string()}),N=P.extend({type:i.z.literal("reasoning_text"),text:i.z.string()}),M=P.extend({type:i.z.literal("input_image"),image:i.z.string().or(i.z.object({id:i.z.string()})).describe("Could be a URL, base64 or an object with a file ID.")}),D=P.extend({type:i.z.literal("input_file"),file:i.z.string().describe("Either base64 encoded file data or a publicly accessible file URL").or(i.z.object({id:i.z.string().describe("OpenAI file ID")})).or(i.z.object({url:i.z.string().describe("Publicly accessible PDF file URL")})).describe("Contents of the file or an object with a file ID.")}),F=P.extend({type:i.z.literal("audio"),audio:i.z.string().or(i.z.object({id:i.z.string()})).describe("Base64 encoded audio data or file id"),format:i.z.string().nullable().optional(),transcript:i.z.string().nullable().optional()}),L=P.extend({type:i.z.literal("image"),image:i.z.string().describe("Base64 encoded image data")}),$=P.extend({type:i.z.literal("text"),text:i.z.string()}),Z=P.extend({type:i.z.literal("image"),data:i.z.string().describe("Base64 encoded image data"),mediaType:i.z.string().describe("IANA media type of the image")}),q=P.extend({type:i.z.literal("computer_screenshot"),data:i.z.string().describe("Base64 encoded image data or URL")}),U=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("screenshot")}),i.z.object({type:i.z.literal("click"),x:i.z.number(),y:i.z.number(),button:i.z.enum(["left","right","wheel","back","forward"])}),i.z.object({type:i.z.literal("double_click"),x:i.z.number(),y:i.z.number()}),i.z.object({type:i.z.literal("scroll"),x:i.z.number(),y:i.z.number(),scroll_x:i.z.number(),scroll_y:i.z.number()}),i.z.object({type:i.z.literal("type"),text:i.z.string()}),i.z.object({type:i.z.literal("wait")}),i.z.object({type:i.z.literal("move"),x:i.z.number(),y:i.z.number()}),i.z.object({type:i.z.literal("keypress"),keys:i.z.array(i.z.string())}),i.z.object({type:i.z.literal("drag"),path:i.z.array(i.z.object({x:i.z.number(),y:i.z.number()}))})]),J=i.z.discriminatedUnion("type",[O,j,F,L]),G=E.extend({type:i.z.literal("message").optional()}),K=G.extend({role:i.z.literal("assistant"),status:i.z.enum(["in_progress","completed","incomplete"]),content:i.z.array(J)}),B=i.z.discriminatedUnion("type",[R,M,D,F]),W=G.extend({role:i.z.literal("user"),content:i.z.array(B).or(i.z.string())}),H=G.extend({role:i.z.literal("system"),content:i.z.string()}),V=i.z.discriminatedUnion("role",[H,K,W]),Q=E.extend({type:i.z.literal("hosted_tool_call"),name:i.z.string().describe("The name of the hosted tool"),arguments:i.z.string().describe("The arguments of the hosted tool call").optional(),status:i.z.string().optional(),output:i.z.string().optional()}),Y=E.extend({type:i.z.literal("function_call"),callId:i.z.string().describe("The ID of the tool call"),name:i.z.string().describe("The name of the function"),status:i.z.enum(["in_progress","completed","incomplete"]).optional(),arguments:i.z.string()}),X=E.extend({type:i.z.literal("function_call_result"),name:i.z.string().describe("The name of the tool"),callId:i.z.string().describe("The ID of the tool call"),status:i.z.enum(["in_progress","completed","incomplete"]),output:i.z.discriminatedUnion("type",[$,Z])}),tt=E.extend({type:i.z.literal("computer_call"),callId:i.z.string().describe("The ID of the computer call"),status:i.z.enum(["in_progress","completed","incomplete"]),action:U}),et=E.extend({type:i.z.literal("computer_call_result"),callId:i.z.string().describe("The ID of the computer call"),output:q}),nt=i.z.discriminatedUnion("type",[tt,Y,Q]),rt=P.extend({id:i.z.string().optional(),type:i.z.literal("reasoning"),content:i.z.array(R),rawContent:i.z.array(N).optional()}),ot=E.extend({type:i.z.literal("unknown")}),st=i.z.discriminatedUnion("type",[K,Q,Y,tt,rt,ot]),at=i.z.union([W,K,H,Q,Y,tt,X,et,rt,ot]),it=i.z.object({requests:i.z.number().optional(),inputTokens:i.z.number(),outputTokens:i.z.number(),totalTokens:i.z.number(),inputTokensDetails:i.z.record(i.z.string(),i.z.number()).optional(),outputTokensDetails:i.z.record(i.z.string(),i.z.number()).optional()}),ut=P.extend({type:i.z.literal("output_text_delta"),delta:i.z.string()}),ct=P.extend({type:i.z.literal("response_started")}),lt=P.extend({type:i.z.literal("response_done"),response:P.extend({id:i.z.string(),usage:it,output:i.z.array(st)})}),pt=P.extend({type:i.z.literal("model"),event:i.z.any().describe("The event from the model")}),dt=i.z.discriminatedUnion("type",[ut,lt,ct,pt]);class mt{requests;inputTokens;outputTokens;totalTokens;inputTokensDetails=[];outputTokensDetails=[];constructor(t){if(void 0===t)this.requests=0,this.inputTokens=0,this.outputTokens=0,this.totalTokens=0,this.inputTokensDetails=[],this.outputTokensDetails=[];else{this.requests=t?.requests??1,this.inputTokens=t?.inputTokens??t?.input_tokens??0,this.outputTokens=t?.outputTokens??t?.output_tokens??0,this.totalTokens=t?.totalTokens??t?.total_tokens??0;const e=t?.inputTokensDetails??t?.input_tokens_details;this.inputTokensDetails=e?[e]:[];const n=t?.outputTokensDetails??t?.output_tokens_details;this.outputTokensDetails=n?[n]:[]}}add(t){this.requests+=t.requests,this.inputTokens+=t.inputTokens,this.outputTokens+=t.outputTokens,this.totalTokens+=t.totalTokens,t.inputTokensDetails&&this.inputTokensDetails.push(...t.inputTokensDetails),t.outputTokensDetails&&this.outputTokensDetails.push(...t.outputTokensDetails)}}class gt{context;usage;#J;constructor(t={}){this.context=t,this.usage=new mt,this.#J=new Map}_rebuildApprovals(t){this.#J=new Map(Object.entries(t))}isToolApproved({toolName:t,callId:e}){const n=this.#J.get(t);if(!0===n?.approved&&!0===n.rejected)return b.Ay.warn("Tool is permanently approved and rejected at the same time. Approval takes precedence"),!0;if(!0===n?.approved)return!0;if(!0===n?.rejected)return!1;const r=!!Array.isArray(n?.approved)&&n.approved.includes(e),o=!!Array.isArray(n?.rejected)&&n.rejected.includes(e);return r&&o?(b.Ay.warn(`Tool call ${e} is both approved and rejected at the same time. Approval takes precedence`),!0):!!r||!o&&void 0}approveTool(t,{alwaysApprove:e=!1}={}){const n=t.rawItem.name;if(e)return void this.#J.set(n,{approved:!0,rejected:[]});const r=this.#J.get(n)??{approved:[],rejected:[]};if(Array.isArray(r.approved)){const e="callId"in t.rawItem?t.rawItem.callId:t.rawItem.id;r.approved.push(e)}this.#J.set(n,r)}rejectTool(t,{alwaysReject:e=!1}={}){const n=t.rawItem.name;if(e)return void this.#J.set(n,{approved:!1,rejected:!0});const r=this.#J.get(n)??{approved:[],rejected:[]};if(Array.isArray(r.rejected)){const e="callId"in t.rawItem?t.rawItem.callId:t.rawItem.id;r.rejected.push(e)}this.#J.set(n,r)}toJSON(){return{context:this.context,usage:this.usage,approvals:Object.fromEntries(this.#J.entries())}}}class ht{state;constructor(t){this.state=t}get history(){return _e(this.input,this.newItems)}get output(){return _e([],this.newItems)}get input(){return this.state._originalInput}get newItems(){return this.state._generatedItems}get rawResponses(){return this.state._modelResponses}get lastResponseId(){const t=this.rawResponses;return t&&t.length>0?t[t.length-1].responseId:void 0}get lastAgent(){return this.state._currentAgent}get inputGuardrailResults(){return this.state._inputGuardrailResults}get outputGuardrailResults(){return this.state._outputGuardrailResults}get interruptions(){return"next_step_interruption"===this.state._currentStep?.type?this.state._currentStep.data.interruptions:[]}get finalOutput(){if("next_step_final_output"===this.state._currentStep?.type)return this.state._currentAgent.processFinalOutput(this.state._currentStep.output);b.Ay.warn("Accessed finalOutput before agent run is completed.")}}class ft extends ht{constructor(t){super(t)}}class yt extends ht{get currentAgent(){return this.lastAgent}currentTurn=0;maxTurns;#G=null;#K;#B;#W;#H;#V;#Q;#Y=!1;constructor(t={}){if(super(t.state),this.#K=t.signal,this.#W=new a.ZY({start:t=>{this.#B=t},cancel:()=>{this.#Y=!0}}),this.#H=new Promise((t,e)=>{this.#V=t,this.#Q=e}),this.#K){const t=()=>{if(this.#Y)return;this.#Y=!0;const t=this.#B;if(this.#B=void 0,this.#W.locked){if(t)try{t.close()}catch(t){b.Ay.debug(`Failed to close readable stream on abort: ${t}`)}}else this.#W.cancel(this.#K?.reason).catch(t=>{b.Ay.debug(`Failed to cancel readable stream on abort: ${t}`)});this.#V?.()};this.#K.aborted?t():this.#K.addEventListener("abort",t,{once:!0})}}_addItem(t){this.cancelled||this.#B?.enqueue(t)}_done(){!this.cancelled&&this.#B&&(this.#B.close(),this.#B=void 0,this.#V?.())}_raiseError(t){!this.cancelled&&this.#B&&(this.#B.error(t),this.#B=void 0),this.#G=t,this.#Q?.(t),this.#H.catch(t=>{b.Ay.debug(`Resulted in an error: ${t}`)})}get cancelled(){return this.#Y}toStream(){return this.#W}get completed(){return this.#H}get error(){return this.#G}toTextStream(t={}){const e=this.#W.pipeThrough(new a.Rv({transform(t,e){if("raw_model_stream_event"===t.type&&"output_text_delta"===t.data.type){const n=ut.parse(t.data);e.enqueue(n.delta)}}}));return t.compatibleWithNodeStreams?a.$p.fromWeb(e):e}[Symbol.asyncIterator](){return this.#W[Symbol.asyncIterator]()}}function _t(t){return"function"===t.type?{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}:"computer"===t.type?{type:"computer",name:t.name,environment:t.computer.environment,dimensions:t.computer.dimensions}:{type:"hosted_tool",name:t.name,providerData:t.providerData}}function vt(t){return{toolName:t.toolName,toolDescription:t.toolDescription,inputJsonSchema:t.inputJsonSchema,strictJsonSchema:t.strictJsonSchema}}var bt=n(6170);class wt{type="base_item";rawItem;toJSON(){return{type:this.type,rawItem:this.rawItem}}}class zt extends wt{rawItem;agent;type="message_output_item";constructor(t,e){super(),this.rawItem=t,this.agent=e}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}get content(){let t="";for(const e of this.rawItem.content)"output_text"===e.type&&(t+=e.text);return t}}class xt extends wt{rawItem;agent;type="tool_call_item";constructor(t,e){super(),this.rawItem=t,this.agent=e}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class At extends wt{rawItem;agent;output;type="tool_call_output_item";constructor(t,e,n){super(),this.rawItem=t,this.agent=e,this.output=n}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON(),output:(0,bt.I)(this.output)}}}class It extends wt{rawItem;agent;type="reasoning_item";constructor(t,e){super(),this.rawItem=t,this.agent=e}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class Tt extends wt{rawItem;agent;type="handoff_call_item";constructor(t,e){super(),this.rawItem=t,this.agent=e}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class St extends wt{rawItem;sourceAgent;targetAgent;type="handoff_output_item";constructor(t,e,n){super(),this.rawItem=t,this.sourceAgent=e,this.targetAgent=n}toJSON(){return{...super.toJSON(),sourceAgent:this.sourceAgent.toJSON(),targetAgent:this.targetAgent.toJSON()}}}class Ct extends wt{rawItem;agent;type="tool_approval_item";constructor(t,e){super(),this.rawItem=t,this.agent=e}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}function kt(t){return t.filter(t=>"message_output_item"===t.type).map(t=>t.content).join("")}function Pt(t){if("message"!==t.type)return;if("assistant"!==t.role)return;const e=t.content[t.content.length-1];return"output_text"===e.type?e.text:void 0}var Et=n(476),jt=n(8326);class Ot{data;type="raw_model_stream_event";constructor(t){this.data=t}}class Rt{name;item;type="run_item_stream_event";constructor(t,e){this.name=t,this.item=e}}class Nt{agent;type="agent_updated_stream_event";constructor(t){this.agent=t}}var Mt=n(7962);function Dt(t,e,n,r){const o=[],s=[],a=[],i=[],u=[],c=[],l=new Map(r.map(t=>[t.toolName,t])),p=new Map(n.filter(t=>"function"===t.type).map(t=>[t.name,t])),d=n.find(t=>"computer"===t.type),m=new Map(n.filter(t=>"hosted_tool"===t.type&&"mcp"===t.providerData?.type).map(t=>t).map(t=>[t.providerData.server_label,t]));for(const n of t.output){if("message"===n.type)"assistant"===n.role&&o.push(new zt(n,e));else if("hosted_tool_call"===n.type){o.push(new xt(n,e));const t=n.name;if(c.push(t),"mcp_approval_request"===n.providerData?.type||"mcp_approval_request"===n.name){const t=n.providerData,r=t.server_label,s=m.get(r);if(void 0===s){const t=`MCP server (${r}) not found in Agent (${e.name})`;throw(0,v.eE)({message:t,data:{mcp_server_label:r}}),new y.af(t)}const a=new Ct({type:"hosted_tool_call",name:t.name,id:t.id,status:"in_progress",providerData:t},e);u.push({requestItem:a,mcpTool:s}),s.providerData.on_approval||o.push(a)}}else if("reasoning"===n.type)o.push(new It(n,e));else if("computer_call"===n.type){if(o.push(new xt(n,e)),c.push("computer_use"),!d)throw(0,v.eE)({message:"Model produced computer action without a computer tool.",data:{agent_name:e.name}}),new y.af("Model produced computer action without a computer tool.");i.push({toolCall:n,computer:d})}if("function_call"!==n.type)continue;c.push(n.name);const t=l.get(n.name);if(t)o.push(new Tt(n,e)),s.push({toolCall:n,handoff:t});else{const t=p.get(n.name);if(!t)throw(0,v.eE)({message:`Tool ${n.name} not found in agent ${e.name}.`,data:{tool_name:n.name,agent_name:e.name}}),new y.af(`Tool ${n.name} not found in agent ${e.name}.`);o.push(new xt(n,e)),a.push({toolCall:n,tool:t})}}return{newItems:o,handoffs:s,functions:a,computerActions:i,mcpApprovalRequests:u,toolsUsed:c,hasToolsOrApprovalsToRun:()=>s.length>0||a.length>0||u.length>0||i.length>0}}const Ft=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("next_step_handoff"),newAgent:i.z.any()}),i.z.object({type:i.z.literal("next_step_final_output"),output:i.z.string()}),i.z.object({type:i.z.literal("next_step_run_again")}),i.z.object({type:i.z.literal("next_step_interruption"),data:i.z.record(i.z.string(),i.z.any())})]);class Lt{originalInput;modelResponse;preStepItems;newStepItems;nextStep;constructor(t,e,n,r,o){this.originalInput=t,this.modelResponse=e,this.preStepItems=n,this.newStepItems=r,this.nextStep=o}get generatedItems(){return this.preStepItems.concat(this.newStepItems)}}function $t(t,e,n){return t.resetToolChoice&&e.hasUsedTools(t)?{...n,toolChoice:void 0}:n}async function Zt(t,e,n,r,o,s,a){const i=n.filter(t=>t instanceof Ct&&"callId"in t.rawItem&&"function_call"===t.rawItem.type).map(t=>t.rawItem.callId),u=o.functions.filter(t=>i.includes(t.toolCall.callId)),c=await Jt(t,u,s,a),l=c.map(t=>t.runItem),p=o.mcpApprovalRequests.filter(t=>"tool_approval_item"===t.requestItem.type&&"hosted_tool_call"===t.requestItem.rawItem.type&&"mcp_approval_request"===t.requestItem.rawItem.providerData?.type);for(const e of p){const n=e.requestItem.rawItem.id,r=a._context.isToolApproved({toolName:e.requestItem.rawItem.name,callId:n});if(void 0!==r){const e={approve:r,approval_request_id:n,reason:void 0};l.push(new xt({type:"hosted_tool_call",name:"mcp_approval_response",providerData:e},t))}}const d=await Wt(t,c,a),m=n.filter(t=>!(t instanceof Ct));return d.isFinalOutput?(s.emit("agent_end",a._context,t,d.finalOutput),t.emit("agent_end",a._context,d.finalOutput),new Lt(e,r,m,l,{type:"next_step_final_output",output:d.finalOutput})):d.isInterrupted?new Lt(e,r,m,l,{type:"next_step_interruption",data:{interruptions:d.interruptions}}):new Lt(e,r,m,l,{type:"next_step_run_again"})}async function qt(t,e,n,r,o,s,a){const i=n;let u=o.newItems;const[c,l]=await Promise.all([Jt(t,o.functions,s,a),Kt(t,o.computerActions,s,a._context)]);if(u=u.concat(c.map(t=>t.runItem)),u=u.concat(l),o.mcpApprovalRequests.length>0)for(const e of o.mcpApprovalRequests){const n=e.mcpTool.providerData,r=e.requestItem.rawItem.providerData;if(n.on_approval){const o=await n.on_approval(a._context,e.requestItem),s={approve:o.approve,approval_request_id:r.id,reason:o.reason};u.push(new xt({type:"hosted_tool_call",name:"mcp_approval_response",providerData:s},t))}else{u.push(e.requestItem);const n={type:"hosted_mcp_tool_approval",tool:e.mcpTool,runItem:new Ct({type:"hosted_tool_call",name:r.name,id:r.id,arguments:r.arguments,status:"in_progress",providerData:r},t)};c.push(n)}}if(o.handoffs.length>0)return await async function(t,e,n,r,o,s,a,i){if(r=[...r],0===s.length)return b.Ay.warn("Incorrectly called executeHandoffCalls with no handoffs. This should not happen. Moving on."),new Lt(e,o,n,r,{type:"next_step_run_again"});if(s.length>1){const e="Multiple handoffs detected, ignoring this one.";for(let n=1;n<s.length;n++)r.push(new At(Ut(s[n].toolCall,e),t,e))}const u=s[0];return(0,Et.$t)(async c=>{const l=u.handoff,p=await l.onInvokeHandoff(i,u.toolCall.arguments);if(c.spanData.to_agent=p.name,s.length>1){const t=s.map(t=>t.handoff.agentName);c.setError({message:"Multiple handoffs requested",data:{requested_agents:t}})}r.push(new St(Ut(u.toolCall,w(p)),t,p)),a.emit("agent_handoff",i,t,p),t.emit("agent_handoff",i,p);const d=l.inputFilter??a.config.handoffInputFilter;if(d){b.Ay.debug("Filtering inputs for handoff"),"function"!=typeof d&&c.setError({message:"Invalid input filter",data:{details:"not callable"}});const t=d({inputHistory:Array.isArray(e)?[...e]:e,preHandoffItems:[...n],newItems:[...r],runContext:i});e=t.inputHistory,n=t.preHandoffItems,r=t.newItems}return new Lt(e,o,n,r,{type:"next_step_handoff",newAgent:p})},{data:{from_agent:t.name}})}(t,e,i,u,r,o.handoffs,s,a._context);const p=await Wt(t,c,a);if(p.isFinalOutput)return s.emit("agent_end",a._context,t,p.finalOutput),t.emit("agent_end",a._context,p.finalOutput),new Lt(e,r,i,u,{type:"next_step_final_output",output:p.finalOutput});if(p.isInterrupted)return new Lt(e,r,i,u,{type:"next_step_interruption",data:{interruptions:p.interruptions}});if((o.functions?.length??0)>0||(o.computerActions?.length??0)>0||(o.mcpApprovalRequests?.length??0)>0||(o.handoffs?.length??0)>0)return new Lt(e,r,i,u,{type:"next_step_run_again"});const d=u.filter(t=>t instanceof zt),m=d.length>0?Pt(d[d.length-1].rawItem):void 0;if(void 0===m)return new Lt(e,r,i,u,{type:"next_step_run_again"});if(!c.some(t=>t.runItem instanceof Ct)){if("text"===t.outputType)return new Lt(e,r,i,u,{type:"next_step_final_output",output:m});if("text"!==t.outputType&&m){const{parser:n}=(0,_.AW)(t.outputType,"final_output"),[o]=await(0,jt.V)(()=>n(m));if(o)throw(0,v.eE)({message:"Invalid output type",data:{error:String(o)}}),new y.af("Invalid output type");return new Lt(e,r,i,u,{type:"next_step_final_output",output:m})}}return new Lt(e,r,i,u,{type:"next_step_run_again"})}function Ut(t,e){return{type:"function_call_result",name:t.name,callId:t.callId,status:"completed",output:{type:"text",text:(0,bt.I)(e)}}}async function Jt(t,e,n,r){try{return await Promise.all(e.map(async function(e){let o=e.toolCall.arguments;if(e.tool.parameters&&(o=(0,Mt.f3)(e.tool.parameters)?e.tool.parameters.parse(o):JSON.parse(o)),await e.tool.needsApproval(r._context,o,e.toolCall.callId)){const n=r._context.isToolApproved({toolName:e.tool.name,callId:e.toolCall.callId});if(!1===n)return(0,Et.PJ)(async n=>{const r="Tool execution was not approved.";return n.setError({message:r,data:{tool_name:e.tool.name,error:`Tool execution for ${e.toolCall.callId} was manually rejected by user.`}}),n.spanData.output=r,{type:"function_output",tool:e.tool,output:r,runItem:new At(Ut(e.toolCall,r),t,r)}},{data:{name:e.tool.name}});if(!0!==n)return{type:"function_approval",tool:e.tool,runItem:new Ct(e.toolCall,t)}}return(0,Et.PJ)(async o=>{n.config.traceIncludeSensitiveData&&(o.spanData.input=e.toolCall.arguments);try{n.emit("agent_tool_start",r._context,t,e.tool,{toolCall:e.toolCall}),t.emit("agent_tool_start",r._context,e.tool,{toolCall:e.toolCall});const s=await e.tool.invoke(r._context,e.toolCall.arguments,{toolCall:e.toolCall}),a=(0,bt.I)(s);n.emit("agent_tool_end",r._context,t,e.tool,a,{toolCall:e.toolCall}),t.emit("agent_tool_end",r._context,e.tool,a,{toolCall:e.toolCall}),n.config.traceIncludeSensitiveData&&(o.spanData.output=a);const i={type:"function_output",tool:e.tool,output:s,runItem:new At(Ut(e.toolCall,s),t,s)},u=function(t){const e=Ie.get(t);return e&&Ie.delete(t),e}(e.toolCall);if(u){i.agentRunResult=u;const t=u.interruptions;t.length>0&&(i.interruptions=t)}return i}catch(t){throw o.setError({message:"Error running tool",data:{tool_name:e.tool.name,error:String(t)}}),t}},{data:{name:e.tool.name}})}))}catch(t){throw new y.Du(`Failed to run function tools: ${t}`,t,r)}}async function Gt(t,e){const n=e.action;let r;switch(n.type){case"click":await t.click(n.x,n.y,n.button);break;case"double_click":await t.doubleClick(n.x,n.y);break;case"drag":await t.drag(n.path.map(t=>[t.x,t.y]));break;case"keypress":await t.keypress(n.keys);break;case"move":await t.move(n.x,n.y);break;case"screenshot":r=await t.screenshot();break;case"scroll":await t.scroll(n.x,n.y,n.scroll_x,n.scroll_y);break;case"type":await t.type(n.text);break;case"wait":await t.wait()}if(void 0!==r)return r;if("function"==typeof t.screenshot&&(r=await t.screenshot(),void 0!==r))return r;throw new Error("Computer does not implement screenshot()")}async function Kt(t,e,n,r,o=void 0){const s=o??b.Ay,a=[];for(const o of e){const e=o.computer.computer,i=o.toolCall;let u;n.emit("agent_tool_start",r,t,o.computer,{toolCall:i}),"function"==typeof t.emit&&t.emit("agent_tool_start",r,o.computer,{toolCall:i});try{u=await Gt(e,i)}catch(t){s.error("Failed to execute computer action:",t),u=""}n.emit("agent_tool_end",r,t,o.computer,u,{toolCall:i}),"function"==typeof t.emit&&t.emit("agent_tool_end",r,o.computer,u,{toolCall:i});const c=u?`data:image/png;base64,${u}`:"",l={type:"computer_call_result",callId:i.callId,output:{type:"computer_screenshot",data:c}};a.push(new At(l,t,c))}return a}const Bt={isFinalOutput:!1,isInterrupted:void 0};async function Wt(t,e,n){if(0===e.length)return Bt;const r=[];for(const t of e)if(t.runItem instanceof Ct&&r.push(t.runItem),"function_output"===t.type)if(Array.isArray(t.interruptions))r.push(...t.interruptions);else if(t.agentRunResult){const e=t.agentRunResult.interruptions;e.length>0&&r.push(...e)}if(r.length>0)return{isFinalOutput:!1,isInterrupted:!0,interruptions:r};if("run_llm_again"===t.toolUseBehavior)return Bt;const o=e[0];if("stop_on_first_tool"===t.toolUseBehavior)return"function_output"===o?.type?{isFinalOutput:!0,isInterrupted:void 0,finalOutput:(0,bt.I)(o.output)}:Bt;const s=t.toolUseBehavior;if("object"==typeof s){const t=e.find(t=>s.stopAtToolNames.includes(t.tool.name));return"function_output"===t?.type?{isFinalOutput:!0,isInterrupted:void 0,finalOutput:(0,bt.I)(t.output)}:Bt}if("function"==typeof s)return s(n._context,e);throw new y.yo(`Invalid toolUseBehavior: ${s}`,n)}function Ht(t,e){const n=function(t){return t instanceof zt?"message_output_created":t instanceof Tt?"handoff_requested":t instanceof St?"handoff_occurred":t instanceof xt?"tool_called":t instanceof At?"tool_output":t instanceof It?"reasoning_item_created":t instanceof Ct?"tool_approval_requested":void 0}(e);n?t._addItem(new Rt(n,e)):b.Ay.warn("Unknown item type: ",e)}function Vt(t,e){for(const n of e)Ht(t,n)}function Qt(t,e,n){const r=n?.skipItems;for(const n of e.newStepItems)r?.has(n)||Ht(t,n)}class Yt{#X=new Map;addToolUse(t,e){this.#X.set(t,e)}hasUsedTools(t){return this.#X.has(t)}toJSON(){return Object.fromEntries(Array.from(this.#X.entries()).map(([t,e])=>[t.name,e]))}}var Xt=n(2618);const te="1.0",ee=i.z.literal(te),ne=i.z.object({name:i.z.string()}),re=i.z.object({object:i.z.literal("trace.span"),id:i.z.string(),trace_id:i.z.string(),parent_id:i.z.string().nullable(),started_at:i.z.string().nullable(),ended_at:i.z.string().nullable(),error:i.z.object({message:i.z.string(),data:i.z.record(i.z.string(),i.z.any()).optional()}).nullable(),span_data:i.z.record(i.z.string(),i.z.any())}).extend({previous_span:i.z.lazy(()=>re).optional()}),oe=i.z.object({requests:i.z.number(),inputTokens:i.z.number(),outputTokens:i.z.number(),totalTokens:i.z.number()}),se=i.z.object({usage:oe,output:i.z.array(st),responseId:i.z.string().optional(),providerData:i.z.record(i.z.string(),i.z.any()).optional()}),ae=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("message_output_item"),rawItem:K,agent:ne}),i.z.object({type:i.z.literal("tool_call_item"),rawItem:nt.or(Q),agent:ne}),i.z.object({type:i.z.literal("tool_call_output_item"),rawItem:X,agent:ne,output:i.z.string()}),i.z.object({type:i.z.literal("reasoning_item"),rawItem:rt,agent:ne}),i.z.object({type:i.z.literal("handoff_call_item"),rawItem:Y,agent:ne}),i.z.object({type:i.z.literal("handoff_output_item"),rawItem:X,sourceAgent:ne,targetAgent:ne}),i.z.object({type:i.z.literal("tool_approval_item"),rawItem:Y.or(Q),agent:ne})]),ie=i.z.object({object:i.z.literal("trace"),id:i.z.string(),workflow_name:i.z.string(),group_id:i.z.string().nullable(),metadata:i.z.record(i.z.string(),i.z.any())}),ue=i.z.object({newItems:i.z.array(ae),toolsUsed:i.z.array(i.z.string()),handoffs:i.z.array(i.z.object({toolCall:i.z.any(),handoff:i.z.any()})),functions:i.z.array(i.z.object({toolCall:i.z.any(),tool:i.z.any()})),computerActions:i.z.array(i.z.object({toolCall:i.z.any(),computer:i.z.any()})),mcpApprovalRequests:i.z.array(i.z.object({requestItem:i.z.object({rawItem:i.z.object({type:i.z.literal("hosted_tool_call"),name:i.z.string(),arguments:i.z.string().optional(),status:i.z.string().optional(),output:i.z.string().optional(),providerData:i.z.record(i.z.string(),i.z.any()).nullable().optional()})}),mcpTool:i.z.object({type:i.z.literal("hosted_tool"),name:i.z.literal("hosted_mcp"),providerData:i.z.record(i.z.string(),i.z.any())})})).optional()}),ce=i.z.object({tripwireTriggered:i.z.boolean(),outputInfo:i.z.any()}),le=i.z.object({guardrail:i.z.object({type:i.z.literal("input"),name:i.z.string()}),output:ce}),pe=i.z.object({guardrail:i.z.object({type:i.z.literal("output"),name:i.z.string()}),agentOutput:i.z.any(),agent:ne,output:ce}),de=i.z.object({$schemaVersion:ee,currentTurn:i.z.number(),currentAgent:ne,originalInput:i.z.string().or(i.z.array(at)),modelResponses:i.z.array(se),context:i.z.object({usage:oe,approvals:i.z.record(i.z.string(),i.z.object({approved:i.z.array(i.z.string()).or(i.z.boolean()),rejected:i.z.array(i.z.string()).or(i.z.boolean())})),context:i.z.record(i.z.string(),i.z.any())}),toolUseTracker:i.z.record(i.z.string(),i.z.array(i.z.string())),maxTurns:i.z.number(),currentAgentSpan:re.nullable().optional(),noActiveAgentRun:i.z.boolean(),inputGuardrailResults:i.z.array(le),outputGuardrailResults:i.z.array(pe),currentStep:Ft.optional(),lastModelResponse:se.optional(),generatedItems:i.z.array(ae),lastProcessedResponse:ue.optional(),trace:ie.nullable()});class me{_currentTurn=0;_currentAgent;_originalInput;_modelResponses;_currentAgentSpan;_context;_toolUseTracker;_generatedItems;_maxTurns;_noActiveAgentRun=!0;_lastTurnResponse;_inputGuardrailResults;_outputGuardrailResults;_currentStep=void 0;_lastProcessedResponse=void 0;_trace=null;constructor(t,e,n,r){this._context=t,this._originalInput=structuredClone(e),this._modelResponses=[],this._currentAgentSpan=void 0,this._currentAgent=n,this._toolUseTracker=new Yt,this._generatedItems=[],this._maxTurns=r,this._inputGuardrailResults=[],this._outputGuardrailResults=[],this._trace=(0,o.j3)()}get history(){return _e(this._originalInput,this._generatedItems)}getInterruptions(){return"next_step_interruption"!==this._currentStep?.type?[]:this._currentStep.data.interruptions}approve(t,e={alwaysApprove:!1}){this._context.approveTool(t,e)}reject(t,e={alwaysReject:!1}){this._context.rejectTool(t,e)}toJSON(){const t={$schemaVersion:te,currentTurn:this._currentTurn,currentAgent:{name:this._currentAgent.name},originalInput:this._originalInput,modelResponses:this._modelResponses.map(t=>({usage:{requests:t.usage.requests,inputTokens:t.usage.inputTokens,outputTokens:t.usage.outputTokens,totalTokens:t.usage.totalTokens},output:t.output,responseId:t.responseId,providerData:t.providerData})),context:this._context.toJSON(),toolUseTracker:this._toolUseTracker.toJSON(),maxTurns:this._maxTurns,currentAgentSpan:this._currentAgentSpan?.toJSON(),noActiveAgentRun:this._noActiveAgentRun,inputGuardrailResults:this._inputGuardrailResults,outputGuardrailResults:this._outputGuardrailResults.map(t=>({...t,agent:t.agent.toJSON()})),currentStep:this._currentStep,lastModelResponse:this._lastTurnResponse,generatedItems:this._generatedItems.map(t=>t.toJSON()),lastProcessedResponse:this._lastProcessedResponse,trace:this._trace?this._trace.toJSON():null},e=de.safeParse(t);if(!e.success)throw new y._N(`Failed to serialize run state. ${e.error.message}`);return e.data}toString(){return JSON.stringify(this.toJSON())}static async fromString(t,e){const[n,r]=await(0,jt.V)(()=>JSON.parse(e));if(n)throw new y.yo(`Failed to parse run state. ${n instanceof Error?n.message:String(n)}`);const o=r.$schemaVersion;if(!o)throw new y.yo("Run state is missing schema version");if(o!==te)throw new y.yo(`Run state schema version ${o} is not supported. Please use version ${te}`);const s=de.parse(JSON.parse(e)),a=function(t){const e=new Map,n=[t];for(;n.length>0;){const t=n.shift();if(!e.has(t.name)){e.set(t.name,t);for(const r of t.handoffs)r instanceof Se?e.has(r.name)||n.push(r):r.agent&&(e.has(r.agent.name)||n.push(r.agent))}}return e}(t),i=new gt(s.context.context);i._rebuildApprovals(s.context.approvals);const u=a.get(s.currentAgent.name);if(!u)throw new y.yo(`Agent ${s.currentAgent.name} not found`);const c=new me(i,"",u,s.maxTurns);c._currentTurn=s.currentTurn,c._toolUseTracker=new Yt;for(const[t,e]of Object.entries(s.toolUseTracker))c._toolUseTracker.addToolUse(a.get(t),e);if(s.currentAgentSpan){s.trace||b.Ay.warn("Trace is not set, skipping tracing setup");const t=(0,Xt.A)().createTrace({traceId:s.trace?.id,name:s.trace?.workflow_name,groupId:s.trace?.group_id??void 0,metadata:s.trace?.metadata});c._currentAgentSpan=ge(t,s.currentAgentSpan),c._trace=t}return c._noActiveAgentRun=s.noActiveAgentRun,c._inputGuardrailResults=s.inputGuardrailResults,c._outputGuardrailResults=s.outputGuardrailResults.map(t=>({...t,agent:a.get(t.agent.name)})),c._currentStep=s.currentStep,c._originalInput=s.originalInput,c._modelResponses=s.modelResponses.map(he),c._lastTurnResponse=s.lastModelResponse?he(s.lastModelResponse):void 0,c._generatedItems=s.generatedItems.map(t=>fe(t,a)),c._lastProcessedResponse=s.lastProcessedResponse?await async function(t,e,n,r){const o=await e.getAllTools(n),s=new Map(o.filter(t=>"function"===t.type).map(t=>[t.name,t])),a=new Map(o.filter(t=>"computer"===t.type).map(t=>[t.name,t])),i=new Map(e.handoffs.map(t=>t instanceof Se?[t.name,x(t)]:[t.toolName,t])),u={newItems:r.newItems.map(e=>fe(e,t)),toolsUsed:r.toolsUsed,handoffs:r.handoffs.map(t=>{if(!i.has(t.handoff.toolName))throw new y.yo(`Handoff ${t.handoff.toolName} not found`);return{toolCall:t.toolCall,handoff:i.get(t.handoff.toolName)}}),functions:await Promise.all(r.functions.map(async t=>{if(!s.has(t.tool.name))throw new y.yo(`Tool ${t.tool.name} not found`);return{toolCall:t.toolCall,tool:s.get(t.tool.name)}})),computerActions:r.computerActions.map(t=>{const e=t.computer.name;if(!a.has(e))throw new y.yo(`Computer tool ${e} not found`);return{toolCall:t.toolCall,computer:a.get(e)}}),mcpApprovalRequests:(r.mcpApprovalRequests??[]).map(t=>({requestItem:new Ct(t.requestItem.rawItem,e),mcpTool:t.mcpTool}))};return{...u,hasToolsOrApprovalsToRun:()=>u.handoffs.length>0||u.functions.length>0||u.mcpApprovalRequests.length>0||u.computerActions.length>0}}(a,c._currentAgent,c._context,s.lastProcessedResponse):void 0,"next_step_handoff"===s.currentStep?.type&&(c._currentStep={type:"next_step_handoff",newAgent:a.get(s.currentStep.newAgent.name)}),c}}function ge(t,e){const n=e.span_data,r=e.previous_span?ge(t,e.previous_span):void 0,o=(0,Xt.A)().createSpan({spanId:e.id,traceId:e.trace_id,parentId:e.parent_id??void 0,startedAt:e.started_at??void 0,endedAt:e.ended_at??void 0,data:n},t);return o.previousSpan=r,o}function he(t){const e=new mt;return e.requests=t.usage.requests,e.inputTokens=t.usage.inputTokens,e.outputTokens=t.usage.outputTokens,e.totalTokens=t.usage.totalTokens,{usage:e,output:t.output.map(t=>st.parse(t)),responseId:t.responseId,providerData:t.providerData}}function fe(t,e){switch(t.type){case"message_output_item":return new zt(t.rawItem,e.get(t.agent.name));case"tool_call_item":return new xt(t.rawItem,e.get(t.agent.name));case"tool_call_output_item":return new At(t.rawItem,e.get(t.agent.name),t.output);case"reasoning_item":return new It(t.rawItem,e.get(t.agent.name));case"handoff_call_item":return new Tt(t.rawItem,e.get(t.agent.name));case"handoff_output_item":return new St(t.rawItem,e.get(t.sourceAgent.name),e.get(t.targetAgent.name));case"tool_approval_item":return new Ct(t.rawItem,e.get(t.agent.name))}}function ye(t,e){return!t&&(!!e||"enabled_without_data")}function _e(t,e){const n=e.filter(t=>"tool_approval_item"!==t.type).map(t=>t.rawItem);return"string"==typeof t&&(t=[{type:"message",role:"user",content:t}]),[...t,...n]}class ve extends u.Um{config;inputGuardrailDefs;outputGuardrailDefs;constructor(t={}){super(),this.config={modelProvider:t.modelProvider??k(),model:t.model,modelSettings:t.modelSettings,handoffInputFilter:t.handoffInputFilter,inputGuardrails:t.inputGuardrails,outputGuardrails:t.outputGuardrails,tracingDisabled:t.tracingDisabled??!1,traceIncludeSensitiveData:t.traceIncludeSensitiveData??!0,workflowName:t.workflowName??"Agent workflow",traceId:t.traceId,groupId:t.groupId,traceMetadata:t.traceMetadata},this.inputGuardrailDefs=(t.inputGuardrails??[]).map(I),this.outputGuardrailDefs=(t.outputGuardrails??[]).map(T)}async#tt(t,e,n){return(0,v.QL)(async()=>{const r=e instanceof me?e:new me(n.context instanceof gt?n.context:new gt(n.context),e,t,n.maxTurns??10);try{for(;;){const t=void 0!==r._currentAgent.model&&""!==r._currentAgent.model||void 0!==this.config.model&&""!==this.config.model;let e=we(r._currentAgent.model,this.config.model);if("string"==typeof e&&(e=await this.config.modelProvider.getModel(e)),r._currentStep=r._currentStep??{type:"next_step_run_again"},"next_step_interruption"===r._currentStep.type){if(b.Ay.debug("Continuing from interruption"),!r._lastTurnResponse||!r._lastProcessedResponse)throw new y.yo("No model response found in previous state",r);const t=await Zt(r._currentAgent,r._originalInput,r._generatedItems,r._lastTurnResponse,r._lastProcessedResponse,this,r);if(r._toolUseTracker.addToolUse(r._currentAgent,r._lastProcessedResponse.toolsUsed),r._originalInput=t.originalInput,r._generatedItems=t.generatedItems,r._currentStep=t.nextStep,"next_step_interruption"===t.nextStep.type)return new ft(r);continue}if("next_step_run_again"===r._currentStep.type){const s=await r._currentAgent.getEnabledHandoffs(r._context);if(!r._currentAgentSpan){const t=s.map(t=>t.agentName);r._currentAgentSpan=(0,o.M6)({data:{name:r._currentAgent.name,handoffs:t,output_type:r._currentAgent.outputSchemaName}}),r._currentAgentSpan.start(),(0,v.mq)(r._currentAgentSpan)}const a=await r._currentAgent.getAllTools(r._context),i=a.map(t=>_t(t)),u=s.map(t=>vt(t));if(r._currentAgentSpan&&(r._currentAgentSpan.spanData.tools=a.map(t=>t.name)),r._currentTurn++,r._currentTurn>r._maxTurns)throw r._currentAgentSpan?.setError({message:"Max turns exceeded",data:{max_turns:r._maxTurns}}),new y.MP(`Max turns (${r._maxTurns}) exceeded`,r);b.Ay.debug(`Running agent ${r._currentAgent.name} (turn ${r._currentTurn})`),1===r._currentTurn&&await this.#et(r);const c=_e(r._originalInput,r._generatedItems);r._noActiveAgentRun&&(r._currentAgent.emit("agent_start",r._context,r._currentAgent),this.emit("agent_start",r._context,r._currentAgent));let l={...this.config.modelSettings,...r._currentAgent.modelSettings};l=xe(t,r._currentAgent.modelSettings,e,l),l=$t(r._currentAgent,r._toolUseTracker,l),r._lastTurnResponse=await e.getResponse({systemInstructions:await r._currentAgent.getSystemPrompt(r._context),prompt:await r._currentAgent.getPrompt(r._context),input:c,previousResponseId:n.previousResponseId,conversationId:n.conversationId,modelSettings:l,tools:i,outputType:(0,_.IS)(r._currentAgent.outputType),handoffs:u,tracing:ye(this.config.tracingDisabled,this.config.traceIncludeSensitiveData),signal:n.signal}),r._modelResponses.push(r._lastTurnResponse),r._context.usage.add(r._lastTurnResponse.usage),r._noActiveAgentRun=!1;const p=Dt(r._lastTurnResponse,r._currentAgent,a,s);r._lastProcessedResponse=p;const d=await qt(r._currentAgent,r._originalInput,r._generatedItems,r._lastTurnResponse,r._lastProcessedResponse,this,r);r._toolUseTracker.addToolUse(r._currentAgent,r._lastProcessedResponse.toolsUsed),r._originalInput=d.originalInput,r._generatedItems=d.generatedItems,r._currentStep=d.nextStep}if(r._currentStep&&"next_step_final_output"===r._currentStep.type)return await this.#D(r,r._currentStep.output),this.emit("agent_end",r._context,r._currentAgent,r._currentStep.output),r._currentAgent.emit("agent_end",r._context,r._currentStep.output),new ft(r);if(r._currentStep&&"next_step_handoff"===r._currentStep.type)r._currentAgent=r._currentStep.newAgent,r._currentAgentSpan&&(r._currentAgentSpan.end(),(0,v.h6)(),r._currentAgentSpan=void 0),r._noActiveAgentRun=!0,r._currentStep={type:"next_step_run_again"};else{if(r._currentStep&&"next_step_interruption"===r._currentStep.type)return new ft(r);b.Ay.debug("Running next loop")}}}catch(t){throw r._currentAgentSpan&&r._currentAgentSpan.setError({message:"Error in agent run",data:{error:String(t)}}),t}finally{r._currentAgentSpan&&("next_step_interruption"!==r._currentStep?.type&&r._currentAgentSpan.end(),(0,v.h6)())}})}async#et(t){const e=this.inputGuardrailDefs.concat(t._currentAgent.inputGuardrails.map(I));if(e.length>0){const n={agent:t._currentAgent,input:t._originalInput,context:t._context};try{const r=await Promise.all(e.map(async e=>(0,o.cS)(async t=>{const r=await e.run(n);return t.spanData.triggered=r.output.tripwireTriggered,r},{data:{name:e.name}},t._currentAgentSpan)));for(const e of r)if(e.output.tripwireTriggered)throw t._currentAgentSpan&&t._currentAgentSpan.setError({message:"Guardrail tripwire triggered",data:{guardrail:e.guardrail.name}}),new y.Fb(`Input guardrail triggered: ${JSON.stringify(e.output.outputInfo)}`,e,t)}catch(e){if(e instanceof y.Fb)throw e;throw t._currentTurn--,new y.yZ(`Input guardrail failed to complete: ${e}`,e,t)}}}async#D(t,e){const n=this.outputGuardrailDefs.concat(t._currentAgent.outputGuardrails.map(T));if(n.length>0){const r=t._currentAgent.processFinalOutput(e),s={agent:t._currentAgent,agentOutput:r,context:t._context,details:{modelResponse:t._lastTurnResponse}};try{const e=await Promise.all(n.map(async e=>(0,o.cS)(async t=>{const n=await e.run(s);return t.spanData.triggered=n.output.tripwireTriggered,n},{data:{name:e.name}},t._currentAgentSpan)));for(const n of e)if(n.output.tripwireTriggered)throw t._currentAgentSpan&&t._currentAgentSpan.setError({message:"Guardrail tripwire triggered",data:{guardrail:n.guardrail.name}}),new y.K6(`Output guardrail triggered: ${JSON.stringify(n.output.outputInfo)}`,n,t)}catch(e){if(e instanceof y.K6)throw e;throw new y.yZ(`Output guardrail failed to complete: ${e}`,e,t)}}}async#nt(t,e){try{for(;;){const n=t.state._currentAgent,r=await n.getEnabledHandoffs(t.state._context),s=await n.getAllTools(t.state._context),a=s.map(t=>_t(t)),i=r.map(t=>vt(t));if(t.state._currentStep=t.state._currentStep??{type:"next_step_run_again"},"next_step_interruption"===t.state._currentStep.type){if(b.Ay.debug("Continuing from interruption"),!t.state._lastTurnResponse||!t.state._lastProcessedResponse)throw new y.yo("No model response found in previous state",t.state);const e=await Zt(t.state._currentAgent,t.state._originalInput,t.state._generatedItems,t.state._lastTurnResponse,t.state._lastProcessedResponse,this,t.state);if(Qt(t,e),t.state._toolUseTracker.addToolUse(t.state._currentAgent,t.state._lastProcessedResponse.toolsUsed),t.state._originalInput=e.originalInput,t.state._generatedItems=e.generatedItems,t.state._currentStep=e.nextStep,"next_step_interruption"===e.nextStep.type)return;continue}if("next_step_run_again"===t.state._currentStep.type){if(!t.state._currentAgentSpan){const e=r.map(t=>t.agentName);t.state._currentAgentSpan=(0,o.M6)({data:{name:n.name,handoffs:e,tools:s.map(t=>t.name),output_type:n.outputSchemaName}}),t.state._currentAgentSpan.start(),(0,v.mq)(t.state._currentAgentSpan)}if(t.state._currentTurn++,t.state._currentTurn>t.state._maxTurns)throw t.state._currentAgentSpan?.setError({message:"Max turns exceeded",data:{max_turns:t.state._maxTurns}}),new y.MP(`Max turns (${t.state._maxTurns}) exceeded`,t.state);b.Ay.debug(`Running agent ${n.name} (turn ${t.state._currentTurn})`);const u=void 0!==n.model&&""!==n.model||void 0!==this.config.model&&""!==this.config.model;let c=we(n.model,this.config.model);"string"==typeof c&&(c=await this.config.modelProvider.getModel(c)),1===t.state._currentTurn&&await this.#et(t.state);let l={...this.config.modelSettings,...n.modelSettings};l=xe(u,n.modelSettings,c,l),l=$t(n,t.state._toolUseTracker,l);const p=_e(t.input,t.newItems);let d;t.state._noActiveAgentRun&&(n.emit("agent_start",t.state._context,n),this.emit("agent_start",t.state._context,n));for await(const r of c.getStreamedResponse({systemInstructions:await n.getSystemPrompt(t.state._context),prompt:await n.getPrompt(t.state._context),input:p,previousResponseId:e.previousResponseId,conversationId:e.conversationId,modelSettings:l,tools:a,handoffs:i,outputType:(0,_.IS)(n.outputType),tracing:ye(this.config.tracingDisabled,this.config.traceIncludeSensitiveData),signal:e.signal})){if("response_done"===r.type){const t=lt.parse(r);d={usage:new mt(t.response.usage),output:t.response.output,responseId:t.response.id}}if(t.cancelled)return;t._addItem(new Ot(r))}if(t.state._noActiveAgentRun=!1,!d)throw new y.af("Model did not produce a final response!",t.state);t.state._lastTurnResponse=d,t.state._modelResponses.push(t.state._lastTurnResponse);const m=Dt(t.state._lastTurnResponse,n,s,r);t.state._lastProcessedResponse=m;const g=new Set(m.newItems);g.size>0&&Vt(t,m.newItems);const h=await qt(n,t.state._originalInput,t.state._generatedItems,t.state._lastTurnResponse,t.state._lastProcessedResponse,this,t.state);Qt(t,h,{skipItems:g}),t.state._toolUseTracker.addToolUse(n,m.toolsUsed),t.state._originalInput=h.originalInput,t.state._generatedItems=h.generatedItems,t.state._currentStep=h.nextStep}if("next_step_final_output"===t.state._currentStep.type)return await this.#D(t.state,t.state._currentStep.output),this.emit("agent_end",t.state._context,n,t.state._currentStep.output),void n.emit("agent_end",t.state._context,t.state._currentStep.output);if("next_step_interruption"===t.state._currentStep.type)return;"next_step_handoff"===t.state._currentStep.type?(t.state._currentAgent=t.state._currentStep?.newAgent,t.state._currentAgentSpan&&(t.state._currentAgentSpan.end(),(0,v.h6)()),t.state._currentAgentSpan=void 0,t._addItem(new Nt(t.state._currentAgent)),t.state._noActiveAgentRun=!0,t.state._currentStep={type:"next_step_run_again"}):b.Ay.debug("Running next loop")}}catch(e){throw t.state._currentAgentSpan&&t.state._currentAgentSpan.setError({message:"Error in agent run",data:{error:String(e)}}),e}finally{t.state._currentAgentSpan&&("next_step_interruption"!==t.state._currentStep?.type&&t.state._currentAgentSpan.end(),(0,v.h6)())}}async#rt(t,e,n){return n=n??{},(0,v.QL)(async()=>{const r=e instanceof me?e:new me(n.context instanceof gt?n.context:new gt(n.context),e,t,n.maxTurns??10),o=new yt({signal:n.signal,state:r});return o.maxTurns=n.maxTurns??r._maxTurns,this.#nt(o,n).then(()=>{o._done()},t=>{o._raiseError(t)}),o})}run(t,e,n={stream:!1,context:void 0}){return e instanceof me&&e._trace?(0,v.SZ)(e._trace,async()=>(e._currentAgentSpan&&(0,v.mq)(e._currentAgentSpan),n?.stream?this.#rt(t,e,n):this.#tt(t,e,n))):(0,v.Nn)(async()=>n?.stream?this.#rt(t,e,n):this.#tt(t,e,n),{traceId:this.config.traceId,name:this.config.workflowName,groupId:this.config.groupId,metadata:this.config.traceMetadata})}}let be;function we(t,e){return"string"==typeof t&&t!==Se.DEFAULT_MODEL_PLACEHOLDER||t?t:e??t??Se.DEFAULT_MODEL_PLACEHOLDER}async function ze(t,e,n){const r=be||(be=new ve,be);return await r.run(t,e,n)}function xe(t,e,n,r){if(m()&&t&&("string"!=typeof n||!d(n))&&(e.providerData?.reasoning||e.providerData?.text?.verbosity||e.providerData?.reasoning_effort)){const t={...r};return delete t.providerData?.reasoning,delete t.providerData?.text?.verbosity,delete t.providerData?.reasoning_effort,t.reasoning&&(delete t.reasoning.effort,delete t.reasoning.summary),t.text&&delete t.text.verbosity,t}return r}var Ae=n(9520);const Ie=new WeakMap,Te=i.z.object({input:i.z.string()});class Se extends u.u9{static create(t){return new Se({...t,handoffs:t.handoffs,outputType:t.outputType,handoffOutputTypeWarningEnabled:!1})}static DEFAULT_MODEL_PLACEHOLDER="";name;instructions;prompt;handoffDescription;handoffs;model;modelSettings;tools;mcpServers;inputGuardrails;outputGuardrails;outputType="text";toolUseBehavior;resetToolChoice;constructor(t){if(super(),"string"!=typeof t.name||""===t.name.trim())throw new y.yo("Agent must have a name.");if(this.name=t.name,this.instructions=t.instructions??Se.DEFAULT_MODEL_PLACEHOLDER,this.prompt=t.prompt,this.handoffDescription=t.handoffDescription??"",this.handoffs=t.handoffs??[],this.model=t.model??"",this.modelSettings=t.modelSettings??h(),this.tools=t.tools??[],this.mcpServers=t.mcpServers??[],this.inputGuardrails=t.inputGuardrails??[],this.outputGuardrails=t.outputGuardrails??[],t.outputType&&(this.outputType=t.outputType),this.toolUseBehavior=t.toolUseBehavior??"run_llm_again",this.resetToolChoice=t.resetToolChoice??!0,void 0===t.model||!m()||"string"==typeof t.model&&d(t.model)||void 0!==t.modelSettings||(this.modelSettings={}),(void 0===t.handoffOutputTypeWarningEnabled||t.handoffOutputTypeWarningEnabled)&&this.handoffs&&this.outputType){const t=new Set([JSON.stringify(this.outputType)]);for(const e of this.handoffs)"outputType"in e&&e.outputType?t.add(JSON.stringify(e.outputType)):"agent"in e&&e.agent.outputType&&t.add(JSON.stringify(e.agent.outputType));t.size>1&&b.Ay.warn(`[Agent] Warning: Handoff agents have different output types: ${Array.from(t).join(", ")}. You can make it type-safe by using Agent.create({ ... }) method instead.`)}}get outputSchemaName(){if("text"===this.outputType)return"text";if((0,Ae.f)(this.outputType))return"ZodOutput";if("object"==typeof this.outputType)return this.outputType.name;throw new Error(`Unknown output type: ${this.outputType}`)}clone(t){return new Se({...this,...t})}asTool(t){const{toolName:e,toolDescription:n,customOutputExtractor:r,needsApproval:o,runConfig:s,runOptions:a,isEnabled:i}=t;return(0,f.z6)({name:e??(0,_.Tl)(this.name),description:n??"",parameters:Te,strict:!0,needsApproval:o,isEnabled:i,execute:async(t,e,n)=>{if(!(0,Ae.A)(t))throw new y.af("Agent tool called with invalid input");const o=new ve(s??{}),i=await o.run(this,t.input,{context:e,...a??{}}),u="object"==typeof this.toolUseBehavior&&null!==this.toolUseBehavior&&"stopAtToolNames"in this.toolUseBehavior;"function"!=typeof r&&u&&b.Ay.debug(`You're passing the agent (name: ${this.name}) with toolUseBehavior.stopAtToolNames configured as a tool to a different agent; this may not work as you expect. You may want to have a wrapper function tool to consistently return the final output.`);const c="function"==typeof r?await r(i):0===(l=i.rawResponses[i.rawResponses.length-1]).output.length?"":Pt(l.output[l.output.length-1])||"";var l,p,d;return n?.toolCall&&(d=i,(p=n.toolCall)&&Ie.set(p,d)),c}})}async getSystemPrompt(t){return"function"==typeof this.instructions?await this.instructions(t,this):this.instructions}async getPrompt(t){return"function"==typeof this.prompt?await this.prompt(t,this):this.prompt}async getMcpTools(t){return this.mcpServers.length>0?(0,c.Ph)({mcpServers:this.mcpServers,runContext:t,agent:this,convertSchemasToStrict:!1}):[]}async getAllTools(t){const e=await this.getMcpTools(t),n=[];for(const e of this.tools){if("function"===e.type){const n=e.isEnabled;if(!("function"==typeof n?await n(t,this):"boolean"!=typeof n||n))continue}n.push(e)}return[...e,...n]}async getEnabledHandoffs(t){const e=this.handoffs?.map(t=>A(t))??[],n=[];for(const r of e)await r.isEnabled({runContext:t,agent:this})&&n.push(r);return n}processFinalOutput(t){if("text"===this.outputType)return t;if("object"==typeof this.outputType){const e=JSON.parse(t);return(0,Ae.f)(this.outputType)?this.outputType.parse(e):e}throw new Error(`Unknown output type: ${this.outputType}`)}toJSON(){return{name:this.name}}}function Ce(t,e){return{type:"message",role:"user",content:"string"==typeof t?[{type:"input_text",text:t}]:t,providerData:e}}function ke(t,e){return{type:"message",role:"system",content:t,providerData:e}}function Pe(t,e){return{type:"message",role:"assistant",content:"string"==typeof t?[{type:"output_text",text:t}]:t,status:"completed",providerData:e}}function Ee(t){if(!t?.allowed&&!t?.blocked)return;const e={};return t?.allowed&&(e.allowedToolNames=t.allowed),t?.blocked&&(e.blockedToolNames=t.blocked),e}(0,o.VP)((0,s.mh)())},6170:(t,e,n)=>{"use strict";function r(t){if(null==t)return String(t);if("string"==typeof t)return t;if("object"==typeof t)try{return JSON.stringify(t)}catch(t){return"[object with circular references]"}return String(t)}n.d(e,{I:()=>r})},6201:(t,e,n)=>{"use strict";n.d(e,{Du:()=>c,Fb:()=>l,K6:()=>p,MP:()=>s,_N:()=>o,af:()=>a,pf:()=>r,yZ:()=>u,yo:()=>i});class r extends Error{state;constructor(t,e){super(t),this.state=e}}class o extends r{}class s extends r{}class a extends r{}class i extends r{}class u extends r{error;constructor(t,e,n){super(t,n),this.error=e}}class c extends r{error;constructor(t,e,n){super(t,n),this.error=e}}class l extends r{result;constructor(t,e,n){super(t,n),this.result=e}}class p extends r{result;constructor(t,e,n){super(t,n),this.result=e}}},6585:t=>{var e=1e3,n=60*e,r=60*n,o=24*r,s=7*o;function a(t,e,n,r){var o=e>=1.5*n;return Math.round(t/n)+" "+r+(o?"s":"")}t.exports=function(t,i){i=i||{};var u,c,l=typeof t;if("string"===l&&t.length>0)return function(t){if(!((t=String(t)).length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(a){var i=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*i;case"weeks":case"week":case"w":return i*s;case"days":case"day":case"d":return i*o;case"hours":case"hour":case"hrs":case"hr":case"h":return i*r;case"minutes":case"minute":case"mins":case"min":case"m":return i*n;case"seconds":case"second":case"secs":case"sec":case"s":return i*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}}}(t);if("number"===l&&isFinite(t))return i.long?(u=t,(c=Math.abs(u))>=o?a(u,c,o,"day"):c>=r?a(u,c,r,"hour"):c>=n?a(u,c,n,"minute"):c>=e?a(u,c,e,"second"):u+" ms"):function(t){var s=Math.abs(t);return s>=o?Math.round(t/o)+"d":s>=r?Math.round(t/r)+"h":s>=n?Math.round(t/n)+"m":s>=e?Math.round(t/e)+"s":t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},7020:(t,e,n)=>{"use strict";n.d(e,{ZF:()=>a,bR:()=>u,el:()=>s,n9:()=>o,uA:()=>i});var r=n(341);function o(){return(new Date).toISOString()}function s(){return`trace_${(0,r.N4)().replace(/-/g,"")}`}function a(){return`span_${(0,r.N4)().replace(/-/g,"").slice(0,24)}`}function i(){return`group_${(0,r.N4)().replace(/-/g,"").slice(0,24)}`}function u(t){return Object.fromEntries(Object.entries(t).filter(([t])=>!t.startsWith("_")))}},7036:(t,e,n)=>{"use strict";n.d(e,{RA:()=>r.RA,cH:()=>r.cH,k5:()=>r.k5,pf:()=>r.pf,qA:()=>r.qA,vc:()=>r.vc});var r=n(2588)},7755:(t,e,n)=>{"use strict";n.d(e,{AF:()=>i,VD:()=>a,mh:()=>p,qQ:()=>u});var r=n(3004),o=n(341),s=n(5786);class a{async export(t){if(s.zR.disabled)r.Ay.debug("Tracing is disabled. Skipping export");else for(const e of t)"trace"===e.type?console.log(`[Exporter] Export trace traceId=${e.traceId} name=${e.name}${e.groupId?` groupId=${e.groupId}`:""}`):console.log(`[Exporter] Export span: ${JSON.stringify(e)}`)}}class i{#ot;#st;#at;#it;#ut;#ct=[];#lt;#pt=null;#dt=!1;#mt=null;constructor(t,{maxQueueSize:e=1e3,maxBatchSize:n=100,scheduleDelay:s=5e3,exportTriggerRatio:a=.8}={}){this.#ot=e,this.#st=n,this.#at=s,this.#it=e*a,this.#ut=t,this.#lt=o.O1,(0,o.am)()?this.start():r.Ay.debug("Automatic trace export loop is not supported in this environment. You need to manually call `getGlobalTraceProvider().forceFlush()` to export traces.")}start(){this.#mt=new AbortController,this.#gt()}async#ht(t){this.#ct.length+1>this.#ot?r.Ay.error("Dropping trace because buffer is full"):(this.#ct.push(t),this.#ct.length>this.#it&&await this.#ft())}#gt(){this.#pt=this.#lt.setTimeout(async()=>{await this.#ft(),this.#gt()},this.#at),"function"==typeof this.#pt.unref&&this.#pt.unref()}async#ft(t=!1){if(0!==this.#ct.length)if(r.Ay.debug(`Exporting batches. Force: ${t}. Buffer size: ${this.#ct.length}`),t||this.#ct.length<this.#st){const t=[...this.#ct];this.#ct=[],this.#dt=!0,await this.#ut.export(t),this.#dt=!1}else if(this.#ct.length>0){const t=this.#ct.splice(0,this.#st);this.#dt=!0,await this.#ut.export(t),this.#dt=!1}}async onTraceStart(t){await this.#ht(t)}async onTraceEnd(t){}async onSpanStart(t){}async onSpanEnd(t){await this.#ht(t)}async shutdown(t){for(t&&this.#lt.setTimeout(()=>{this.#mt?.abort()},t),r.Ay.debug("Shutting down gracefully");this.#ct.length>0;){if(r.Ay.debug(`Waiting for buffer to empty. Items left: ${this.#ct.length}`),this.#dt||await this.#ft(!0),this.#mt?.signal.aborted){r.Ay.debug("Timeout reached, force flushing"),await this.#ft(!0);break}await new Promise(t=>this.#lt.setTimeout(t,500))}r.Ay.debug("Buffer empty. Exiting"),this.#lt&&this.#pt&&this.#lt.clearTimeout(this.#pt)}async forceFlush(){this.#ct.length>0&&await this.#ft(!0)}}class u{#yt=[];start(){for(const t of this.#yt)t.start&&t.start()}addTraceProcessor(t){this.#yt.push(t)}setProcessors(t){r.Ay.debug("Shutting down old processors");for(const t of this.#yt)t.shutdown();this.#yt=t}async onTraceStart(t){for(const e of this.#yt)await e.onTraceStart(t)}async onTraceEnd(t){for(const e of this.#yt)await e.onTraceEnd(t)}async onSpanStart(t){for(const e of this.#yt)await e.onSpanStart(t)}async onSpanEnd(t){for(const e of this.#yt)await e.onSpanEnd(t)}async shutdown(t){for(const e of this.#yt)await e.shutdown(t)}async forceFlush(){for(const t of this.#yt)await t.forceFlush()}}let c=null,l=null;function p(){return l||(l=new i((c||(c=new a),c))),l}},7780:(t,e,n)=>{"use strict";n.d(e,{L:()=>s,f:()=>a});var r=n(3004),o=n(7020);class s{type="trace.span";#_t;#vt;#bt;#wt;#q;#zt;#xt;#G;#At;constructor(t,e){this.#vt=t.traceId,this.#bt=t.spanId??(0,o.ZF)(),this.#_t=t.data,this.#q=e,this.#wt=t.parentId??null,this.#G=t.error??null,this.#zt=t.startedAt??null,this.#xt=t.endedAt??null}get traceId(){return this.#vt}get spanData(){return this.#_t}get spanId(){return this.#bt}get parentId(){return this.#wt}get previousSpan(){return this.#At}set previousSpan(t){this.#At=t}start(){this.#zt?r.Ay.warn("Span already started"):(this.#zt=(0,o.n9)(),this.#q.onSpanStart(this))}end(){this.#xt?r.Ay.debug("Span already finished",this.spanData):(this.#xt=(0,o.n9)(),this.#q.onSpanEnd(this))}setError(t){this.#G=t}get error(){return this.#G}get startedAt(){return this.#zt}get endedAt(){return this.#xt}clone(){const t=new s({traceId:this.traceId,spanId:this.spanId,parentId:this.parentId??void 0,data:this.spanData,startedAt:this.#zt??void 0,endedAt:this.#xt??void 0,error:this.#G??void 0},this.#q);return t.previousSpan=this.previousSpan?.clone(),t}toJSON(){return{object:this.type,id:this.spanId,trace_id:this.traceId,parent_id:this.parentId,started_at:this.startedAt,ended_at:this.endedAt,span_data:(0,o.bR)(this.spanData),error:this.error}}}class a extends s{constructor(t,e){super({traceId:"no-op",spanId:"no-op",data:t},e)}start(){}end(){}setError(){}toJSON(){return null}}},7788:(t,e,n)=>{"use strict";n.d(e,{Ar:()=>p,Dg:()=>d,Ph:()=>b,W4:()=>m,Wm:()=>h,l6:()=>g,p2:()=>f,qi:()=>_,y6:()=>w});var r=n(5738),o=n(6201),s=n(341),a=n(9463),i=n(3004),u=n(7833),c=n.n(u),l=n(4231);class p{cacheToolsList;_cachedTools=void 0;toolFilter;logger;constructor(t){this.logger=t.logger??(0,i.tZ)("openai-agents:stdio-mcp-client"),this.cacheToolsList=t.cacheToolsList??!1,this.toolFilter=t.toolFilter}debugLog(t){c().enabled(this.logger.namespace)&&this.logger.debug(t())}}class d{cacheToolsList;_cachedTools=void 0;toolFilter;logger;constructor(t){this.logger=t.logger??(0,i.tZ)("openai-agents:streamable-http-mcp-client"),this.cacheToolsList=t.cacheToolsList??!1,this.toolFilter=t.toolFilter}debugLog(t){c().enabled(this.logger.namespace)&&this.logger.debug(t())}}class m{cacheToolsList;_cachedTools=void 0;toolFilter;logger;constructor(t){this.logger=t.logger??(0,i.tZ)("openai-agents:sse-mcp-client"),this.cacheToolsList=t.cacheToolsList??!1,this.toolFilter=t.toolFilter}debugLog(t){c().enabled(this.logger.namespace)&&this.logger.debug(t())}}l.z.object({name:l.z.string(),description:l.z.string().optional(),inputSchema:l.z.object({type:l.z.literal("object"),properties:l.z.record(l.z.string(),l.z.any()),required:l.z.array(l.z.string()),additionalProperties:l.z.boolean()})});class g extends p{underlying;constructor(t){super(t),this.underlying=new s.l6(t)}get name(){return this.underlying.name}connect(){return this.underlying.connect()}close(){return this.underlying.close()}async listTools(){if(this.cacheToolsList&&this._cachedTools)return this._cachedTools;const t=await this.underlying.listTools();return this.cacheToolsList&&(this._cachedTools=t),t}callTool(t,e){return this.underlying.callTool(t,e)}invalidateToolsCache(){return this.underlying.invalidateToolsCache()}}class h extends d{underlying;constructor(t){super(t),this.underlying=new s.Wm(t)}get name(){return this.underlying.name}connect(){return this.underlying.connect()}close(){return this.underlying.close()}async listTools(){if(this.cacheToolsList&&this._cachedTools)return this._cachedTools;const t=await this.underlying.listTools();return this.cacheToolsList&&(this._cachedTools=t),t}callTool(t,e){return this.underlying.callTool(t,e)}invalidateToolsCache(){return this.underlying.invalidateToolsCache()}}class f extends m{underlying;constructor(t){super(t),this.underlying=new s.p2(t)}get name(){return this.underlying.name}connect(){return this.underlying.connect()}close(){return this.underlying.close()}async listTools(){if(this.cacheToolsList&&this._cachedTools)return this._cachedTools;const t=await this.underlying.listTools();return this.cacheToolsList&&(this._cachedTools=t),t}callTool(t,e){return this.underlying.callTool(t,e)}invalidateToolsCache(){return this.underlying.invalidateToolsCache()}}const y={};async function _(t){delete y[t]}async function v({server:t,convertSchemasToStrict:e,runContext:n,agent:r}){return t.cacheToolsList&&y[t.name]?y[t.name].map(n=>w(n,t,e)):(0,a.cW)(async o=>{const s=await t.listTools();let a=s;if(n&&r){const e={runContext:n,agent:r,serverName:t.name},o=[];for(const n of s){const r=t.toolFilter;if(r)if("function"==typeof r){if(!await r(e,n)){i.vF.debug(`MCP Tool (server: ${t.name}, tool: ${n.name}) is blocked by the callable filter.`);continue}}else{const e=r.allowedToolNames??[],o=r.blockedToolNames??[];if(e.length>0||o.length>0){const r=!(e.length>0)||e.includes(n.name),s=o.length>0&&o.includes(n.name);if(!r||s){s?i.vF.debug(`MCP Tool (server: ${t.name}, tool: ${n.name}) is blocked by the static filter.`):r||i.vF.debug(`MCP Tool (server: ${t.name}, tool: ${n.name}) is not allowed by the static filter.`);continue}}}o.push(n)}a=o}o.spanData.result=a.map(t=>t.name);const u=a.map(n=>w(n,t,e));return t.cacheToolsList&&(y[t.name]=a),u},{data:{server:t.name}})}async function b(t,e,n,r=!1){const s=Array.isArray(t)?{mcpServers:t,runContext:e,agent:n,convertSchemasToStrict:r}:t,{mcpServers:a,convertSchemasToStrict:i=!1,runContext:u,agent:c}=s,l=[],p=new Set;for(const t of a){const e=await v({server:t,convertSchemasToStrict:i,runContext:u,agent:c}),n=[...new Set(e.map(t=>t.name))].filter(t=>p.has(t));if(n.length>0)throw new o.yo(`Duplicate tool names found across MCP servers: ${n.join(", ")}`);for(const t of e)p.add(t.name),l.push(t)}return l}function w(t,e,n){async function o(n,r){let o={};"string"==typeof n&&n?o=JSON.parse(n):"object"==typeof n&&null!=n&&(o=n);const s=(0,a.YP)();s&&(s.spanData.mcp_data={server:e.name});const i=await e.callTool(t.name,o);return 1===i.length?i[0]:i}const s={...t.inputSchema,type:t.inputSchema?.type??"object",properties:t.inputSchema?.properties??{},required:t.inputSchema?.required??[],additionalProperties:t.inputSchema?.additionalProperties??!1};if(n||!0===s.additionalProperties)try{const e=function(t){const e={...t,additionalProperties:!1};return e.required||(e.required=[]),e}(s);return(0,r.z6)({name:t.name,description:t.description||"",parameters:e,strict:!0,execute:o})}catch(t){i.vF.warn(`Error converting MCP schema to strict mode: ${t}`)}const u={...s,additionalProperties:!0};return(0,r.z6)({name:t.name,description:t.description||"",parameters:u,strict:!1,execute:o})}},7833:(t,e,n)=>{var r=n(5606);e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,t=>{"%%"!==t&&(r++,"%c"===t&&(o=r))}),e.splice(o,0,n)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(t){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(t){}return!t&&void 0!==r&&"env"in r&&(t=r.env.DEBUG),t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(t){}}(),e.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=n(736)(e);const{formatters:o}=t.exports;o.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},7962:(t,e,n)=>{"use strict";n.d(e,{ID:()=>o.I,Ko:()=>s.Ko,f3:()=>r.f});var r=n(9520),o=n(6170),s=n(5316)},8326:(t,e,n)=>{"use strict";async function r(t){try{return[null,await t()]}catch(t){return[t,null]}}n.d(e,{V:()=>r})},9352:(t,e,n)=>{"use strict";n.d(e,{IS:()=>Z,AW:()=>$,Tl:()=>L});var r=n(9731);const o=Symbol("Let zodToJsonSchema decide on which parser to use"),s={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},a=t=>"_def"in t?t._def:t;var i=n(9661);function u(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function c(t,e,n,r,o){t[e]=n,u(t,e,r,o)}function l(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>l(t,e,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return p(t,e)}}const p=(t,e)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===e.target)return n;for(const r of t.checks)switch(r.kind){case"min":c(n,"minimum",r.value,r.message,e);break;case"max":c(n,"maximum",r.value,r.message,e)}return n};let d;const m=/^[cC][^\s-]{8,}$/,g=/^[0-9a-z]+$/,h=/^[0-9A-HJKMNP-TV-Z]{26}$/,f=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,y=()=>(void 0===d&&(d=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),d),_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,v=/^[a-zA-Z0-9_-]{21}$/;function b(t,e){const n={type:"string"};function r(t){return"escape"===e.patternStrategy?w(t):t}if(t.checks)for(const o of t.checks)switch(o.kind){case"min":c(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,o.value):o.value,o.message,e);break;case"max":c(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":z(n,"email",o.message,e);break;case"format:idn-email":z(n,"idn-email",o.message,e);break;case"pattern:zod":x(n,f,o.message,e)}break;case"url":z(n,"uri",o.message,e);break;case"uuid":z(n,"uuid",o.message,e);break;case"regex":x(n,o.regex,o.message,e);break;case"cuid":x(n,m,o.message,e);break;case"cuid2":x(n,g,o.message,e);break;case"startsWith":x(n,RegExp(`^${r(o.value)}`),o.message,e);break;case"endsWith":x(n,RegExp(`${r(o.value)}$`),o.message,e);break;case"datetime":z(n,"date-time",o.message,e);break;case"date":z(n,"date",o.message,e);break;case"time":z(n,"time",o.message,e);break;case"duration":z(n,"duration",o.message,e);break;case"length":c(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,o.value):o.value,o.message,e),c(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,o.value):o.value,o.message,e);break;case"includes":x(n,RegExp(r(o.value)),o.message,e);break;case"ip":"v6"!==o.version&&z(n,"ipv4",o.message,e),"v4"!==o.version&&z(n,"ipv6",o.message,e);break;case"emoji":x(n,y,o.message,e);break;case"ulid":x(n,h,o.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":z(n,"binary",o.message,e);break;case"contentEncoding:base64":c(n,"contentEncoding","base64",o.message,e);break;case"pattern:zod":x(n,_,o.message,e)}break;case"nanoid":x(n,v,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:(()=>{})()}return n}const w=t=>Array.from(t).map(t=>/[a-zA-Z0-9]/.test(t)?t:`\\${t}`).join(""),z=(t,e,n,r)=>{t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):c(t,"format",e,n,r)},x=(t,e,n,r)=>{t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.allOf.push({pattern:A(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):c(t,"pattern",A(e,r),n,r)},A=(t,e)=>{const n="function"==typeof t?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const r=n.flags.includes("i"),o=n.flags.includes("m"),s=n.flags.includes("s"),a=r?n.source.toLowerCase():n.source;let i="",u=!1,c=!1,l=!1;for(let t=0;t<a.length;t++)if(u)i+=a[t],u=!1;else{if(r)if(c){if(a[t].match(/[a-z]/)){l?(i+=a[t],i+=`${a[t-2]}-${a[t]}`.toUpperCase(),l=!1):"-"===a[t+1]&&a[t+2]?.match(/[a-z]/)?(i+=a[t],l=!0):i+=`${a[t]}${a[t].toUpperCase()}`;continue}}else if(a[t].match(/[a-z]/)){i+=`[${a[t]}${a[t].toUpperCase()}]`;continue}if(o){if("^"===a[t]){i+="(^|(?<=[\r\n]))";continue}if("$"===a[t]){i+="($|(?=[\r\n]))";continue}}s&&"."===a[t]?i+=c?`${a[t]}\r\n`:`[${a[t]}\r\n]`:(i+=a[t],"\\"===a[t]?u=!0:c&&"]"===a[t]?c=!1:c||"["!==a[t]||(c=!0))}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return i};function I(t,e){if("openApi3"===e.target&&t.keyType?._def.typeName===i.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,r)=>({...n,[r]:k(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:k(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if("openApi3"===e.target)return n;if(t.keyType?._def.typeName===i.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){const r=Object.entries(b(t.keyType._def,e)).reduce((t,[e,n])=>"type"===e?t:{...t,[e]:n},{});return{...n,propertyNames:r}}return t.keyType?._def.typeName===i.ZodFirstPartyTypeKind.ZodEnum?{...n,propertyNames:{enum:t.keyType._def.values}}:n}const T={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},S=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((t,n)=>k(t._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(t=>!!t&&(!e.strictUnions||"object"==typeof t&&Object.keys(t).length>0));return n.length?{anyOf:n}:void 0};function C(t,e){return"strict"===e.removeAdditionalStrategy?"ZodNever"===t.catchall._def.typeName?"strict"!==t.unknownKeys:k(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:"ZodNever"===t.catchall._def.typeName?"passthrough"===t.unknownKeys:k(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function k(t,e,n=!1){const r=e.seen.get(t);if(e.override){const s=e.override?.(t,e,r,n);if(s!==o)return s}if(r&&!n){const t=P(r,e);if(void 0!==t)return"$ref"in t&&e.seenRefs.add(t.$ref),t}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=j(t,t.typeName,e,n);return a&&O(t,e,a),s.jsonSchema=a,a}const P=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&"duplicate-ref"===e.nameStrategy&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:E(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):"seen"===e.$refStrategy?{}:void 0}},E=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},j=(t,e,n,r)=>{switch(e){case i.ZodFirstPartyTypeKind.ZodString:return b(t,n);case i.ZodFirstPartyTypeKind.ZodNumber:return function(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",u(n,"type",r.message,e);break;case"min":"jsonSchema7"===e.target?r.inclusive?c(n,"minimum",r.value,r.message,e):c(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),c(n,"minimum",r.value,r.message,e));break;case"max":"jsonSchema7"===e.target?r.inclusive?c(n,"maximum",r.value,r.message,e):c(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),c(n,"maximum",r.value,r.message,e));break;case"multipleOf":c(n,"multipleOf",r.value,r.message,e)}return n}(t,n);case i.ZodFirstPartyTypeKind.ZodObject:return function(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((t,[n,r])=>{if(void 0===r||void 0===r._def)return t;const o=[...e.currentPath,"properties",n],s=k(r._def,{...e,currentPath:o,propertyPath:o});if(void 0===s)return t;if(e.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&void 0===r._def?.defaultValue)throw new Error(`Zod field at \`${o.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...t.properties,[n]:s},required:r.isOptional()&&!e.openaiStrictMode?t.required:[...t.required,n]}},{properties:{},required:[]}),additionalProperties:C(t,e)};return n.required.length||delete n.required,n}(t,n);case i.ZodFirstPartyTypeKind.ZodBigInt:return function(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":"jsonSchema7"===e.target?r.inclusive?c(n,"minimum",r.value,r.message,e):c(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),c(n,"minimum",r.value,r.message,e));break;case"max":"jsonSchema7"===e.target?r.inclusive?c(n,"maximum",r.value,r.message,e):c(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),c(n,"maximum",r.value,r.message,e));break;case"multipleOf":c(n,"multipleOf",r.value,r.message,e)}return n}(t,n);case i.ZodFirstPartyTypeKind.ZodBoolean:return{type:"boolean"};case i.ZodFirstPartyTypeKind.ZodDate:return l(t,n);case i.ZodFirstPartyTypeKind.ZodUndefined:return{not:{}};case i.ZodFirstPartyTypeKind.ZodNull:return function(t){return"openApi3"===t.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case i.ZodFirstPartyTypeKind.ZodArray:return function(t,e){const n={type:"array"};return t.type?._def?.typeName!==i.ZodFirstPartyTypeKind.ZodAny&&(n.items=k(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&c(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&c(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(c(n,"minItems",t.exactLength.value,t.exactLength.message,e),c(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}(t,n);case i.ZodFirstPartyTypeKind.ZodUnion:case i.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return function(t,e){if("openApi3"===e.target)return S(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(t=>t._def.typeName in T&&(!t._def.checks||!t._def.checks.length))){const t=n.reduce((t,e)=>{const n=T[e._def.typeName];return n&&!t.includes(n)?[...t,n]:t},[]);return{type:t.length>1?t:t[0]}}if(n.every(t=>"ZodLiteral"===t._def.typeName&&!t.description)){const t=n.reduce((t,e)=>{const n=typeof e._def.value;switch(n){case"string":case"number":case"boolean":return[...t,n];case"bigint":return[...t,"integer"];case"object":if(null===e._def.value)return[...t,"null"];default:return t}},[]);if(t.length===n.length){const e=t.filter((t,e,n)=>n.indexOf(t)===e);return{type:e.length>1?e:e[0],enum:n.reduce((t,e)=>t.includes(e._def.value)?t:[...t,e._def.value],[])}}}else if(n.every(t=>"ZodEnum"===t._def.typeName))return{type:"string",enum:n.reduce((t,e)=>[...t,...e._def.values.filter(e=>!t.includes(e))],[])};return S(t,e)}(t,n);case i.ZodFirstPartyTypeKind.ZodIntersection:return function(t,e){const n=[k(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),k(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(t=>!!t);let r="jsonSchema2019-09"===e.target?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach(t=>{if("type"in(e=t)&&"string"===e.type||!("allOf"in e)){let e=t;if("additionalProperties"in t&&!1===t.additionalProperties){const{additionalProperties:n,...r}=t;e=r}else r=void 0;o.push(e)}else o.push(...t.allOf),void 0===t.unevaluatedProperties&&(r=void 0);var e}),o.length?{allOf:o,...r}:void 0}(t,n);case i.ZodFirstPartyTypeKind.ZodTuple:return function(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,n)=>k(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,e)=>void 0===e?t:[...t,e],[]),additionalItems:k(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,n)=>k(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,e)=>void 0===e?t:[...t,e],[])}}(t,n);case i.ZodFirstPartyTypeKind.ZodRecord:return I(t,n);case i.ZodFirstPartyTypeKind.ZodLiteral:return function(t,e){const n=typeof t.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(t.value)?"array":"object"}:"openApi3"===e.target?{type:"bigint"===n?"integer":n,enum:[t.value]}:{type:"bigint"===n?"integer":n,const:t.value}}(t,n);case i.ZodFirstPartyTypeKind.ZodEnum:return function(t){return{type:"string",enum:[...t.values]}}(t);case i.ZodFirstPartyTypeKind.ZodNativeEnum:return function(t){const e=t.values,n=Object.keys(t.values).filter(t=>"number"!=typeof e[e[t]]).map(t=>e[t]),r=Array.from(new Set(n.map(t=>typeof t)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(t);case i.ZodFirstPartyTypeKind.ZodNullable:return function(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return"openApi3"===e.target||"property"===e.nullableStrategy?{type:T[t.innerType._def.typeName],nullable:!0}:{type:[T[t.innerType._def.typeName],"null"]};if("openApi3"===e.target){const n=k(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=k(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(t,n);case i.ZodFirstPartyTypeKind.ZodOptional:return((t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return k(t.innerType._def,{...e,currentPath:e.currentPath});const n=k(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}})(t,n);case i.ZodFirstPartyTypeKind.ZodMap:return function(t,e){return"record"===e.mapStrategy?I(t,e):{type:"array",maxItems:125,items:{type:"array",items:[k(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},k(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(t,n);case i.ZodFirstPartyTypeKind.ZodSet:return function(t,e){const n={type:"array",uniqueItems:!0,items:k(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&c(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&c(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}(t,n);case i.ZodFirstPartyTypeKind.ZodLazy:return k(t.getter()._def,n);case i.ZodFirstPartyTypeKind.ZodPromise:return function(t,e){return k(t.type._def,e)}(t,n);case i.ZodFirstPartyTypeKind.ZodNaN:case i.ZodFirstPartyTypeKind.ZodNever:return{not:{}};case i.ZodFirstPartyTypeKind.ZodEffects:return function(t,e,n){return"input"===e.effectStrategy?k(t.schema._def,e,n):{}}(t,n,r);case i.ZodFirstPartyTypeKind.ZodAny:case i.ZodFirstPartyTypeKind.ZodUnknown:return{};case i.ZodFirstPartyTypeKind.ZodDefault:return function(t,e){return{...k(t.innerType._def,e),default:t.defaultValue()}}(t,n);case i.ZodFirstPartyTypeKind.ZodBranded:return function(t,e){return k(t.type._def,e)}(t,n);case i.ZodFirstPartyTypeKind.ZodReadonly:case i.ZodFirstPartyTypeKind.ZodCatch:return((t,e)=>k(t.innerType._def,e))(t,n);case i.ZodFirstPartyTypeKind.ZodPipeline:return((t,e)=>{if("input"===e.pipeStrategy)return k(t.in._def,e);if("output"===e.pipeStrategy)return k(t.out._def,e);const n=k(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[n,k(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]})].filter(t=>void 0!==t)}})(t,n);case i.ZodFirstPartyTypeKind.ZodFunction:case i.ZodFirstPartyTypeKind.ZodVoid:case i.ZodFirstPartyTypeKind.ZodSymbol:default:return}},O=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),R=(t,e)=>{const n=(t=>{const e=(t=>"string"==typeof t?{...s,basePath:["#"],definitions:{},name:t}:{...s,basePath:["#"],definitions:{},...t})(t),n=void 0!==e.name?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([t,n])=>[a(n),{def:a(n),path:[...e.basePath,e.definitionPath,t],jsonSchema:void 0}]))}})(e),r="string"==typeof e?e:"title"===e?.nameStrategy?void 0:e?.name,o=k(t._def,void 0===r?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},i="object"==typeof e&&void 0!==e.name&&"title"===e.nameStrategy?e.name:void 0;void 0!==i&&(o.title=i);const u=(()=>{if(function(t){if(!t)return!0;for(const e in t)return!1;return!0}(n.definitions))return;const t={},e=new Set;for(let r=0;r<500;r++){const r=Object.entries(n.definitions).filter(([t])=>!e.has(t));if(0===r.length)break;for(const[o,s]of r)t[o]=k(a(s),{...n,currentPath:[...n.basePath,n.definitionPath,o]},!0)??{},e.add(o)}return t})(),c=void 0===r?u?{...o,[n.definitionPath]:u}:o:"duplicate-ref"===n.nameStrategy?{...o,...u||n.seenRefs.size?{[n.definitionPath]:{...u,...n.seenRefs.size?{[r]:o}:void 0}}:void 0}:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...u,[r]:o}};return"jsonSchema7"===n.target?c.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===n.target&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),c};var N=n(839);function M(t,e){return R(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}var D=n(6201),F=n(9520);function L(t){if(0===(t=(t=t.replace(/\s/g,"_")).replace(/[^a-zA-Z0-9]/g,"_")).length)throw new Error("Tool name cannot be empty");return t}function $(t,e){if((0,F.f)(t)){const r=(n={name:e,parameters:t,function:()=>{},description:""},(0,N.bi)({type:"function",name:n.name,parameters:M(n.parameters,{name:n.name}),strict:!0,...n.description?{description:n.description}:void 0},{callback:n.function,parser:t=>n.parameters.parse(JSON.parse(t))}));return{schema:r.parameters,parser:r.$parseRaw}}if("object"==typeof t&&null!==t)return{schema:t,parser:t=>JSON.parse(t)};var n;throw new D.yo("Input type is not a ZodObject or a valid JSON schema")}function Z(t){if("text"===t)return"text";if((0,F.f)(t)){const o=(e=t,n="output",(0,r.i1)({type:"json_schema",name:n,strict:!0,schema:M(e,{name:n})},t=>e.parse(JSON.parse(t))));return{type:o.type,name:o.name,strict:o.strict||!1,schema:o.schema}}var e,n;return t}},9463:(t,e,n)=>{"use strict";n.d(e,{$t:()=>s.$t,AF:()=>a.AF,B9:()=>s.B9,Cn:()=>u.C,Cp:()=>s.Cp,DT:()=>s.DT,Ee:()=>s.Ee,Eu:()=>s.Eu,JA:()=>p,L0:()=>s.L0,L9:()=>i.L,LG:()=>s.LG,M6:()=>s.M6,Nn:()=>o.Nn,PJ:()=>s.PJ,Qv:()=>m,SZ:()=>o.SZ,UC:()=>s.UC,UI:()=>s.UI,VD:()=>a.VD,VP:()=>l,Xq:()=>s.Xq,YP:()=>o.YP,ZF:()=>c.ZF,cS:()=>s.cS,cW:()=>s.cW,dr:()=>d,el:()=>c.el,fz:()=>i.f,h6:()=>o.h6,hn:()=>s.hn,ih:()=>u.i,it:()=>s.it,j3:()=>o.j3,mp:()=>s.mp,mq:()=>o.mq,tL:()=>s.tL,tQ:()=>s.tQ,uA:()=>c.uA,ub:()=>s.ub,ux:()=>s.ux});var r=n(2618),o=n(26),s=n(476),a=n(7755),i=n(7780),u=n(4075),c=n(7020);function l(t){(0,r.A)().registerProcessor(t)}function p(t){(0,r.A)().setProcessors(t)}function d(t){(0,r.A)().setDisabled(t)}function m(){(0,r.A)().startExportLoop()}},9520:(t,e,n)=>{"use strict";function r(t){return"object"==typeof t&&null!==t&&"_def"in t&&"object"==typeof t._def&&null!==t._def&&"typeName"in t._def&&"ZodObject"===t._def.typeName}function o(t){return"object"==typeof t&&null!==t&&"input"in t&&"string"==typeof t.input}n.d(e,{A:()=>o,f:()=>r})},9731:(t,e,n)=>{"use strict";n.d(e,{OJ:()=>u,Tw:()=>o,U:()=>a,cz:()=>g,d4:()=>d,i1:()=>s,i_:()=>i,ie:()=>c,tp:()=>p});var r=n(7036);function o(t){return void 0!==t&&"function"in t&&void 0!==t.function}function s(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function a(t){return"auto-parseable-response-format"===t?.$brand}function i(t){return"auto-parseable-tool"===t?.$brand}function u(t,e){return e&&d(e)?c(t,e):{...t,choices:t.choices.map(t=>(m(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}}function c(t,e){const n=t.choices.map(t=>{if("length"===t.finish_reason)throw new r.k5;if("content_filter"===t.finish_reason)throw new r.pf;return m(t.message.tool_calls),{...t,message:{...t.message,...t.message.tool_calls?{tool_calls:t.message.tool_calls?.map(t=>function(t,e){const n=t.tools?.find(t=>o(t)&&t.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:i(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}(e,t))??void 0}:void 0,parsed:t.message.content&&!t.message.refusal?l(e,t.message.content):null}}});return{...t,choices:n}}function l(t,e){return"json_schema"!==t.response_format?.type?null:"json_schema"===t.response_format?.type?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function p(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(t=>o(t)&&t.function?.name===e.function.name);return o(n)&&(i(n)||n?.function.strict||!1)}function d(t){return!!a(t.response_format)||(t.tools?.some(t=>i(t)||"function"===t.type&&!0===t.function.strict)??!1)}function m(t){for(const e of t||[])if("function"!==e.type)throw new r.vc(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function g(t){for(const e of t??[]){if("function"!==e.type)throw new r.vc(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(!0!==e.function.strict)throw new r.vc(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}}}]);
|