@babelbeez/sdk 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +38 -6
- package/dist/babelbeez-sdk.d.ts +18 -2
- package/dist/babelbeez-sdk.js +6691 -6769
- package/dist/babelbeez-sdk.umd.cjs +11 -11
- package/package.json +1 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
(function(ee,te){typeof exports=="object"&&typeof module<"u"?te(exports):typeof define=="function"&&define.amd?define(["exports"],te):(ee=typeof globalThis<"u"?globalThis:ee||self,te(ee.BabelbeezSDK={}))})(this,function(ee){"use strict";var _f=Object.defineProperty;var ho=ee=>{throw TypeError(ee)};var vf=(ee,te,le)=>te in ee?_f(ee,te,{enumerable:!0,configurable:!0,writable:!0,value:le}):ee[te]=le;var S=(ee,te,le)=>vf(ee,typeof te!="symbol"?te+"":te,le),Fr=(ee,te,le)=>te.has(ee)||ho("Cannot "+le);var c=(ee,te,le)=>(Fr(ee,te,"read from private field"),le?le.call(ee):te.get(ee)),R=(ee,te,le)=>te.has(ee)?ho("Cannot add the same private member more than once"):te instanceof WeakSet?te.add(ee):te.set(ee,le),k=(ee,te,le,ss)=>(Fr(ee,te,"write to private field"),ss?ss.call(ee,le):te.set(ee,le),le),z=(ee,te,le)=>(Fr(ee,te,"access private method"),le);var en,Nt,ke,nn,oe,$r,jr,mo,go,yo,_o,es,Ur,Lr,Rn,pt,Ae,st,sn,rn,Nn,Pt,Pn,Dn,an,Mn,Fn,on,be,rt,ft,ht,un,Te,zr,Br,gn,Ce,$n,jn,Un,Ln,Dt,mt,gt,Mt,zn,cn,it,_e,Ft,Fs,vo,$t,Bn,xe,Zn,qn,ie,Jn,yt,Gn,_t,jt,Ut,ye,Vn,at,Lt,zt,ln,Hn,Bt,Zr,bo,W,Z,dn,q,pn,fn,Wn,ue,hn,mn,Ge,Kn,Zt,Yn,Xn,ae,ts,ns,wo,js,Io,qr,So,Jr;const te={version:"0.3.6"};async function le(n){try{return[null,await n()]}catch(e){return[e,null]}}function ss(n){const e=Object.values(n).filter(s=>typeof s=="number");return Object.entries(n).filter(([s,r])=>e.indexOf(+s)===-1).map(([s,r])=>r)}class Gr{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const s=t[0];if(this._map.set(e,s),s&&typeof s=="object"&&"id"in s){if(this._idmap.has(s.id))throw new Error(`ID ${s.id} already exists in the registry`);this._idmap.set(s.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const s={...this.get(t)??{}};return delete s.id,{...s,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function To(){return new Gr}const xo=To();class Vr{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??xo,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var d,m,g;var s;const r=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,t.schemaPath.includes(e)&&(o.cycle=t.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,a);const u=(m=(d=e._zod).toJSONSchema)==null?void 0:m.call(d);if(u)a.schema=u;else{const _={...t,schemaPath:[...t.schemaPath,e],path:t.path},T=e._zod.parent;if(T)a.ref=T,this.process(T,_),this.seen.get(T).isParent=!0;else{const y=a.schema;switch(r.type){case"string":{const h=y;h.type="string";const{minimum:v,maximum:b,format:N,patterns:x,contentEncoding:A}=e._zod.bag;if(typeof v=="number"&&(h.minLength=v),typeof b=="number"&&(h.maxLength=b),N&&(h.format=i[N]??N,h.format===""&&delete h.format),A&&(h.contentEncoding=A),x&&x.size>0){const D=[...x];D.length===1?h.pattern=D[0].source:D.length>1&&(a.schema.allOf=[...D.map(U=>({...this.target==="draft-7"?{type:"string"}:{},pattern:U.source}))])}break}case"number":{const h=y,{minimum:v,maximum:b,format:N,multipleOf:x,exclusiveMaximum:A,exclusiveMinimum:D}=e._zod.bag;typeof N=="string"&&N.includes("int")?h.type="integer":h.type="number",typeof D=="number"&&(h.exclusiveMinimum=D),typeof v=="number"&&(h.minimum=v,typeof D=="number"&&(D>=v?delete h.minimum:delete h.exclusiveMinimum)),typeof A=="number"&&(h.exclusiveMaximum=A),typeof b=="number"&&(h.maximum=b,typeof A=="number"&&(A<=b?delete h.maximum:delete h.exclusiveMaximum)),typeof x=="number"&&(h.multipleOf=x);break}case"boolean":{const h=y;h.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{y.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{y.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const h=y,{minimum:v,maximum:b}=e._zod.bag;typeof v=="number"&&(h.minItems=v),typeof b=="number"&&(h.maxItems=b),h.type="array",h.items=this.process(r.element,{..._,path:[..._.path,"items"]});break}case"object":{const h=y;h.type="object",h.properties={};const v=r.shape;for(const x in v)h.properties[x]=this.process(v[x],{..._,path:[..._.path,"properties",x]});const b=new Set(Object.keys(v)),N=new Set([...b].filter(x=>{const A=r.shape[x]._zod;return this.io==="input"?A.optin===void 0:A.optout===void 0}));N.size>0&&(h.required=Array.from(N)),((g=r.catchall)==null?void 0:g._zod.def.type)==="never"?h.additionalProperties=!1:r.catchall?r.catchall&&(h.additionalProperties=this.process(r.catchall,{..._,path:[..._.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{const h=y;h.anyOf=r.options.map((v,b)=>this.process(v,{..._,path:[..._.path,"anyOf",b]}));break}case"intersection":{const h=y,v=this.process(r.left,{..._,path:[..._.path,"allOf",0]}),b=this.process(r.right,{..._,path:[..._.path,"allOf",1]}),N=A=>"allOf"in A&&Object.keys(A).length===1,x=[...N(v)?v.allOf:[v],...N(b)?b.allOf:[b]];h.allOf=x;break}case"tuple":{const h=y;h.type="array";const v=r.items.map((x,A)=>this.process(x,{..._,path:[..._.path,"prefixItems",A]}));if(this.target==="draft-2020-12"?h.prefixItems=v:h.items=v,r.rest){const x=this.process(r.rest,{..._,path:[..._.path,"items"]});this.target==="draft-2020-12"?h.items=x:h.additionalItems=x}r.rest&&(h.items=this.process(r.rest,{..._,path:[..._.path,"items"]}));const{minimum:b,maximum:N}=e._zod.bag;typeof b=="number"&&(h.minItems=b),typeof N=="number"&&(h.maxItems=N);break}case"record":{const h=y;h.type="object",h.propertyNames=this.process(r.keyType,{..._,path:[..._.path,"propertyNames"]}),h.additionalProperties=this.process(r.valueType,{..._,path:[..._.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const h=y,v=ss(r.entries);v.every(b=>typeof b=="number")&&(h.type="number"),v.every(b=>typeof b=="string")&&(h.type="string"),h.enum=v;break}case"literal":{const h=y,v=[];for(const b of r.values)if(b===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof b=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(b))}else v.push(b);if(v.length!==0)if(v.length===1){const b=v[0];h.type=b===null?"null":typeof b,h.const=b}else v.every(b=>typeof b=="number")&&(h.type="number"),v.every(b=>typeof b=="string")&&(h.type="string"),v.every(b=>typeof b=="boolean")&&(h.type="string"),v.every(b=>b===null)&&(h.type="null"),h.enum=v;break}case"file":{const h=y,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:b,maximum:N,mime:x}=e._zod.bag;b!==void 0&&(v.minLength=b),N!==void 0&&(v.maxLength=N),x?x.length===1?(v.contentMediaType=x[0],Object.assign(h,v)):h.anyOf=x.map(A=>({...v,contentMediaType:A})):Object.assign(h,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const h=this.process(r.innerType,_);y.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(r.innerType,_),a.ref=r.innerType;break}case"success":{const h=y;h.type="boolean";break}case"default":{this.process(r.innerType,_),a.ref=r.innerType,y.default=JSON.parse(JSON.stringify(r.defaultValue));break}case"prefault":{this.process(r.innerType,_),a.ref=r.innerType,this.io==="input"&&(y._prefault=JSON.parse(JSON.stringify(r.defaultValue)));break}case"catch":{this.process(r.innerType,_),a.ref=r.innerType;let h;try{h=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}y.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const h=y,v=e._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=v.source;break}case"pipe":{const h=this.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;this.process(h,_),a.ref=h;break}case"readonly":{this.process(r.innerType,_),a.ref=r.innerType,y.readOnly=!0;break}case"promise":{this.process(r.innerType,_),a.ref=r.innerType;break}case"optional":{this.process(r.innerType,_),a.ref=r.innerType;break}case"lazy":{const h=e._zod.innerType;this.process(h,_),a.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&he(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((s=a.schema).default??(s.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,t){var p,d,m,g,_,T;const s={cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0},r=this.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=y=>{var x;const h=this.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const A=(x=s.external.registry.get(y[0]))==null?void 0:x.id,D=s.external.uri??(G=>G);if(A)return{ref:D(A)};const U=y[1].defId??y[1].schema.id??`schema${this.counter++}`;return y[1].defId=U,{defId:U,ref:`${D("__shared")}#/${h}/${U}`}}if(y[1]===r)return{ref:"#"};const b=`#/${h}/`,N=y[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:b+N}},o=y=>{if(y[1].schema.$ref)return;const h=y[1],{ref:v,defId:b}=i(y);h.def={...h.schema},b&&(h.defId=b);const N=h.schema;for(const x in N)delete N[x];N.$ref=v};if(s.cycles==="throw")for(const y of this.seen.entries()){const h=y[1];if(h.cycle)throw new Error(`Cycle detected: #/${(p=h.cycle)==null?void 0:p.join("/")}/<root>
|
|
1
|
+
(function(Ke,Me){typeof exports=="object"&&typeof module<"u"?Me(exports):typeof define=="function"&&define.amd?define(["exports"],Me):(Ke=typeof globalThis<"u"?globalThis:Ke||self,Me(Ke.BabelbeezSDK={}))})(this,(function(Ke){"use strict";const Me={version:"0.3.6"};async function en(t){try{return[null,await t()]}catch(e){return[e,null]}}function _i(t){const e=Object.values(t).filter(s=>typeof s=="number");return Object.entries(t).filter(([s,r])=>e.indexOf(+s)===-1).map(([s,r])=>r)}class Wn{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){const s=n[0];if(this._map.set(e,s),s&&typeof s=="object"&&"id"in s){if(this._idmap.has(s.id))throw new Error(`ID ${s.id} already exists in the registry`);this._idmap.set(s.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const s={...this.get(n)??{}};return delete s.id,{...s,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function vi(){return new Wn}const bi=vi();class Kn{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??bi,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var s;const r=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,o);const u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{const p={...n,schemaPath:[...n.schemaPath,e],path:n.path},h=e._zod.parent;if(h)o.ref=h,this.process(h,p),this.seen.get(h).isParent=!0;else{const f=o.schema;switch(r.type){case"string":{const m=f;m.type="string";const{minimum:g,maximum:_,format:w,patterns:b,contentEncoding:C}=e._zod.bag;if(typeof g=="number"&&(m.minLength=g),typeof _=="number"&&(m.maxLength=_),w&&(m.format=i[w]??w,m.format===""&&delete m.format),C&&(m.contentEncoding=C),b&&b.size>0){const k=[...b];k.length===1?m.pattern=k[0].source:k.length>1&&(o.schema.allOf=[...k.map(x=>({...this.target==="draft-7"?{type:"string"}:{},pattern:x.source}))])}break}case"number":{const m=f,{minimum:g,maximum:_,format:w,multipleOf:b,exclusiveMaximum:C,exclusiveMinimum:k}=e._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof k=="number"&&(m.exclusiveMinimum=k),typeof g=="number"&&(m.minimum=g,typeof k=="number"&&(k>=g?delete m.minimum:delete m.exclusiveMinimum)),typeof C=="number"&&(m.exclusiveMaximum=C),typeof _=="number"&&(m.maximum=_,typeof C=="number"&&(C<=_?delete m.maximum:delete m.exclusiveMaximum)),typeof b=="number"&&(m.multipleOf=b);break}case"boolean":{const m=f;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=f,{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof _=="number"&&(m.maxItems=_),m.type="array",m.items=this.process(r.element,{...p,path:[...p.path,"items"]});break}case"object":{const m=f;m.type="object",m.properties={};const g=r.shape;for(const b in g)m.properties[b]=this.process(g[b],{...p,path:[...p.path,"properties",b]});const _=new Set(Object.keys(g)),w=new Set([..._].filter(b=>{const C=r.shape[b]._zod;return this.io==="input"?C.optin===void 0:C.optout===void 0}));w.size>0&&(m.required=Array.from(w)),r.catchall?._zod.def.type==="never"?m.additionalProperties=!1:r.catchall?r.catchall&&(m.additionalProperties=this.process(r.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=f;m.anyOf=r.options.map((g,_)=>this.process(g,{...p,path:[...p.path,"anyOf",_]}));break}case"intersection":{const m=f,g=this.process(r.left,{...p,path:[...p.path,"allOf",0]}),_=this.process(r.right,{...p,path:[...p.path,"allOf",1]}),w=C=>"allOf"in C&&Object.keys(C).length===1,b=[...w(g)?g.allOf:[g],...w(_)?_.allOf:[_]];m.allOf=b;break}case"tuple":{const m=f;m.type="array";const g=r.items.map((b,C)=>this.process(b,{...p,path:[...p.path,"prefixItems",C]}));if(this.target==="draft-2020-12"?m.prefixItems=g:m.items=g,r.rest){const b=this.process(r.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=b:m.additionalItems=b}r.rest&&(m.items=this.process(r.rest,{...p,path:[...p.path,"items"]}));const{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(m.minItems=_),typeof w=="number"&&(m.maxItems=w);break}case"record":{const m=f;m.type="object",m.propertyNames=this.process(r.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(r.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const m=f,g=_i(r.entries);g.every(_=>typeof _=="number")&&(m.type="number"),g.every(_=>typeof _=="string")&&(m.type="string"),m.enum=g;break}case"literal":{const m=f,g=[];for(const _ of r.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(_))}else g.push(_);if(g.length!==0)if(g.length===1){const _=g[0];m.type=_===null?"null":typeof _,m.const=_}else g.every(_=>typeof _=="number")&&(m.type="number"),g.every(_=>typeof _=="string")&&(m.type="string"),g.every(_=>typeof _=="boolean")&&(m.type="string"),g.every(_=>_===null)&&(m.type="null"),m.enum=g;break}case"file":{const m=f,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:b}=e._zod.bag;_!==void 0&&(g.minLength=_),w!==void 0&&(g.maxLength=w),b?b.length===1?(g.contentMediaType=b[0],Object.assign(m,g)):m.anyOf=b.map(C=>({...g,contentMediaType:C})):Object.assign(m,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(r.innerType,p);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(r.innerType,p),o.ref=r.innerType;break}case"success":{const m=f;m.type="boolean";break}case"default":{this.process(r.innerType,p),o.ref=r.innerType,f.default=JSON.parse(JSON.stringify(r.defaultValue));break}case"prefault":{this.process(r.innerType,p),o.ref=r.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(r.defaultValue)));break}case"catch":{this.process(r.innerType,p),o.ref=r.innerType;let m;try{m=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=f,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=g.source;break}case"pipe":{const m=this.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;this.process(m,p),o.ref=m;break}case"readonly":{this.process(r.innerType,p),o.ref=r.innerType,f.readOnly=!0;break}case"promise":{this.process(r.innerType,p),o.ref=r.innerType;break}case"optional":{this.process(r.innerType,p),o.ref=r.innerType;break}case"lazy":{const m=e._zod.innerType;this.process(m,p),o.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const l=this.metadataRegistry.get(e);return l&&Object.assign(o.schema,l),this.io==="input"&&W(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((s=o.schema).default??(s.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,n){const s={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},r=this.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=d=>{const p=this.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const g=s.external.registry.get(d[0])?.id,_=s.external.uri??(b=>b);if(g)return{ref:_(g)};const w=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=w,{defId:w,ref:`${_("__shared")}#/${p}/${w}`}}if(d[1]===r)return{ref:"#"};const f=`#/${p}/`,m=d[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},a=d=>{if(d[1].schema.$ref)return;const p=d[1],{ref:h,defId:f}=i(d);p.def={...p.schema},f&&(p.defId=f);const m=p.schema;for(const g in m)delete m[g];m.$ref=h};if(s.cycles==="throw")for(const d of this.seen.entries()){const p=d[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
2
2
|
|
|
3
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const y of this.seen.entries()){const h=y[1];if(e===y[0]){o(y);continue}if(s.external){const b=(d=s.external.registry.get(y[0]))==null?void 0:d.id;if(e!==y[0]&&b){o(y);continue}}if((m=this.metadataRegistry.get(y[0]))==null?void 0:m.id){o(y);continue}if(h.cycle){o(y);continue}if(h.count>1&&s.reused==="ref"){o(y);continue}}const a=(y,h)=>{const v=this.seen.get(y),b=v.def??v.schema,N={...b};if(v.ref===null)return;const x=v.ref;if(v.ref=null,x){a(x,h);const A=this.seen.get(x).schema;A.$ref&&h.target==="draft-7"?(b.allOf=b.allOf??[],b.allOf.push(A)):(Object.assign(b,A),Object.assign(b,N))}v.isParent||this.override({zodSchema:y,jsonSchema:b,path:v.path??[]})};for(const y of[...this.seen.entries()].reverse())a(y[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(g=s.external)!=null&&g.uri){const y=(_=s.external.registry.get(e))==null?void 0:_.id;if(!y)throw new Error("Schema is missing an `id` property");u.$id=s.external.uri(y)}Object.assign(u,r.def);const l=((T=s.external)==null?void 0:T.defs)??{};for(const y of this.seen.entries()){const h=y[1];h.def&&h.defId&&(l[h.defId]=h.def)}s.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function ko(n,e){if(n instanceof Gr){const s=new Vr(e),r={};for(const a of n._idmap.entries()){const[u,l]=a;s.process(l)}const i={},o={registry:n,uri:e==null?void 0:e.uri,defs:r};for(const a of n._idmap.entries()){const[u,l]=a;i[u]=s.emit(l,{...e,external:o})}if(Object.keys(r).length>0){const a=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[a]:r}}return{schemas:i}}const t=new Vr(e);return t.process(n),t.emit(n,e)}function he(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const r=n._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return he(r.element,t);case"object":{for(const i in r.shape)if(he(r.shape[i],t))return!0;return!1}case"union":{for(const i of r.options)if(he(i,t))return!0;return!1}case"intersection":return he(r.left,t)||he(r.right,t);case"tuple":{for(const i of r.items)if(he(i,t))return!0;return!!(r.rest&&he(r.rest,t))}case"record":return he(r.keyType,t)||he(r.valueType,t);case"map":return he(r.keyType,t)||he(r.valueType,t);case"set":return he(r.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return he(r.innerType,t);case"lazy":return he(r.getter(),t);case"default":return he(r.innerType,t);case"prefault":return he(r.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return he(r.in,t)||he(r.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${r.type}`)}function Ao(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}const Co=Symbol("Let zodToJsonSchema decide on which parser to use"),Hr={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"},Oo=n=>typeof n=="string"?{...Hr,basePath:["#"],definitions:{},name:n}:{...Hr,basePath:["#"],definitions:{},...n},Us=n=>"_def"in n?n._def:n;function Eo(n){if(!n)return!0;for(const e in n)return!1;return!0}const Ro=n=>{const e=Oo(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,r])=>[Us(r),{def:Us(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function Wr(n,e,t,s){s!=null&&s.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function ne(n,e,t,s,r){n[e]=t,Wr(n,e,s,r)}var X;(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},n.getValidEnumValues=r=>{const i=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(i){return r[i]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},n.find=(r,i)=>{for(const o of r)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=s,n.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(X||(X={}));var Kr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Kr||(Kr={}));const M=X.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ot=n=>{switch(typeof n){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(n)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(n)?M.array:n===null?M.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?M.promise:typeof Map<"u"&&n instanceof Map?M.map:typeof Set<"u"&&n instanceof Set?M.set:typeof Date<"u"&&n instanceof Date?M.date:M.object;default:return M.unknown}},C=X.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Fe extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(t(o));else{let a=s,u=0;for(;u<o.path.length;){const l=o.path[u];u===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return r(this),s}static assert(e){if(!(e instanceof Fe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,X.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Fe.create=n=>new Fe(n);const Ls=(n,e)=>{let t;switch(n.code){case C.invalid_type:n.received===M.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case C.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,X.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:t=`Unrecognized key(s) in object: ${X.joinValues(n.keys,", ")}`;break;case C.invalid_union:t="Invalid input";break;case C.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${X.joinValues(n.options)}`;break;case C.invalid_enum_value:t=`Invalid enum value. Expected ${X.joinValues(n.options)}, received '${n.received}'`;break;case C.invalid_arguments:t="Invalid function arguments";break;case C.invalid_return_type:t="Invalid function return type";break;case C.invalid_date:t="Invalid date";break;case C.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:X.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case C.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case C.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case C.custom:t="Invalid input";break;case C.invalid_intersection_types:t="Intersection results could not be merged";break;case C.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case C.not_finite:t="Number must be finite";break;default:t=e.defaultError,X.assertNever(n)}return{message:t}};let No=Ls;function Po(){return No}const Do=n=>{const{data:e,path:t,errorMaps:s,issueData:r}=n,i=[...t,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const u=s.filter(l=>!!l).slice().reverse();for(const l of u)a=l(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function P(n,e){const t=Po(),s=Do({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Ls?void 0:Ls].filter(r=>!!r)});n.common.issues.push(s)}class we{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return B;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return we.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return B;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const B=Object.freeze({status:"aborted"}),yn=n=>({status:"dirty",value:n}),Oe=n=>({status:"valid",value:n}),Yr=n=>n.status==="aborted",Xr=n=>n.status==="dirty",qt=n=>n.status==="valid",rs=n=>typeof Promise<"u"&&n instanceof Promise;var j;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(j||(j={}));class $e{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Qr=(n,e)=>{if(qt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Fe(n.common.issues);return this._error=t,this._error}}};function V(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:u}=n;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:r}}class K{get description(){return this._def.description}_getType(e){return ot(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new we,ctx:{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(rs(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Qr(s,r)}"~validate"(e){var s,r;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return qt(i)?{value:i.value}:{issues:t.common.issues}}catch(i){(r=(s=i==null?void 0:i.message)==null?void 0:s.toLowerCase())!=null&&r.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>qt(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(rs(r)?r:Promise.resolve(r));return Qr(s,i)}refine(e,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:C.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new wt({schema:this,typeName:O.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ke.create(this,this._def)}nullable(){return It.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return je.create(this)}promise(){return ds.create(this,this._def)}or(e){return as.create([this,e],this._def)}and(e){return os.create(this,e,this._def)}transform(e){return new wt({...V(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ps({...V(this._def),innerType:this,defaultValue:t,typeName:O.ZodDefault})}brand(){return new ui({typeName:O.ZodBranded,type:this,...V(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new fs({...V(this._def),innerType:this,catchValue:t,typeName:O.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Hs.create(this,e)}readonly(){return hs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Mo=/^c[^\s-]{8,}$/i,Fo=/^[0-9a-z]+$/,$o=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Uo=/^[a-z0-9_-]{21}$/i,Lo=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zo=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Bo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Zo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let zs;const qo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Jo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Go=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Vo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ho=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Wo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ei="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ko=new RegExp(`^${ei}$`);function ti(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Yo(n){return new RegExp(`^${ti(n)}$`)}function Xo(n){let e=`${ei}T${ti(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Qo(n,e){return!!((e==="v4"||!e)&&qo.test(n)||(e==="v6"||!e)&&Go.test(n))}function eu(n,e){if(!Lo.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function tu(n,e){return!!((e==="v4"||!e)&&Jo.test(n)||(e==="v6"||!e)&&Vo.test(n))}class He extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){const i=this._getOrReturnCtx(e);return P(i,{code:C.invalid_type,expected:M.string,received:i.parsedType}),B}const s=new we;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?P(r,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&P(r,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")Bo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"email",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")zs||(zs=new RegExp(Zo,"u")),zs.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"emoji",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")jo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"uuid",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Uo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"nanoid",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Mo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")Fo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid2",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")$o.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ulid",code:C.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),P(r,{validation:"url",code:C.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"regex",code:C.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),P(r,{code:C.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),P(r,{code:C.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),P(r,{code:C.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Xo(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:C.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ko.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:C.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Yo(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:C.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?zo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:C.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Qo(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ip",code:C.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?eu(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"jwt",code:C.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?tu(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cidr",code:C.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Ho.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:C.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Wo.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:C.invalid_string,message:i.message}),s.dirty()):X.assertNever(i);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(r=>e.test(r),{validation:t,code:C.invalid_string,...j.errToObj(s)})}_addCheck(e){return new He({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...j.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...j.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...j.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...j.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...j.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...j.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...j.errToObj(t)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new He({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new He({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new He({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}He.create=n=>new He({checks:[],typeName:O.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...V(n)});function nu(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Jt extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){const i=this._getOrReturnCtx(e);return P(i,{code:C.invalid_type,expected:M.number,received:i.parsedType}),B}let s;const r=new we;for(const i of this._def.checks)i.kind==="int"?X.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:C.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:C.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:C.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?nu(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),P(s,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:C.not_finite,message:i.message}),r.dirty()):X.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,s,r){return new Jt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:j.toString(r)}]})}_addCheck(e){return new Jt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&X.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Jt.create=n=>new Jt({checks:[],typeName:O.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...V(n)});class _n extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let s;const r=new we;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:C.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),P(s,{code:C.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),P(s,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):X.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return P(t,{code:C.invalid_type,expected:M.bigint,received:t.parsedType}),B}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,s,r){return new _n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:j.toString(r)}]})}_addCheck(e){return new _n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}_n.create=n=>new _n({checks:[],typeName:O.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...V(n)});class Bs extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){const s=this._getOrReturnCtx(e);return P(s,{code:C.invalid_type,expected:M.boolean,received:s.parsedType}),B}return Oe(e.data)}}Bs.create=n=>new Bs({typeName:O.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...V(n)});class is extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){const i=this._getOrReturnCtx(e);return P(i,{code:C.invalid_type,expected:M.date,received:i.parsedType}),B}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return P(i,{code:C.invalid_date}),B}const s=new we;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:C.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),P(r,{code:C.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):X.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new is({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:j.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}is.create=n=>new is({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:O.ZodDate,...V(n)});class ni extends K{_parse(e){if(this._getType(e)!==M.symbol){const s=this._getOrReturnCtx(e);return P(s,{code:C.invalid_type,expected:M.symbol,received:s.parsedType}),B}return Oe(e.data)}}ni.create=n=>new ni({typeName:O.ZodSymbol,...V(n)});class Zs extends K{_parse(e){if(this._getType(e)!==M.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:C.invalid_type,expected:M.undefined,received:s.parsedType}),B}return Oe(e.data)}}Zs.create=n=>new Zs({typeName:O.ZodUndefined,...V(n)});class qs extends K{_parse(e){if(this._getType(e)!==M.null){const s=this._getOrReturnCtx(e);return P(s,{code:C.invalid_type,expected:M.null,received:s.parsedType}),B}return Oe(e.data)}}qs.create=n=>new qs({typeName:O.ZodNull,...V(n)});class vn extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}}vn.create=n=>new vn({typeName:O.ZodAny,...V(n)});class si extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}}si.create=n=>new si({typeName:O.ZodUnknown,...V(n)});class ut extends K{_parse(e){const t=this._getOrReturnCtx(e);return P(t,{code:C.invalid_type,expected:M.never,received:t.parsedType}),B}}ut.create=n=>new ut({typeName:O.ZodNever,...V(n)});class ri extends K{_parse(e){if(this._getType(e)!==M.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:C.invalid_type,expected:M.void,received:s.parsedType}),B}return Oe(e.data)}}ri.create=n=>new ri({typeName:O.ZodVoid,...V(n)});class je extends K{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:C.invalid_type,expected:M.array,received:t.parsedType}),B;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(P(t,{code:o?C.too_big:C.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:C.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:C.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new $e(t,o,t.path,a)))).then(o=>we.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new $e(t,o,t.path,a)));return we.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new je({...this._def,minLength:{value:e,message:j.toString(t)}})}max(e,t){return new je({...this._def,maxLength:{value:e,message:j.toString(t)}})}length(e,t){return new je({...this._def,exactLength:{value:e,message:j.toString(t)}})}nonempty(e){return this.min(1,e)}}je.create=(n,e)=>new je({type:n,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...V(e)});function Gt(n){if(n instanceof de){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=Ke.create(Gt(s))}return new de({...n._def,shape:()=>e})}else return n instanceof je?new je({...n._def,type:Gt(n.element)}):n instanceof Ke?Ke.create(Gt(n.unwrap())):n instanceof It?It.create(Gt(n.unwrap())):n instanceof vt?vt.create(n.items.map(e=>Gt(e))):n}class de extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=X.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==M.object){const l=this._getOrReturnCtx(e);return P(l,{code:C.invalid_type,expected:M.object,received:l.parsedType}),B}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ut&&this._def.unknownKeys==="strip"))for(const l in r.data)o.includes(l)||a.push(l);const u=[];for(const l of o){const p=i[l],d=r.data[l];u.push({key:{status:"valid",value:l},value:p._parse(new $e(r,d,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof ut){const l=this._def.unknownKeys;if(l==="passthrough")for(const p of a)u.push({key:{status:"valid",value:p},value:{status:"valid",value:r.data[p]}});else if(l==="strict")a.length>0&&(P(r,{code:C.unrecognized_keys,keys:a}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const p of a){const d=r.data[p];u.push({key:{status:"valid",value:p},value:l._parse(new $e(r,d,r.path,p)),alwaysSet:p in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const l=[];for(const p of u){const d=await p.key,m=await p.value;l.push({key:d,value:m,alwaysSet:p.alwaysSet})}return l}).then(l=>we.mergeObjectSync(s,l)):we.mergeObjectSync(s,u)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new de({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var i,o;const r=((o=(i=this._def).errorMap)==null?void 0:o.call(i,t,s).message)??s.defaultError;return t.code==="unrecognized_keys"?{message:j.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:O.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const s of X.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const s of X.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}deepPartial(){return Gt(this)}partial(e){const t={};for(const s of X.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const s of X.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Ke;)i=i._def.innerType;t[s]=i}return new de({...this._def,shape:()=>t})}keyof(){return ai(X.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:ut.create(),typeName:O.ZodObject,...V(e)}),de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:ut.create(),typeName:O.ZodObject,...V(e)}),de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:ut.create(),typeName:O.ZodObject,...V(e)});class as extends K{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Fe(a.ctx.common.issues));return P(t,{code:C.invalid_union,unionErrors:o}),B}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const u of s){const l={...t,common:{...t.common,issues:[]},parent:null},p=u._parseSync({data:t.data,path:t.path,parent:l});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(u=>new Fe(u));return P(t,{code:C.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}}as.create=(n,e)=>new as({options:n,typeName:O.ZodUnion,...V(e)});const We=n=>n instanceof cs?We(n.schema):n instanceof wt?We(n.innerType()):n instanceof ls?[n.value]:n instanceof bt?n.options:n instanceof Vs?X.objectValues(n.enum):n instanceof ps?We(n._def.innerType):n instanceof Zs?[void 0]:n instanceof qs?[null]:n instanceof Ke?[void 0,...We(n.unwrap())]:n instanceof It?[null,...We(n.unwrap())]:n instanceof ui||n instanceof hs?We(n.unwrap()):n instanceof fs?We(n._def.innerType):[];class Js extends K{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:C.invalid_type,expected:M.object,received:t.parsedType}),B;const s=this.discriminator,r=t.data[s],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const r=new Map;for(const i of t){const o=We(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,i)}}return new Js({typeName:O.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...V(s)})}}function Gs(n,e){const t=ot(n),s=ot(e);if(n===e)return{valid:!0,data:n};if(t===M.object&&s===M.object){const r=X.objectKeys(e),i=X.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const u=Gs(n[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===M.array&&s===M.array){if(n.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<n.length;i++){const o=n[i],a=e[i],u=Gs(o,a);if(!u.valid)return{valid:!1};r.push(u.data)}return{valid:!0,data:r}}else return t===M.date&&s===M.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class os extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(Yr(i)||Yr(o))return B;const a=Gs(i.value,o.value);return a.valid?((Xr(i)||Xr(o))&&t.dirty(),{status:t.value,value:a.data}):(P(s,{code:C.invalid_intersection_types}),B)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}os.create=(n,e,t)=>new os({left:n,right:e,typeName:O.ZodIntersection,...V(t)});class vt extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==M.array)return P(s,{code:C.invalid_type,expected:M.array,received:s.parsedType}),B;if(s.data.length<this._def.items.length)return P(s,{code:C.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&s.data.length>this._def.items.length&&(P(s,{code:C.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...s.data].map((o,a)=>{const u=this._def.items[a]||this._def.rest;return u?u._parse(new $e(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>we.mergeArray(t,o)):we.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new vt({...this._def,rest:e})}}vt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vt({items:n,typeName:O.ZodTuple,rest:null,...V(e)})};class us extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==M.object)return P(s,{code:C.invalid_type,expected:M.object,received:s.parsedType}),B;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new $e(s,a,s.path,a)),value:o._parse(new $e(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?we.mergeObjectAsync(t,r):we.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof K?new us({keyType:e,valueType:t,typeName:O.ZodRecord,...V(s)}):new us({keyType:He.create(),valueType:e,typeName:O.ZodRecord,...V(t)})}}class ii extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==M.map)return P(s,{code:C.invalid_type,expected:M.map,received:s.parsedType}),B;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,u],l)=>({key:r._parse(new $e(s,a,s.path,[l,"key"])),value:i._parse(new $e(s,u,s.path,[l,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const u of o){const l=await u.key,p=await u.value;if(l.status==="aborted"||p.status==="aborted")return B;(l.status==="dirty"||p.status==="dirty")&&t.dirty(),a.set(l.value,p.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const u of o){const l=u.key,p=u.value;if(l.status==="aborted"||p.status==="aborted")return B;(l.status==="dirty"||p.status==="dirty")&&t.dirty(),a.set(l.value,p.value)}return{status:t.value,value:a}}}}ii.create=(n,e,t)=>new ii({valueType:e,keyType:n,typeName:O.ZodMap,...V(t)});class bn extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==M.set)return P(s,{code:C.invalid_type,expected:M.set,received:s.parsedType}),B;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(P(s,{code:C.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(P(s,{code:C.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(u){const l=new Set;for(const p of u){if(p.status==="aborted")return B;p.status==="dirty"&&t.dirty(),l.add(p.value)}return{status:t.value,value:l}}const a=[...s.data.values()].map((u,l)=>i._parse(new $e(s,u,s.path,l)));return s.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new bn({...this._def,minSize:{value:e,message:j.toString(t)}})}max(e,t){return new bn({...this._def,maxSize:{value:e,message:j.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}bn.create=(n,e)=>new bn({valueType:n,minSize:null,maxSize:null,typeName:O.ZodSet,...V(e)});class cs extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}cs.create=(n,e)=>new cs({getter:n,typeName:O.ZodLazy,...V(e)});class ls extends K{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:C.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}}ls.create=(n,e)=>new ls({value:n,typeName:O.ZodLiteral,...V(e)});function ai(n,e){return new bt({values:n,typeName:O.ZodEnum,...V(e)})}class bt extends K{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return P(t,{expected:X.joinValues(s),received:t.parsedType,code:C.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return P(t,{received:t.data,code:C.invalid_enum_value,options:s}),B}return Oe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return bt.create(e,{...this._def,...t})}exclude(e,t=this._def){return bt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}bt.create=ai;class Vs extends K{_parse(e){const t=X.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==M.string&&s.parsedType!==M.number){const r=X.objectValues(t);return P(s,{expected:X.joinValues(r),received:s.parsedType,code:C.invalid_type}),B}if(this._cache||(this._cache=new Set(X.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=X.objectValues(t);return P(s,{received:s.data,code:C.invalid_enum_value,options:r}),B}return Oe(e.data)}get enum(){return this._def.values}}Vs.create=(n,e)=>new Vs({values:n,typeName:O.ZodNativeEnum,...V(e)});class ds extends K{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.promise&&t.common.async===!1)return P(t,{code:C.invalid_type,expected:M.promise,received:t.parsedType}),B;const s=t.parsedType===M.promise?t.data:Promise.resolve(t.data);return Oe(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ds.create=(n,e)=>new ds({type:n,typeName:O.ZodPromise,...V(e)});class wt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return B;const u=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return u.status==="aborted"?B:u.status==="dirty"||t.value==="dirty"?yn(u.value):u});{if(t.value==="aborted")return B;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?B:a.status==="dirty"||t.value==="dirty"?yn(a.value):a}}if(r.type==="refinement"){const o=a=>{const u=r.refinement(a,i);if(s.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?B:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?B:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!qt(o))return B;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>qt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):B);X.assertNever(r)}}wt.create=(n,e,t)=>new wt({schema:n,typeName:O.ZodEffects,effect:e,...V(t)}),wt.createWithPreprocess=(n,e,t)=>new wt({schema:e,effect:{type:"preprocess",transform:n},typeName:O.ZodEffects,...V(t)});class Ke extends K{_parse(e){return this._getType(e)===M.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ke.create=(n,e)=>new Ke({innerType:n,typeName:O.ZodOptional,...V(e)});class It extends K{_parse(e){return this._getType(e)===M.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}It.create=(n,e)=>new It({innerType:n,typeName:O.ZodNullable,...V(e)});class ps extends K{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===M.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ps.create=(n,e)=>new ps({innerType:n,typeName:O.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});class fs extends K{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return rs(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Fe(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Fe(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}fs.create=(n,e)=>new fs({innerType:n,typeName:O.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});class oi extends K{_parse(e){if(this._getType(e)!==M.nan){const s=this._getOrReturnCtx(e);return P(s,{code:C.invalid_type,expected:M.nan,received:s.parsedType}),B}return{status:"valid",value:e.data}}}oi.create=n=>new oi({typeName:O.ZodNaN,...V(n)});class ui extends K{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Hs extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?B:i.status==="dirty"?(t.dirty(),yn(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?B:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new Hs({in:e,out:t,typeName:O.ZodPipeline})}}class hs extends K{_parse(e){const t=this._def.innerType._parse(e),s=r=>(qt(r)&&(r.value=Object.freeze(r.value)),r);return rs(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}hs.create=(n,e)=>new hs({innerType:n,typeName:O.ZodReadonly,...V(e)});function ci(n,e){const t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function su(n,e={},t){return n?vn.create().superRefine((s,r)=>{const i=n(s);if(i instanceof Promise)return i.then(o=>{if(!o){const a=ci(e,s),u=a.fatal??t??!0;r.addIssue({code:"custom",...a,fatal:u})}});if(!i){const o=ci(e,s),a=o.fatal??t??!0;r.addIssue({code:"custom",...o,fatal:a})}}):vn.create()}var O;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(O||(O={}));const li=(n,e={message:`Input not instance of ${n.name}`})=>su(t=>t instanceof n,e),f=He.create,E=Jt.create,St=Bs.create,H=vn.create;ut.create;const J=je.create,w=de.create,Ye=as.create,ve=Js.create;os.create,vt.create;const se=us.create,ru=cs.create,I=ls.create,pe=bt.create;ds.create,Ke.create,It.create;function iu(){return{}}function au(n,e){var s,r;const t={type:"array"};return((r=(s=n.type)==null?void 0:s._def)==null?void 0:r.typeName)!==O.ZodAny&&(t.items=Q(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&ne(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&ne(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(ne(t,"minItems",n.exactLength.value,n.exactLength.message,e),ne(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function ou(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const s of n.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?ne(t,"minimum",s.value,s.message,e):ne(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),ne(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?ne(t,"maximum",s.value,s.message,e):ne(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),ne(t,"maximum",s.value,s.message,e));break;case"multipleOf":ne(t,"multipleOf",s.value,s.message,e);break}return t}function uu(){return{type:"boolean"}}function cu(n,e){return Q(n.type._def,e)}const lu=(n,e)=>Q(n.innerType._def,e);function di(n,e,t){const s=t??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,i)=>di(n,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return du(n,e)}}const du=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const s of n.checks)switch(s.kind){case"min":ne(t,"minimum",s.value,s.message,e);break;case"max":ne(t,"maximum",s.value,s.message,e);break}return t};function pu(n,e){return{...Q(n.innerType._def,e),default:n.defaultValue()}}function fu(n,e,t){return e.effectStrategy==="input"?Q(n.schema._def,e,t):{}}function hu(n){return{type:"string",enum:[...n.values]}}const mu=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function gu(n,e){const t=[Q(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Q(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return t.forEach(i=>{if(mu(i))r.push(...i.allOf),i.unevaluatedProperties===void 0&&(s=void 0);else{let o=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:a,...u}=i;o=u}else s=void 0;r.push(o)}}),r.length?{allOf:r,...s}:void 0}function yu(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let Ws;const Tt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ws===void 0&&(Ws=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ws),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function pi(n,e){const t={type:"string"};function s(r){return e.patternStrategy==="escape"?_u(r):r}if(n.checks)for(const r of n.checks)switch(r.kind){case"min":ne(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":ne(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Pe(t,"email",r.message,e);break;case"format:idn-email":Pe(t,"idn-email",r.message,e);break;case"pattern:zod":De(t,Tt.email,r.message,e);break}break;case"url":Pe(t,"uri",r.message,e);break;case"uuid":Pe(t,"uuid",r.message,e);break;case"regex":De(t,r.regex,r.message,e);break;case"cuid":De(t,Tt.cuid,r.message,e);break;case"cuid2":De(t,Tt.cuid2,r.message,e);break;case"startsWith":De(t,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":De(t,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":Pe(t,"date-time",r.message,e);break;case"date":Pe(t,"date",r.message,e);break;case"time":Pe(t,"time",r.message,e);break;case"duration":Pe(t,"duration",r.message,e);break;case"length":ne(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),ne(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{De(t,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&Pe(t,"ipv4",r.message,e),r.version!=="v4"&&Pe(t,"ipv6",r.message,e);break}case"emoji":De(t,Tt.emoji,r.message,e);break;case"ulid":{De(t,Tt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Pe(t,"binary",r.message,e);break}case"contentEncoding:base64":{ne(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{De(t,Tt.base64,r.message,e);break}}break}case"nanoid":De(t,Tt.nanoid,r.message,e)}return t}const _u=n=>Array.from(n).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Pe=(n,e,t,s)=>{var r;n.format||(r=n.anyOf)!=null&&r.some(i=>i.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&s.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&s.errorMessages&&{errorMessage:{format:t}}})):ne(n,"format",e,t,s)},De=(n,e,t,s)=>{var r;n.pattern||(r=n.allOf)!=null&&r.some(i=>i.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&s.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:fi(e,s),...t&&s.errorMessages&&{errorMessage:{pattern:t}}})):ne(n,"pattern",fi(e,s),t,s)},fi=(n,e)=>{var l;const t=typeof n=="function"?n():n;if(!e.applyRegexFlags||!t.flags)return t.source;const s={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=s.i?t.source.toLowerCase():t.source;let i="",o=!1,a=!1,u=!1;for(let p=0;p<r.length;p++){if(o){i+=r[p],o=!1;continue}if(s.i){if(a){if(r[p].match(/[a-z]/)){u?(i+=r[p],i+=`${r[p-2]}-${r[p]}`.toUpperCase(),u=!1):r[p+1]==="-"&&((l=r[p+2])!=null&&l.match(/[a-z]/))?(i+=r[p],u=!0):i+=`${r[p]}${r[p].toUpperCase()}`;continue}}else if(r[p].match(/[a-z]/)){i+=`[${r[p]}${r[p].toUpperCase()}]`;continue}}if(s.m){if(r[p]==="^"){i+=`(^|(?<=[\r
|
|
4
|
-
]))`;continue}else if(r[
|
|
5
|
-
]))`;continue}}if(s.s&&r[
|
|
6
|
-
`:`[${r[
|
|
7
|
-
]`;continue}i+=r[p],r[p]==="\\"?o=!0:a&&r[p]==="]"?a=!1:!a&&r[p]==="["&&(a=!0)}try{const p=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`),t.source}return i};function hi(n,e){var s,r,i,o;if(e.target==="openApi3"&&((s=n.keyType)==null?void 0:s._def.typeName)===O.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((a,u)=>({...a,[u]:Q(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:Q(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(((r=n.keyType)==null?void 0:r._def.typeName)===O.ZodString&&((i=n.keyType._def.checks)!=null&&i.length)){const a=Object.entries(pi(n.keyType._def,e)).reduce((u,[l,p])=>l==="type"?u:{...u,[l]:p},{});return{...t,propertyNames:a}}else if(((o=n.keyType)==null?void 0:o._def.typeName)===O.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};return t}function vu(n,e){if(e.mapStrategy==="record")return hi(n,e);const t=Q(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=Q(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,s],minItems:2,maxItems:2}}}function bu(n){const e=n.values,s=Object.keys(n.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),r=Array.from(new Set(s.map(i=>typeof i)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:s}}function wu(){return{not:{}}}function Iu(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ms={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Su(n,e){if(e.target==="openApi3")return mi(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(s=>s._def.typeName in ms&&(!s._def.checks||!s._def.checks.length))){const s=t.reduce((r,i)=>{const o=ms[i._def.typeName];return o&&!r.includes(o)?[...r,o]:r},[]);return{type:s.length>1?s:s[0]}}else if(t.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=t.reduce((r,i)=>{const o=typeof i._def.value;switch(o){case"string":case"number":case"boolean":return[...r,o];case"bigint":return[...r,"integer"];case"object":if(i._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(s.length===t.length){const r=s.filter((i,o,a)=>a.indexOf(i)===o);return{type:r.length>1?r:r[0],enum:t.reduce((i,o)=>i.includes(o._def.value)?i:[...i,o._def.value],[])}}}else if(t.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((s,r)=>[...s,...r._def.values.filter(i=>!s.includes(i))],[])};return mi(n,e)}const mi=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((s,r)=>Q(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return t.length?{anyOf:t}:void 0};function Tu(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:ms[n.innerType._def.typeName],nullable:!0}:{type:[ms[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=Q(n.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const t=Q(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function xu(n,e){const t={type:"number"};if(!n.checks)return t;for(const s of n.checks)switch(s.kind){case"int":t.type="integer",Wr(t,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?ne(t,"minimum",s.value,s.message,e):ne(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),ne(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?ne(t,"maximum",s.value,s.message,e):ne(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),ne(t,"maximum",s.value,s.message,e));break;case"multipleOf":ne(t,"multipleOf",s.value,s.message,e);break}return t}function ku(n,e){return e.removeAdditionalStrategy==="strict"?n.catchall._def.typeName==="ZodNever"?n.unknownKeys!=="strict":Q(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:n.catchall._def.typeName==="ZodNever"?n.unknownKeys==="passthrough":Q(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Au(n,e){const t={type:"object",...Object.entries(n.shape()).reduce((s,[r,i])=>{var u;if(i===void 0||i._def===void 0)return s;const o=[...e.currentPath,"properties",r],a=Q(i._def,{...e,currentPath:o,propertyPath:o});if(a===void 0)return s;if(e.openaiStrictMode&&i.isOptional()&&!i.isNullable()&&typeof((u=i._def)==null?void 0:u.defaultValue)>"u")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:{...s.properties,[r]:a},required:i.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,r]}},{properties:{},required:[]}),additionalProperties:ku(n,e)};return t.required.length||delete t.required,t}const Cu=(n,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return Q(n.innerType._def,{...e,currentPath:e.currentPath});const t=Q(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},Ou=(n,e)=>{if(e.pipeStrategy==="input")return Q(n.in._def,e);if(e.pipeStrategy==="output")return Q(n.out._def,e);const t=Q(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=Q(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,s].filter(r=>r!==void 0)}};function Eu(n,e){return Q(n.type._def,e)}function Ru(n,e){const s={type:"array",uniqueItems:!0,items:Q(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&ne(s,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&ne(s,"maxItems",n.maxSize.value,n.maxSize.message,e),s}function Nu(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,s)=>Q(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[]),additionalItems:Q(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,s)=>Q(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[])}}function Pu(){return{not:{}}}function Du(){return{}}const Mu=(n,e)=>Q(n.innerType._def,e);function Q(n,e,t=!1){var o;const s=e.seen.get(n);if(e.override){const a=(o=e.override)==null?void 0:o.call(e,n,e,s,t);if(a!==Co)return a}if(s&&!t){const a=Fu(s,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}const r={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,r);const i=ju(n,n.typeName,e,t);return i&&Uu(n,e,i),r.jsonSchema=i,i}const Fu=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"extract-to-root":const t=n.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=n.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:$u(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((s,r)=>e.currentPath[r]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},$u=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},ju=(n,e,t,s)=>{switch(e){case O.ZodString:return pi(n,t);case O.ZodNumber:return xu(n,t);case O.ZodObject:return Au(n,t);case O.ZodBigInt:return ou(n,t);case O.ZodBoolean:return uu();case O.ZodDate:return di(n,t);case O.ZodUndefined:return Pu();case O.ZodNull:return Iu(t);case O.ZodArray:return au(n,t);case O.ZodUnion:case O.ZodDiscriminatedUnion:return Su(n,t);case O.ZodIntersection:return gu(n,t);case O.ZodTuple:return Nu(n,t);case O.ZodRecord:return hi(n,t);case O.ZodLiteral:return yu(n,t);case O.ZodEnum:return hu(n);case O.ZodNativeEnum:return bu(n);case O.ZodNullable:return Tu(n,t);case O.ZodOptional:return Cu(n,t);case O.ZodMap:return vu(n,t);case O.ZodSet:return Ru(n,t);case O.ZodLazy:return Q(n.getter()._def,t);case O.ZodPromise:return Eu(n,t);case O.ZodNaN:case O.ZodNever:return wu();case O.ZodEffects:return fu(n,t,s);case O.ZodAny:return iu();case O.ZodUnknown:return Du();case O.ZodDefault:return pu(n,t);case O.ZodBranded:return cu(n,t);case O.ZodReadonly:return Mu(n,t);case O.ZodCatch:return lu(n,t);case O.ZodPipeline:return Ou(n,t);case O.ZodFunction:case O.ZodVoid:case O.ZodSymbol:return;default:return(r=>{})()}},Uu=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),Lu=(n,e)=>{const t=Ro(e),s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,r=Q(n._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(r.title=i);const o=(()=>{if(Eo(t.definitions))return;const u={},l=new Set;for(let p=0;p<500;p++){const d=Object.entries(t.definitions).filter(([m])=>!l.has(m));if(d.length===0)break;for(const[m,g]of d)u[m]=Q(Us(g),{...t,currentPath:[...t.basePath,t.definitionPath,m]},!0)??{},l.add(m)}return u})(),a=s===void 0?o?{...r,[t.definitionPath]:o}:r:t.nameStrategy==="duplicate-ref"?{...r,...o||t.seenRefs.size?{[t.definitionPath]:{...o,...t.seenRefs.size?{[s]:r}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...o,[s]:r}};return t.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function zu(n,{parser:e,callback:t}){const s={...n};return Object.defineProperties(s,{$brand:{value:"auto-parseable-tool",enumerable:!1},$parseRaw:{value:e,enumerable:!1},$callback:{value:t,enumerable:!1}}),s}function Bu(n){if(n.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${n.type?`'${n.type}'`:"undefined"}`);const e=structuredClone(n);return Xe(e,[],e)}function Ks(n){if(typeof n=="boolean")return!1;if(n.type==="null")return!0;for(const e of n.oneOf??[])if(Ks(e))return!0;for(const e of n.anyOf??[])if(Ks(e))return!0;return!1}function Xe(n,e,t){if(typeof n=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!xt(n))throw new TypeError(`Expected ${JSON.stringify(n)} to be an object; path=${e.join("/")}`);const s=n.$defs;if(xt(s))for(const[m,g]of Object.entries(s))Xe(g,[...e,"$defs",m],t);const r=n.definitions;if(xt(r))for(const[m,g]of Object.entries(r))Xe(g,[...e,"definitions",m],t);n.type==="object"&&!("additionalProperties"in n)&&(n.additionalProperties=!1);const o=n.required??[],a=n.properties;if(xt(a)){for(const[m,g]of Object.entries(a))if(!Ks(g)&&!o.includes(m))throw new Error(`Zod field at \`${[...e,"properties",m].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`);n.required=Object.keys(a),n.properties=Object.fromEntries(Object.entries(a).map(([m,g])=>[m,Xe(g,[...e,"properties",m],t)]))}const u=n.items;xt(u)&&(n.items=Xe(u,[...e,"items"],t));const l=n.anyOf;Array.isArray(l)&&(n.anyOf=l.map((m,g)=>Xe(m,[...e,"anyOf",String(g)],t)));const p=n.allOf;if(Array.isArray(p))if(p.length===1){const m=Xe(p[0],[...e,"allOf","0"],t);Object.assign(n,m),delete n.allOf}else n.allOf=p.map((m,g)=>Xe(m,[...e,"allOf",String(g)],t));n.default===null&&delete n.default;const d=n.$ref;if(d&&qu(n,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);const m=Zu(t,d);if(typeof m=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!xt(m))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(m)}`);return Object.assign(n,{...m,...n}),delete n.$ref,Xe(n,e,t)}return n}function Zu(n,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const t=e.slice(2).split("/");let s=n;for(const r of t){if(!xt(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);const i=s[r];if(i===void 0)throw new Error(`Key ${r} not found while resolving ${e}`);s=i}return s}function xt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function qu(n,e){let t=0;for(const s in n)if(t++,t>e)return!0;return!1}function gi(n,e){return Lu(n,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function yi(n){return Bu(ko(n,{target:"draft-7"}))}function _i(n){return"_zod"in n}function Ju(n,e,t){return Ao({type:"json_schema",...t,name:e,strict:!0,schema:_i(n)?yi(n):gi(n,{name:e})},s=>n.parse(JSON.parse(s)))}function Gu(n){return zu({type:"function",name:n.name,parameters:_i(n.parameters)?yi(n.parameters):gi(n.parameters,{name:n.name}),strict:!0,...n.description?{description:n.description}:void 0},{callback:n.function,parser:e=>n.parameters.parse(JSON.parse(e))})}class ct extends Error{constructor(t,s){super(t);S(this,"state");this.state=s}}class Vu extends ct{}class vi extends ct{}class Se extends ct{}class re extends ct{}class bi extends ct{constructor(t,s,r){super(t,r);S(this,"error");this.error=s}}class Hu extends ct{constructor(t,s,r){super(t,r);S(this,"error");this.error=s}}class wi extends ct{constructor(t,s,r){super(t,r);S(this,"result");this.result=s}}class Ys extends ct{constructor(t,s,r){super(t,r);S(this,"result");this.result=s}}function bf(n){return n}function Vt(n){var t;if(typeof n!="object"||n===null)return;const e=n;return((t=e._zod)==null?void 0:t.def)||e._def||e.def}function gs(n){const e=Vt(n);if(!e)return;const t=typeof e.typeName=="string"&&e.typeName||typeof e.type=="string"&&e.type;if(typeof t!="string")return;const s=t.toLowerCase();return s.startsWith("zod")?s.slice(3):s}function kt(n){return Vt(n)?gs(n)==="object":!1}function Wu(n){return typeof n=="object"&&n!==null&&"input"in n&&typeof n.input=="string"}const Ku="http://json-schema.org/draft-07/schema#",Yu=new Set(["optional"]),Xu=new Set(["brand","branded","catch","default","effects","pipeline","pipe","prefault","readonly","refinement","transform"]),Ii={string:{type:"string"},number:{type:"number"},bigint:{type:"integer"},boolean:{type:"boolean"},date:{type:"string",format:"date-time"}};function Si(n){return typeof n=="object"&&n!==null&&n.type==="object"&&"properties"in n&&"additionalProperties"in n}function Qu(n){const e=Ti(n);if(e)return Array.isArray(e.required)||(e.required=[]),typeof e.additionalProperties>"u"&&(e.additionalProperties=!1),typeof e.$schema!="string"&&(e.$schema=Ku),e}function Ti(n){const e=dc(n);if(!e)return;const t={},s=[];for(const[r,i]of Object.entries(e)){const{schema:o,optional:a}=ec(i);if(!o)return;t[r]=o,a||s.push(r)}return{type:"object",properties:t,required:s,additionalProperties:!1}}function ec(n){let e=Xs(n),t=!1;for(;Yu.has(gs(e)??"");){t=!0;const s=Vt(e),r=Xs(s==null?void 0:s.innerType);if(!r||r===e)break;e=r}return{schema:Ue(e),optional:t}}function Ue(n){if(n===void 0)return;const e=Xs(n),t=gs(e),s=Vt(e);if(t){if(t in Ii)return Ii[t];switch(t){case"object":return Ti(e);case"array":return tc(s);case"tuple":return nc(s);case"union":return sc(s);case"intersection":return rc(s);case"literal":return cc(s);case"enum":case"nativeenum":return lc(s);case"record":return ic(s);case"map":return ac(s);case"set":return oc(s);case"nullable":return uc(s);default:return}}}function tc(n){const e=Ue(xi(n,"element","items","type"));return e?{type:"array",items:e}:void 0}function nc(n){const e=ki(n==null?void 0:n.items).map(s=>Ue(s)).filter(Boolean);if(!e.length)return;const t={type:"array",items:e,minItems:e.length};return n!=null&&n.rest||(t.maxItems=e.length),t}function sc(n){const e=ki((n==null?void 0:n.options)??(n==null?void 0:n.schemas)).map(t=>Ue(t)).filter(Boolean);return e.length?{anyOf:e}:void 0}function rc(n){const e=Ue(n==null?void 0:n.left),t=Ue(n==null?void 0:n.right);return e&&t?{allOf:[e,t]}:void 0}function ic(n){const e=Ue((n==null?void 0:n.valueType)??(n==null?void 0:n.values));return e?{type:"object",additionalProperties:e}:void 0}function ac(n){const e=Ue((n==null?void 0:n.valueType)??(n==null?void 0:n.values));return e?{type:"array",items:e}:void 0}function oc(n){const e=Ue(n==null?void 0:n.valueType);return e?{type:"array",items:e,uniqueItems:!0}:void 0}function uc(n){const e=Ue((n==null?void 0:n.innerType)??(n==null?void 0:n.type));return e?{anyOf:[e,{type:"null"}]}:void 0}function Xs(n){let e=n;for(;Xu.has(gs(e)??"");){const t=Vt(e),s=(t==null?void 0:t.innerType)??(t==null?void 0:t.schema)??(t==null?void 0:t.base)??(t==null?void 0:t.type)??(t==null?void 0:t.wrapped)??(t==null?void 0:t.underlying);if(!s||s===e)return e;e=s}return e}function xi(n,...e){if(n){for(const t of e)if(t in n&&n[t]!==void 0)return n[t]}}function ki(n){return Array.isArray(n)?n:n===void 0?[]:[n]}function cc(n){if(!n)return;const e=xi(n,"value","literal");if(e!==void 0)return{const:e,type:e===null?"null":typeof e}}function lc(n){if(n){if(Array.isArray(n.values))return{enum:n.values};if(Array.isArray(n.options))return{enum:n.options};if(n.values&&typeof n.values=="object")return{enum:Object.values(n.values)};if(n.enum&&typeof n.enum=="object")return{enum:Object.values(n.enum)}}}function dc(n){if(typeof n!="object"||n===null)return;const e=n;if(e.shape&&typeof e.shape=="object")return e.shape;if(typeof e.shape=="function")try{return e.shape()}catch{return}const t=Vt(e),s=t==null?void 0:t.shape;if(s&&typeof s=="object")return s;if(typeof s=="function")try{return s()}catch{return}}const pc=Gu,fc=Ju;function Ai(n){return Qu(n)}function ys(n){if(n=n.replace(/\s/g,"_"),n=n.replace(/[^a-zA-Z0-9]/g,"_"),n.length===0)throw new Error("Tool name cannot be empty");return n}function Qs(n,e){const t=s=>JSON.parse(s);if(kt(n)){const s=i=>{const o=Ai(n);if(o)return{schema:o,parser:u=>n.parse(JSON.parse(u))};const a=i instanceof Error?` Upstream helper error: ${i.message}`:"";throw new re(`Unable to convert the provided Zod schema to JSON Schema. Ensure that the \`zod\` package is available at runtime or provide a JSON schema object instead.${a}`)};let r;try{r=pc({name:e,parameters:n,function:()=>{},description:""})}catch(i){return s(i)}return Si(r.parameters)?{schema:r.parameters,parser:r.$parseRaw}:s()}else if(typeof n=="object"&&n!==null)return{schema:n,parser:t};throw new re("Input type is not a ZodObject or a valid JSON schema")}function Ci(n){if(n==="text")return"text";if(kt(n)){const e=(s,r)=>{const i=Ai(n);if(i)return{type:(s==null?void 0:s.type)??"json_schema",name:(s==null?void 0:s.name)??"output",strict:(s==null?void 0:s.strict)??!1,schema:i};const o=r instanceof Error?` Upstream helper error: ${r.message}`:"";throw new re(`Unable to convert the provided Zod schema to JSON Schema. Ensure that the \`zod\` package is available at runtime or provide a JSON schema object instead.${o}`)};let t;try{t=fc(n,"output")}catch(s){return e(void 0,s)}return Si(t.schema)?{type:t.type,name:t.name,strict:t.strict||!1,schema:t.schema}:e(t)}return n}function hc(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var _s={exports:{}},er,Oi;function mc(){if(Oi)return er;Oi=1;var n=1e3,e=n*60,t=e*60,s=t*24,r=s*7,i=s*365.25;er=function(p,d){d=d||{};var m=typeof p;if(m==="string"&&p.length>0)return o(p);if(m==="number"&&isFinite(p))return d.long?u(p):a(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var d=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(d){var m=parseFloat(d[1]),g=(d[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return m*i;case"weeks":case"week":case"w":return m*r;case"days":case"day":case"d":return m*s;case"hours":case"hour":case"hrs":case"hr":case"h":return m*t;case"minutes":case"minute":case"mins":case"min":case"m":return m*e;case"seconds":case"second":case"secs":case"sec":case"s":return m*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;default:return}}}}function a(p){var d=Math.abs(p);return d>=s?Math.round(p/s)+"d":d>=t?Math.round(p/t)+"h":d>=e?Math.round(p/e)+"m":d>=n?Math.round(p/n)+"s":p+"ms"}function u(p){var d=Math.abs(p);return d>=s?l(p,d,s,"day"):d>=t?l(p,d,t,"hour"):d>=e?l(p,d,e,"minute"):d>=n?l(p,d,n,"second"):p+" ms"}function l(p,d,m,g){var _=d>=m*1.5;return Math.round(p/m)+" "+g+(_?"s":"")}return er}var tr,Ei;function gc(){if(Ei)return tr;Ei=1;function n(e){s.debug=s,s.default=s,s.coerce=l,s.disable=a,s.enable=i,s.enabled=u,s.humanize=mc(),s.destroy=p,Object.keys(e).forEach(d=>{s[d]=e[d]}),s.names=[],s.skips=[],s.formatters={};function t(d){let m=0;for(let g=0;g<d.length;g++)m=(m<<5)-m+d.charCodeAt(g),m|=0;return s.colors[Math.abs(m)%s.colors.length]}s.selectColor=t;function s(d){let m,g=null,_,T;function y(...h){if(!y.enabled)return;const v=y,b=Number(new Date),N=b-(m||b);v.diff=N,v.prev=m,v.curr=b,m=b,h[0]=s.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let x=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(D,U)=>{if(D==="%%")return"%";x++;const G=s.formatters[U];if(typeof G=="function"){const L=h[x];D=G.call(v,L),h.splice(x,1),x--}return D}),s.formatArgs.call(v,h),(v.log||s.log).apply(v,h)}return y.namespace=d,y.useColors=s.useColors(),y.color=s.selectColor(d),y.extend=r,y.destroy=s.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(_!==s.namespaces&&(_=s.namespaces,T=s.enabled(d)),T),set:h=>{g=h}}),typeof s.init=="function"&&s.init(y),y}function r(d,m){const g=s(this.namespace+(typeof m>"u"?":":m)+d);return g.log=this.log,g}function i(d){s.save(d),s.namespaces=d,s.names=[],s.skips=[];const m=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const g of m)g[0]==="-"?s.skips.push(g.slice(1)):s.names.push(g)}function o(d,m){let g=0,_=0,T=-1,y=0;for(;g<d.length;)if(_<m.length&&(m[_]===d[g]||m[_]==="*"))m[_]==="*"?(T=_,y=g,_++):(g++,_++);else if(T!==-1)_=T+1,y++,g=y;else return!1;for(;_<m.length&&m[_]==="*";)_++;return _===m.length}function a(){const d=[...s.names,...s.skips.map(m=>"-"+m)].join(",");return s.enable(""),d}function u(d){for(const m of s.skips)if(o(d,m))return!1;for(const m of s.names)if(o(d,m))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return s.enable(s.load()),s}return tr=n,tr}var Ri;function yc(){return Ri||(Ri=1,function(n,e){e.formatArgs=s,e.save=r,e.load=i,e.useColors=t,e.storage=o(),e.destroy=(()=>{let u=!1;return()=>{u||(u=!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"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let u;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function s(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+n.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;u.splice(1,0,l,"color: inherit");let p=0,d=0;u[0].replace(/%[a-zA-Z%]/g,m=>{m!=="%%"&&(p++,m==="%c"&&(d=p))}),u.splice(d,0,l)}e.log=console.debug||console.log||(()=>{});function r(u){try{u?e.storage.setItem("debug",u):e.storage.removeItem("debug")}catch{}}function i(){let u;try{u=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u=process.env.DEBUG),u}function o(){try{return localStorage}catch{}}n.exports=gc()(e);const{formatters:a}=n.exports;a.j=function(u){try{return JSON.stringify(u)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}(_s,_s.exports)),_s.exports}var _c=yc();const vc=hc(_c);function Ni(){return Ec()}function Pi(n){const e=Ni();return typeof e<"u"&&(e[n]==="true"||e[n]==="1")}const Di={get disabled(){return!0}},Mi={get dontLogModelData(){return Pi("OPENAI_AGENTS_DONT_LOG_MODEL_DATA")},get dontLogToolData(){return Pi("OPENAI_AGENTS_DONT_LOG_TOOL_DATA")}},bc=Mi.dontLogModelData,wc=Mi.dontLogToolData;function Fi(n="openai-agents"){return{namespace:n,debug:vc(n),error:console.error,warn:console.warn,dontLogModelData:bc,dontLogToolData:wc}}const F=Fi("openai-agents:core"),$i=20;function lt(n){if(n==null)return String(n);if(ji(n))return In(new Uint8Array(n));if(wn(n)){const e=n;return In(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}if(typeof n=="string")return n;if(typeof n=="object")try{return JSON.stringify(n,Sc)}catch{return"[object with circular references]"}return String(n)}function ji(n){if(n instanceof ArrayBuffer)return!0;const e=globalThis.SharedArrayBuffer;return!!(e&&n instanceof e)}function wn(n){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n)}function vs(n){return typeof n=="object"&&n!==null&&n.type==="Buffer"&&Array.isArray(n.data)}function nr(n){const e=globalThis.Buffer;return!!(e&&typeof e.isBuffer=="function"&&e.isBuffer(n))}function In(n){if(n.length===0)return"[byte array (0 bytes)]";const e=Math.min(n.length,$i),t=[];for(let i=0;i<e;i++)t.push(Ic(n[i]));const s=n.length>$i?" …":"";return`[byte array ${t.join(" ")}${s} (${n.length} bytes)]`}function Ic(n){return`0x${n.toString(16).padStart(2,"0")}`}function Sc(n,e){if(ji(e))return In(new Uint8Array(e));if(wn(e)){const t=e;return In(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}return vs(e)?In(Uint8Array.from(e.data)):e}function sr(n){return!!n&&typeof n=="object"&&typeof n.create=="function"}const rr=new WeakMap,Tc=new WeakMap,bs=new WeakMap;function Ui(n){const e=Tc.get(n);if(e)return e;if(typeof n.computer=="function"||sr(n.computer))return n.computer}function Li(n,e,t){let s=bs.get(e);s||(s=new Map,bs.set(e,s)),s.set(n,t)}async function zi(n){const{tool:e,runContext:t}=n,s=e;let r=rr.get(s);r||(r=new WeakMap,rr.set(s,r));const i=r.get(t);if(i)return Li(e,t,i),i.computer;const o=Ui(e),a=o&&sr(o)?o:sr(e.computer)?e.computer:void 0,u=typeof o=="function"?o:(a==null?void 0:a.create)??(typeof e.computer=="function"?e.computer:void 0),l=a==null?void 0:a.dispose,p=u&&typeof u=="function"?await u({runContext:t}):e.computer;if(!p)throw new re("The computer tool did not provide a computer instance.");const d={computer:p,dispose:l};return r.set(t,d),Li(e,t,d),e.computer=p,p}async function Bi({runContext:n}){const e=bs.get(n);if(!e)return;bs.delete(n);const t=[];for(const[s,r]of e.entries()){const i=rr.get(s);i==null||i.delete(n);const o=Ui(s);o&&(s.computer=o),r.dispose&&t.push(async()=>{var a;await((a=r.dispose)==null?void 0:a.call(r,{runContext:n,computer:r.computer}))})}for(const s of t)try{await s()}catch(r){F.warn(`Failed to dispose computer for run context: ${r}`)}}function xc(n,e){return`An error occurred while running the tool. Please try again. Error: ${e instanceof Error?e.toString():String(e)}`}function Ht(n){const e=n.name?ys(n.name):ys(n.execute.name),t=typeof n.errorFunction>"u"?xc:n.errorFunction;if(!e)throw new Error("Tool name cannot be empty. Either name your function or provide a name in the options.");const s=n.strict??!0;if(!s&&kt(n.parameters))throw new re("Strict mode is required for Zod parameters");const{parser:r,schema:i}=Qs(n.parameters,e);async function o(p,d,m){const[g,_]=await le(()=>r(d));if(g!==null)throw F.dontLogToolData?F.debug(`Invalid JSON input for tool ${e}`):F.debug(`Invalid JSON input for tool ${e}: ${d}`),new Se("Invalid JSON input for tool");F.dontLogToolData?F.debug(`Invoking tool ${e}`):F.debug(`Invoking tool ${e} with input ${d}`);const T=await n.execute(_,p,m),y=lt(T);return F.dontLogToolData?F.debug(`Tool ${e} completed`):F.debug(`Tool ${e} returned: ${y}`),T}async function a(p,d,m){return o(p,d,m).catch(g=>{if(t){const _=An();return _==null||_.setError({message:"Error running tool (non-fatal)",data:{tool_name:e,error:g.toString()}}),t(p,g)}throw g})}const u=typeof n.needsApproval=="function"?n.needsApproval:async()=>typeof n.needsApproval=="boolean"?n.needsApproval:!1,l=typeof n.isEnabled=="function"?async(p,d)=>{const m=n.isEnabled;return!!await m({runContext:p,agent:d})}:async()=>typeof n.isEnabled=="boolean"?n.isEnabled:!0;return{type:"function",name:e,description:n.description,parameters:i,strict:s,invoke:a,needsApproval:u,isEnabled:l}}w({name:f(),description:f().optional(),inputSchema:w({type:I("object"),properties:se(f(),H()),required:J(f()),additionalProperties:St()})});const ir={},ar={},kc=({server:n,agent:e})=>n.toolFilter&&typeof n.toolFilter=="function"&&e?`${n.name}:${e.name}`:n.name;async function Ac({server:n,convertSchemasToStrict:e,runContext:t,agent:s,generateMCPToolCacheKey:r}){const i=(r||kc)({server:n,agent:s,runContext:t});if(n.cacheToolsList&&ir[i])return ir[i].map(a=>Zi(a,n,e));const o=async a=>{const u=await n.listTools();let l=u;if(t&&s){const d={runContext:t,agent:s,serverName:n.name},m=[];for(const g of u){const _=n.toolFilter;if(_)if(typeof _=="function"){if(!await _(d,g)){F.debug(`MCP Tool (server: ${n.name}, tool: ${g.name}) is blocked by the callable filter.`);continue}}else{const T=_.allowedToolNames??[],y=_.blockedToolNames??[];if(T.length>0||y.length>0){const h=T.length>0?T.includes(g.name):!0,v=y.length>0?y.includes(g.name):!1;if(!h||v){v?F.debug(`MCP Tool (server: ${n.name}, tool: ${g.name}) is blocked by the static filter.`):h||F.debug(`MCP Tool (server: ${n.name}, tool: ${g.name}) is not allowed by the static filter.`);continue}}}m.push(g)}l=m}a&&(a.spanData.result=l.map(d=>d.name));const p=l.map(d=>Zi(d,n,e));return n.cacheToolsList&&(ir[i]=l,ar[n.name]||(ar[n.name]=new Set),ar[n.name].add(i)),p};return Xt()?Ll(o,{data:{server:n.name}}):o()}async function Cc(n,e,t,s=!1){const r=Array.isArray(n)?{mcpServers:n,runContext:e,agent:t,convertSchemasToStrict:s}:n,{mcpServers:i,convertSchemasToStrict:o=!1,runContext:a,agent:u,generateMCPToolCacheKey:l}=r,p=[],d=new Set;for(const m of i){const g=await Ac({server:m,convertSchemasToStrict:o,runContext:a,agent:u,generateMCPToolCacheKey:l}),T=[...new Set(g.map(y=>y.name))].filter(y=>d.has(y));if(T.length>0)throw new re(`Duplicate tool names found across MCP servers: ${T.join(", ")}`);for(const y of g)d.add(y.name),p.push(y)}return p}function Zi(n,e,t){var o,a,u,l;async function s(p,d){let m={};typeof p=="string"&&p?m=JSON.parse(p):typeof p=="object"&&p!=null&&(m=p);const g=An();g&&(g.spanData.mcp_data={server:e.name});const _=await e.callTool(n.name,m);return _.length===1?_[0]:_}const r={...n.inputSchema,type:((o=n.inputSchema)==null?void 0:o.type)??"object",properties:((a=n.inputSchema)==null?void 0:a.properties)??{},required:((u=n.inputSchema)==null?void 0:u.required)??[],additionalProperties:((l=n.inputSchema)==null?void 0:l.additionalProperties)??!1};if(t||r.additionalProperties===!0)try{const p=Oc(r);return Ht({name:n.name,description:n.description||"",parameters:p,strict:!0,execute:s})}catch(p){F.warn(`Error converting MCP schema to strict mode: ${p}`)}const i={...r,additionalProperties:!0};return Ht({name:n.name,description:n.description||"",parameters:i,strict:!1,execute:s})}function Oc(n){const e={...n,additionalProperties:!1};return e.required||(e.required=[]),e}function Ec(){return{}}class ws{constructor(){R(this,en,new EventTarget);R(this,Nt,new Map)}on(e,t){const s=e;let r=c(this,Nt).get(s);r||(r=new Map,c(this,Nt).set(s,r));let i=r.get(t);i||(i=new Set,r.set(t,i));const o=a=>t(...a.detail??[]);return i.add(o),c(this,en).addEventListener(s,o),this}off(e,t){const s=e,r=c(this,Nt).get(s),i=r==null?void 0:r.get(t);if(i!=null&&i.size){for(const o of i)c(this,en).removeEventListener(s,o);r==null||r.delete(t),(r==null?void 0:r.size)===0&&c(this,Nt).delete(s)}return this}emit(e,...t){const s=new CustomEvent(e,{detail:t});return c(this,en).dispatchEvent(s)}once(e,t){const s=(...r)=>{this.off(e,s),t(...r)};return this.on(e,s),this}}en=new WeakMap,Nt=new WeakMap;const qi=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)}),Rc=class{constructor(){}pipeTo(e,t){}pipeThrough(e,t){}},Nc=globalThis.ReadableStream,Pc=globalThis.TransformStream;class Dc{constructor(){S(this,"context",null)}run(e,t){return this.context=e,t()}getStore(){return this.context}enterWith(e){this.context=e}}class Mc{constructor(){}setTimeout(e,t){const s=setTimeout(e,t);return s.ref=typeof s.ref=="function"?s.ref:()=>s,s.unref=typeof s.unref=="function"?s.unref:()=>s,s.hasRef=typeof s.hasRef=="function"?s.hasRef:()=>!0,s.refresh=typeof s.refresh=="function"?s.refresh:()=>s,s}clearTimeout(e){window.clearTimeout(e)}}const Fc=new Mc;class or{on(e,t){return this.eventEmitter.on(e,t),this.eventEmitter}off(e,t){return this.eventEmitter.off(e,t),this.eventEmitter}emit(e,...t){return this.eventEmitter.emit(e,...t)}once(e,t){return this.eventEmitter.once(e,t),this.eventEmitter}}class $c extends or{constructor(){super(...arguments);S(this,"eventEmitter",new ws)}}class jc extends or{constructor(){super(...arguments);S(this,"eventEmitter",new ws)}}const Uc="OPENAI_DEFAULT_MODEL";function Is(n){return n.startsWith("gpt-5-chat")?!1:n.startsWith("gpt-5")}function Ji(){return Is(Gi())}function Gi(){var e;return((e=Ni()[Uc])==null?void 0:e.toLowerCase())??"gpt-4.1"}function Lc(n){const e=Gi();return Is(e)?{reasoning:{effort:"low"},text:{verbosity:"low"}}:{}}function Vi(n){return JSON.stringify({assistant:n.name})}function zc(n){return`transfer_to_${ys(n.name)}`}function Bc(n){return`Handoff to the ${n.name} agent to handle the request. ${n.handoffDescription??""}`}class Hi{constructor(e,t){S(this,"toolName");S(this,"toolDescription");S(this,"inputJsonSchema",{type:"object",properties:{},required:[],additionalProperties:!1});S(this,"strictJsonSchema",!0);S(this,"onInvokeHandoff");S(this,"agentName");S(this,"inputFilter");S(this,"agent");S(this,"isEnabled",async()=>!0);this.agentName=e.name,this.onInvokeHandoff=t,this.toolName=zc(e),this.toolDescription=Bc(e),this.agent=e}getHandoffAsFunctionTool(){return{type:"function",name:this.toolName,description:this.toolDescription,parameters:this.inputJsonSchema,strict:this.strictJsonSchema}}}function Wi(n,e={}){let t;const s=!!e.onHandoff,r=!!e.inputType;if(!(s===r))throw new re("You must provide either both `onHandoff` and `inputType` or neither.");async function o(u,l){var p;if(t){if(!l)throw nt({message:`Handoff function expected non empty input but got: ${l}`,data:{details:"input is empty"}}),new Se("Handoff function expected non empty input");try{const d=await t(l);e.onHandoff&&await e.onHandoff(u,d)}catch(d){throw nt({message:"Invalid JSON provided",data:{}}),F.dontLogToolData||F.error(`Invalid JSON when parsing: ${l}. Error: ${d}`),new Se("Invalid JSON provided")}}else await((p=e.onHandoff)==null?void 0:p.call(e,u));return n}const a=new Hi(n,o);if(typeof e.isEnabled=="function"){const u=e.isEnabled;a.isEnabled=async({runContext:l,agent:p})=>!!await u({runContext:l,agent:p})}else typeof e.isEnabled=="boolean"&&(a.isEnabled=async()=>e.isEnabled);if(e.inputType){const u=Qs(e.inputType,a.toolName);a.inputJsonSchema=u.schema,a.strictJsonSchema=!0,t=u.parser}return e.toolNameOverride&&(a.toolName=e.toolNameOverride),e.toolDescriptionOverride&&(a.toolDescription=e.toolDescriptionOverride),e.inputFilter&&(a.inputFilter=e.inputFilter),a}function Zc(n){return n instanceof Hi?n:Wi(n)}function Ki(n){if(n.type!=="message"||n.role!=="assistant")return;const e=n.content[n.content.length-1];if(e.type==="output_text")return e.text}function qc(n){return n.output.length===0?"":Ki(n.output[n.output.length-1])||""}const ur=new WeakMap;function Jc(n,e){n&&ur.set(n,e)}function Gc(n){const e=ur.get(n);return e&&ur.delete(n),e}const Vc=w({input:f()}),tn=class tn extends $c{constructor(t){super();S(this,"name");S(this,"instructions");S(this,"prompt");S(this,"handoffDescription");S(this,"handoffs");S(this,"model");S(this,"modelSettings");S(this,"tools");S(this,"mcpServers");S(this,"inputGuardrails");S(this,"outputGuardrails");S(this,"outputType","text");S(this,"toolUseBehavior");S(this,"resetToolChoice");S(this,"_toolsExplicitlyConfigured");if(typeof t.name!="string"||t.name.trim()==="")throw new re("Agent must have a name.");if(this.name=t.name,this.instructions=t.instructions??tn.DEFAULT_MODEL_PLACEHOLDER,this.prompt=t.prompt,this.handoffDescription=t.handoffDescription??"",this.handoffs=t.handoffs??[],this.model=t.model??"",this.modelSettings=t.modelSettings??Lc(),this.tools=t.tools??[],this._toolsExplicitlyConfigured=t.tools!==void 0,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,t.model!==void 0&&Ji()&&(typeof t.model!="string"||!Is(t.model))&&t.modelSettings===void 0&&(this.modelSettings={}),(t.handoffOutputTypeWarningEnabled===void 0||t.handoffOutputTypeWarningEnabled)&&this.handoffs&&this.outputType){const s=new Set([JSON.stringify(this.outputType)]);for(const r of this.handoffs)"outputType"in r&&r.outputType?s.add(JSON.stringify(r.outputType)):"agent"in r&&r.agent.outputType&&s.add(JSON.stringify(r.agent.outputType));s.size>1&&F.warn(`[Agent] Warning: Handoff agents have different output types: ${Array.from(s).join(", ")}. You can make it type-safe by using Agent.create({ ... }) method instead.`)}}static create(t){return new tn({...t,handoffs:t.handoffs,outputType:t.outputType,handoffOutputTypeWarningEnabled:!1})}get outputSchemaName(){if(this.outputType==="text")return"text";if(kt(this.outputType))return"ZodOutput";if(typeof this.outputType=="object")return this.outputType.name;throw new Error(`Unknown output type: ${this.outputType}`)}clone(t){return new tn({...this,...t})}asTool(t){const{toolName:s,toolDescription:r,customOutputExtractor:i,needsApproval:o,runConfig:a,runOptions:u,isEnabled:l,onStream:p}=t,d=new Map,m=async T=>{const y=d.get(T.event.type),h=d.get("*"),v=[...p?[p]:[],...y?Array.from(y):[],...h?Array.from(h):[]];await Promise.allSettled(v.map(b=>Promise.resolve().then(()=>b(T))))},_={...Ht({name:s??ys(this.name),description:r??"",parameters:Vc,strict:!0,needsApproval:o,isEnabled:l,execute:async(T,y,h)=>{if(!Wu(T))throw new Se("Agent tool called with invalid input");const v=new Sd(a??{}),b=typeof p=="function"||d.size>0,N=b?await v.run(this,T.input,{context:y,...u??{},stream:!0}):await v.run(this,T.input,{context:y,...u??{}}),x={agent:this,toolCall:h==null?void 0:h.toolCall};if(b){const G=N;for await(const L of G)await m({event:L,...x});await G.completed}const A=N,D=typeof this.toolUseBehavior=="object"&&this.toolUseBehavior!==null&&"stopAtToolNames"in this.toolUseBehavior;typeof i!="function"&&D&&F.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 U=typeof i=="function"?await i(A):qc(A.rawResponses[A.rawResponses.length-1]);return h!=null&&h.toolCall&&Jc(h.toolCall,A),U}}),on:(T,y)=>{const h=d.get(T)??new Set;return h.add(y),d.set(T,h),_}};return _}async getSystemPrompt(t){return typeof this.instructions=="function"?await this.instructions(t,this):this.instructions}async getPrompt(t){return typeof this.prompt=="function"?await this.prompt(t,this):this.prompt}async getMcpTools(t){return this.mcpServers.length>0?Cc({mcpServers:this.mcpServers,runContext:t,agent:this,convertSchemasToStrict:!1}):[]}async getAllTools(t){const s=await this.getMcpTools(t),r=[];for(const i of this.tools){if(i.type==="function"){const o=i.isEnabled;if(!(typeof o=="function"?await o(t,this):typeof o=="boolean"?o:!0))continue}r.push(i)}return[...s,...r]}hasExplicitToolConfig(){return this._toolsExplicitlyConfigured}async getEnabledHandoffs(t){var i;const s=((i=this.handoffs)==null?void 0:i.map(o=>Zc(o)))??[],r=[];for(const o of s)await o.isEnabled({runContext:t,agent:this})&&r.push(o);return r}processFinalOutput(t){if(this.outputType==="text")return t;if(typeof this.outputType=="object"){const s=JSON.parse(t);return kt(this.outputType)?this.outputType.parse(s):s}throw new Error(`Unknown output type: ${this.outputType}`)}toJSON(){return{name:this.name}}};S(tn,"DEFAULT_MODEL_PLACEHOLDER","");let Qe=tn;function Yi({name:n,execute:e,runInParallel:t=!0}){return{type:"input",name:n,runInParallel:t,guardrailFunction:e,async run(s){return{guardrail:{type:"input",name:n},output:await e(s)}}}}function cr({name:n,execute:e}){return{type:"output",name:n,guardrailFunction:e,async run(t){return{guardrail:{type:"output",name:n},agent:t.agent,agentOutput:t.agentOutput,output:await e(t)}}}}function Hc(){throw new Error("No default model provider set. Make sure to set a provider using setDefaultModelProvider before calling getDefaultModelProvider or pass an explicit provider.")}const me=w({providerData:se(f(),H()).optional()}),Ee=me.extend({id:f().optional()}),Wc=me.extend({type:I("refusal"),refusal:f()}),Kc=me.extend({type:I("output_text"),text:f()}),lr=me.extend({type:I("input_text"),text:f()}),Yc=me.extend({type:I("reasoning_text"),text:f()}),Xi=me.extend({type:I("input_image"),image:f().or(w({id:f().describe("OpenAI file ID")})).describe("Either base64 encoded image data, a data URL, or an object with a file ID.").optional(),detail:f().optional()}),Qi=me.extend({type:I("input_file"),file:f().describe("Either base64 encoded file data or a publicly accessible file URL").or(w({id:f().describe("OpenAI file ID")})).or(w({url:f().describe("Publicly accessible file URL")})).describe("Contents of the file or an object with a file ID.").optional(),filename:f().optional()}),ea=me.extend({type:I("audio"),audio:f().or(w({id:f()})).describe("Base64 encoded audio data or file id"),format:f().nullable().optional(),transcript:f().nullable().optional()}),Xc=me.extend({type:I("image"),image:f().describe("Base64 encoded image data")}),Qc=me.extend({type:I("text"),text:f()}),el=w({data:Ye([f(),li(Uint8Array)]).describe("Base64 image data, or raw bytes that will be base64 encoded automatically."),mediaType:f().optional()}),tl=w({url:f().describe("Publicly accessible URL pointing to the image content")}),nl=w({fileId:f().describe("OpenAI file ID referencing uploaded image content")}),sl=Ye([el,tl,nl]).describe("Inline image data or references to uploaded content."),rl=w({data:Ye([f(),li(Uint8Array)]).describe("Base64 encoded file data, or raw bytes that will be encoded automatically."),mediaType:f().describe("IANA media type describing the file contents"),filename:f().describe("Filename associated with the inline data")}),il=w({url:f().describe("Publicly accessible URL for the file content"),filename:f().optional()}),al=w({id:f().describe("OpenAI file ID referencing uploaded content"),filename:f().optional()}),ol=Ye([f().describe("Existing data URL or base64 string"),rl,il,al]).describe("Inline data (with metadata) or references pointing to file contents."),ul=(...n)=>f(),cl=me.extend({type:I("image"),image:f().or(sl).optional(),detail:ul("low","high","auto").optional()}),ll=me.extend({type:I("file"),file:ol}),dl=me.extend({type:I("computer_screenshot"),data:f().describe("Base64 encoded image data or URL")}),pl=ve("type",[w({type:I("screenshot")}),w({type:I("click"),x:E(),y:E(),button:pe(["left","right","wheel","back","forward"])}),w({type:I("double_click"),x:E(),y:E()}),w({type:I("scroll"),x:E(),y:E(),scroll_x:E(),scroll_y:E()}),w({type:I("type"),text:f()}),w({type:I("wait")}),w({type:I("move"),x:E(),y:E()}),w({type:I("keypress"),keys:J(f())}),w({type:I("drag"),path:J(w({x:E(),y:E()}))})]),fl=ve("type",[Kc,Wc,ea,Xc]),dr=Ee.extend({type:I("message").optional()}),Ss=dr.extend({role:I("assistant"),status:pe(["in_progress","completed","incomplete"]),content:J(fl)}),hl=ve("type",[lr,Xi,Qi,ea]),ta=dr.extend({role:I("user"),content:J(hl).or(f())}),na=dr.extend({role:I("system"),content:f()});ve("role",[na,Ss,ta]);const Sn=Ee.extend({type:I("hosted_tool_call"),name:f().describe("The name of the hosted tool"),arguments:f().describe("The arguments of the hosted tool call").optional(),status:f().optional(),output:f().optional()}),Tn=Ee.extend({type:I("function_call"),callId:f().describe("The ID of the tool call"),name:f().describe("The name of the function"),status:pe(["in_progress","completed","incomplete"]).optional(),arguments:f()}),ml=ve("type",[Qc,cl,ll]),gl=ve("type",[lr,Xi,Qi]),Ts=Ee.extend({type:I("function_call_result"),name:f().describe("The name of the tool"),callId:f().describe("The ID of the tool call"),status:pe(["in_progress","completed","incomplete"]),output:Ye([f(),ml,J(gl)]).describe("Output returned by the tool call. Supports plain strings, legacy ToolOutput items, or structured input_* items.")}),pr=Ee.extend({type:I("computer_call"),callId:f().describe("The ID of the computer call"),status:pe(["in_progress","completed","incomplete"]),action:pl}),yl=Ee.extend({type:I("computer_call_result"),callId:f().describe("The ID of the computer call"),output:dl}),_l=w({commands:J(f()),timeoutMs:E().int().min(0).optional(),maxOutputLength:E().int().min(0).optional()}),xs=Ee.extend({type:I("shell_call"),callId:f(),status:pe(["in_progress","completed","incomplete"]).optional(),action:_l}),vl=ve("type",[w({type:I("timeout")}),w({type:I("exit"),exitCode:E().int().nullable()})]),bl=w({stdout:f(),stderr:f(),outcome:vl}).passthrough(),sa=Ee.extend({type:I("shell_call_output"),callId:f(),maxOutputLength:E().optional(),output:J(bl)}),wl=w({type:I("create_file"),path:f(),diff:f()}),Il=w({type:I("update_file"),path:f(),diff:f()}),Sl=w({type:I("delete_file"),path:f()}),Tl=ve("type",[wl,Il,Sl]),ks=Ee.extend({type:I("apply_patch_call"),callId:f(),status:pe(["in_progress","completed"]),operation:Tl}),ra=Ee.extend({type:I("apply_patch_call_output"),callId:f(),status:pe(["completed","failed"]),output:f().optional()}),xl=ve("type",[pr,xs,ks,Tn,Sn]),fr=me.extend({id:f().optional(),type:I("reasoning"),content:J(lr),rawContent:J(Yc).optional()}),ia=Ee.extend({type:I("compaction"),encrypted_content:f(),id:f().optional(),created_by:f().optional()}),aa=Ee.extend({type:I("unknown")}),hr=ve("type",[Ss,Sn,Tn,pr,xs,ks,Ts,sa,ra,fr,ia,aa]),kl=Ye([ta,Ss,na,Sn,Tn,pr,xs,ks,Ts,yl,sa,ra,fr,ia,aa]),Al=w({inputTokens:E(),outputTokens:E(),totalTokens:E(),inputTokensDetails:se(f(),E()).optional(),outputTokensDetails:se(f(),E()).optional(),endpoint:f().optional()}),Cl=w({requests:E().optional(),inputTokens:E(),outputTokens:E(),totalTokens:E(),inputTokensDetails:Ye([se(f(),E()),J(se(f(),E()))]).optional(),outputTokensDetails:Ye([se(f(),E()),J(se(f(),E()))]).optional(),requestUsageEntries:J(Al).optional()}),oa=me.extend({type:I("output_text_delta"),delta:f()}),Ol=me.extend({type:I("response_started")}),ua=me.extend({type:I("response_done"),response:me.extend({id:f(),usage:Cl,output:J(hr)})}),El=me.extend({type:I("model"),event:H().describe("The event from the model")});ve("type",[oa,ua,Ol,El]);class xn{constructor(e){S(this,"inputTokens");S(this,"outputTokens");S(this,"totalTokens");S(this,"inputTokensDetails");S(this,"outputTokensDetails");S(this,"endpoint");this.inputTokens=(e==null?void 0:e.inputTokens)??(e==null?void 0:e.input_tokens)??0,this.outputTokens=(e==null?void 0:e.outputTokens)??(e==null?void 0:e.output_tokens)??0,this.totalTokens=(e==null?void 0:e.totalTokens)??(e==null?void 0:e.total_tokens)??this.inputTokens+this.outputTokens;const t=(e==null?void 0:e.inputTokensDetails)??(e==null?void 0:e.input_tokens_details);this.inputTokensDetails=t||{};const s=(e==null?void 0:e.outputTokensDetails)??(e==null?void 0:e.output_tokens_details);this.outputTokensDetails=s||{},typeof(e==null?void 0:e.endpoint)<"u"&&(this.endpoint=e.endpoint)}}class kn{constructor(e){S(this,"requests");S(this,"inputTokens");S(this,"outputTokens");S(this,"totalTokens");S(this,"inputTokensDetails",[]);S(this,"outputTokensDetails",[]);S(this,"requestUsageEntries");if(typeof e>"u")this.requests=0,this.inputTokens=0,this.outputTokens=0,this.totalTokens=0,this.inputTokensDetails=[],this.outputTokensDetails=[],this.requestUsageEntries=void 0;else{this.requests=(e==null?void 0:e.requests)??1,this.inputTokens=(e==null?void 0:e.inputTokens)??(e==null?void 0:e.input_tokens)??0,this.outputTokens=(e==null?void 0:e.outputTokens)??(e==null?void 0:e.output_tokens)??0,this.totalTokens=(e==null?void 0:e.totalTokens)??(e==null?void 0:e.total_tokens)??this.inputTokens+this.outputTokens;const t=(e==null?void 0:e.inputTokensDetails)??(e==null?void 0:e.input_tokens_details);Array.isArray(t)?this.inputTokensDetails=t:this.inputTokensDetails=t?[t]:[];const s=(e==null?void 0:e.outputTokensDetails)??(e==null?void 0:e.output_tokens_details);Array.isArray(s)?this.outputTokensDetails=s:this.outputTokensDetails=s?[s]:[];const r=(e==null?void 0:e.requestUsageEntries)??(e==null?void 0:e.request_usage_entries),i=Array.isArray(r)?r.map(o=>o instanceof xn?o:new xn(o)):void 0;this.requestUsageEntries=i&&i.length>0?i:void 0}}add(e){var t,s;this.requests+=e.requests??0,this.inputTokens+=e.inputTokens??0,this.outputTokens+=e.outputTokens??0,this.totalTokens+=e.totalTokens??0,e.inputTokensDetails&&this.inputTokensDetails.push(...e.inputTokensDetails),e.outputTokensDetails&&this.outputTokensDetails.push(...e.outputTokensDetails),Array.isArray(e.requestUsageEntries)&&e.requestUsageEntries.length>0?(this.requestUsageEntries??(this.requestUsageEntries=[]),this.requestUsageEntries.push(...e.requestUsageEntries.map(r=>r instanceof xn?r:new xn(r)))):e.requests===1&&e.totalTokens>0&&(this.requestUsageEntries??(this.requestUsageEntries=[]),this.requestUsageEntries.push(new xn({inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,inputTokensDetails:(t=e.inputTokensDetails)==null?void 0:t[0],outputTokensDetails:(s=e.outputTokensDetails)==null?void 0:s[0]})))}}class Wt{constructor(e={}){S(this,"context");S(this,"usage");R(this,ke);this.context=e,this.usage=new kn,k(this,ke,new Map)}_rebuildApprovals(e){k(this,ke,new Map(Object.entries(e)))}isToolApproved(e){const{toolName:t,callId:s}=e,r=c(this,ke).get(t);if((r==null?void 0:r.approved)===!0&&r.rejected===!0)return F.warn("Tool is permanently approved and rejected at the same time. Approval takes precedence"),!0;if((r==null?void 0:r.approved)===!0)return!0;if((r==null?void 0:r.rejected)===!0)return!1;const i=Array.isArray(r==null?void 0:r.approved)?r.approved.includes(s):!1,o=Array.isArray(r==null?void 0:r.rejected)?r.rejected.includes(s):!1;if(i&&o)return F.warn(`Tool call ${s} is both approved and rejected at the same time. Approval takes precedence`),!0;if(i)return!0;if(o)return!1}approveTool(e,{alwaysApprove:t=!1}={}){const s=e.toolName??e.rawItem.name;if(t){c(this,ke).set(s,{approved:!0,rejected:[]});return}const r=c(this,ke).get(s)??{approved:[],rejected:[]};if(Array.isArray(r.approved)){const i="callId"in e.rawItem?e.rawItem.callId:e.rawItem.id;r.approved.push(i)}c(this,ke).set(s,r)}rejectTool(e,{alwaysReject:t=!1}={}){const s=e.toolName??e.rawItem.name;if(t){c(this,ke).set(s,{approved:!1,rejected:!0});return}const r=c(this,ke).get(s)??{approved:[],rejected:[]};if(Array.isArray(r.rejected)){const i="callId"in e.rawItem?e.rawItem.callId:e.rawItem.id;r.rejected.push(i)}c(this,ke).set(s,r)}toJSON(){return{context:this.context,usage:this.usage,approvals:Object.fromEntries(c(this,ke).entries())}}}ke=new WeakMap;function Rl(n){return!!n&&typeof n=="object"&&"environment"in n&&"dimensions"in n}function Nl(n){if(n.type==="function")return{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict};if(n.type==="computer"){if(!Rl(n.computer))throw new re("Computer tool is not initialized for serialization. Call resolveComputer({ tool, runContext }) first (for example, when building a model payload outside Runner.run).");return{type:"computer",name:n.name,environment:n.computer.environment,dimensions:n.computer.dimensions}}return n.type==="shell"?{type:"shell",name:n.name}:n.type==="apply_patch"?{type:"apply_patch",name:n.name}:{type:"hosted_tool",name:n.name,providerData:n.providerData}}function Pl(n){return{toolName:n.toolName,toolDescription:n.toolDescription,inputJsonSchema:n.inputJsonSchema,strictJsonSchema:n.strictJsonSchema}}class At{constructor(){S(this,"type","base_item");S(this,"rawItem")}toJSON(){return{type:this.type,rawItem:this.rawItem}}}class As extends At{constructor(t,s){super();S(this,"rawItem");S(this,"agent");S(this,"type","message_output_item");this.rawItem=t,this.agent=s}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}get content(){let t="";for(const s of this.rawItem.content)s.type==="output_text"&&(t+=s.text);return t}}class et extends At{constructor(t,s){super();S(this,"rawItem");S(this,"agent");S(this,"type","tool_call_item");this.rawItem=t,this.agent=s}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class Le extends At{constructor(t,s,r){super();S(this,"rawItem");S(this,"agent");S(this,"output");S(this,"type","tool_call_output_item");this.rawItem=t,this.agent=s,this.output=r}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON(),output:lt(this.output)}}}class mr extends At{constructor(t,s){super();S(this,"rawItem");S(this,"agent");S(this,"type","reasoning_item");this.rawItem=t,this.agent=s}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class gr extends At{constructor(t,s){super();S(this,"rawItem");S(this,"agent");S(this,"type","handoff_call_item");this.rawItem=t,this.agent=s}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class yr extends At{constructor(t,s,r){super();S(this,"rawItem");S(this,"sourceAgent");S(this,"targetAgent");S(this,"type","handoff_output_item");this.rawItem=t,this.sourceAgent=s,this.targetAgent=r}toJSON(){return{...super.toJSON(),sourceAgent:this.sourceAgent.toJSON(),targetAgent:this.targetAgent.toJSON()}}}class Ie extends At{constructor(t,s,r){super();S(this,"rawItem");S(this,"agent");S(this,"toolName");S(this,"type","tool_approval_item");this.rawItem=t,this.agent=s,this.toolName=r,this.toolName=r??t.name}get name(){return this.toolName??this.rawItem.name}get arguments(){return"arguments"in this.rawItem?this.rawItem.arguments:void 0}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON(),toolName:this.toolName}}}function Cs(n){return async(e,...t)=>xr(async()=>{const s=n(...t);Tr(s);try{return s.start(),await e(s)}catch(r){throw s.setError({message:r.message,data:r.data}),r}finally{s.end(),Cn()}})}function Dl(n,e){var t;return qe().createSpan({...n,data:{type:"agent",name:((t=n==null?void 0:n.data)==null?void 0:t.name)??"Agent",...n==null?void 0:n.data}},e)}function Ml(n,e){var t,s;return qe().createSpan({...n,data:{type:"function",input:((t=n==null?void 0:n.data)==null?void 0:t.input)??"",output:((s=n==null?void 0:n.data)==null?void 0:s.output)??"",...n==null?void 0:n.data}},e)}const ca=Cs(Ml);function Fl(n,e){return qe().createSpan({...n,data:{type:"handoff",...n==null?void 0:n.data}},e)}const $l=Cs(Fl);function jl(n,e){return qe().createSpan({...n,data:{type:"guardrail",triggered:!1,...n==null?void 0:n.data}},e)}const la=Cs(jl);function Ul(n,e){return qe().createSpan({...n,data:{type:"mcp_tools",...n==null?void 0:n.data}},e)}const Ll=Cs(Ul);function Re(n){if(n.length===0)return"";const e=typeof globalThis<"u"&&globalThis.Buffer?globalThis.Buffer:void 0;if(e)return e.from(n).toString("base64");let t="";for(let o=0;o<n.length;o+=1)t+=String.fromCharCode(n[o]);if(typeof globalThis.btoa=="function")return globalThis.btoa(t);const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let r="",i=0;for(;i<t.length;){const o=t.charCodeAt(i++),a=t.charCodeAt(i++),u=t.charCodeAt(i++),l=o>>2,p=(o&3)<<4|a>>4,d=isNaN(a)?64:(a&15)<<2|u>>6,m=isNaN(u)?64:u&63;r+=s.charAt(l)+s.charAt(p)+s.charAt(d)+s.charAt(m)}return r}class zl{constructor(e){S(this,"data");S(this,"type","raw_model_stream_event");this.data=e}}class Bl{constructor(e,t){S(this,"name");S(this,"item");S(this,"type","run_item_stream_event");this.name=e,this.item=t}}class Zl{constructor(e){S(this,"agent");S(this,"type","agent_updated_stream_event");this.agent=e}}function ql(n){return!!n&&typeof n.runCompaction=="function"}function Jl(n){if(!n||typeof n!="object"||!("rawItem"in n))return!1;const e=n.rawItem;if(!e||typeof e!="object")return!1;const t=e.type;return t==="function_call"||t==="hosted_tool_call"}function da(n){const e=n.rawItem;if(!e)return;if(e.type==="function_call"&&e.callId)return`function_call:${e.callId}`;if("callId"in e&&e.callId)return`${e.type}:${e.callId}`;const t="id"in e?e.id:void 0;if(t)return`${e.type}:${t}`;const s=typeof e.providerData=="object"&&e.providerData?e.providerData:void 0;if(s!=null&&s.id)return`${e.type}:provider:${s.id}`;const r="agent"in n&&n.agent?n.agent.name:"";try{return`${r}:${e.type}:${JSON.stringify(e)}`}catch{return`${r}:${e.type}`}}function Gl(n){try{if(n instanceof Fe){const e=n.issues[0];if(e){const t=Array.isArray(e.path)?e.path:[],s=t.length>0?t.map(i=>String(i)).join("."):"(root)",r=pa(e.message??"");return`Invalid output type: final assistant output failed schema validation at "${s}" (${r}).`}return"Invalid output type: final assistant output failed schema validation."}if(n instanceof Error&&n.message)return`Invalid output type: ${pa(n.message)}`}catch{}return"Invalid output type: final assistant output did not match the expected schema."}function pa(n,e=160){const t=n.trim();return t?t.length<=e?t:`${t.slice(0,e-3)}...`:"Schema validation failed."}function fa(n,e,t,s){var v;const r=[],i=[],o=[],a=[],u=[],l=[],p=[],d=[],m=new Map(s.map(b=>[b.toolName,b])),g=new Map(t.filter(b=>b.type==="function").map(b=>[b.name,b])),_=t.find(b=>b.type==="computer"),T=t.find(b=>b.type==="shell"),y=t.find(b=>b.type==="apply_patch"),h=new Map(t.filter(b=>{var N;return b.type==="hosted_tool"&&((N=b.providerData)==null?void 0:N.type)==="mcp"}).map(b=>b).map(b=>[b.providerData.server_label,b]));for(const b of n.output){if(b.type==="message")b.role==="assistant"&&r.push(new As(b,e));else if(b.type==="hosted_tool_call"){r.push(new et(b,e));const x=b.name;if(d.push(x),((v=b.providerData)==null?void 0:v.type)==="mcp_approval_request"||b.name==="mcp_approval_request"){const A=b.providerData,D=A.server_label,U=h.get(D);if(typeof U>"u"){const L=`MCP server (${D}) not found in Agent (${e.name})`;throw nt({message:L,data:{mcp_server_label:D}}),new Se(L)}const G=new Ie({type:"hosted_tool_call",name:A.name,id:A.id,status:"in_progress",providerData:A},e);p.push({requestItem:G,mcpTool:U}),U.providerData.on_approval||r.push(G)}}else if(b.type==="reasoning")r.push(new mr(b,e));else if(b.type==="computer_call"){if(r.push(new et(b,e)),d.push("computer_use"),!_)throw nt({message:"Model produced computer action without a computer tool.",data:{agent_name:e.name}}),new Se("Model produced computer action without a computer tool.");a.push({toolCall:b,computer:_})}else if(b.type==="shell_call"){if(r.push(new et(b,e)),d.push("shell"),!T)throw nt({message:"Model produced shell action without a shell tool.",data:{agent_name:e.name}}),new Se("Model produced shell action without a shell tool.");u.push({toolCall:b,shell:T})}else if(b.type==="apply_patch_call"){if(r.push(new et(b,e)),d.push("apply_patch"),!y)throw nt({message:"Model produced apply_patch action without an apply_patch tool.",data:{agent_name:e.name}}),new Se("Model produced apply_patch action without an apply_patch tool.");l.push({toolCall:b,applyPatch:y})}if(b.type!=="function_call")continue;d.push(b.name);const N=m.get(b.name);if(N)r.push(new gr(b,e)),i.push({toolCall:b,handoff:N});else{const x=g.get(b.name);if(!x)throw nt({message:`Tool ${b.name} not found in agent ${e.name}.`,data:{tool_name:b.name,agent_name:e.name}}),new Se(`Tool ${b.name} not found in agent ${e.name}.`);r.push(new et(b,e)),o.push({toolCall:b,tool:x})}}return{newItems:r,handoffs:i,functions:o,computerActions:a,shellActions:u,applyPatchActions:l,mcpApprovalRequests:p,toolsUsed:d,hasToolsOrApprovalsToRun(){return i.length>0||o.length>0||p.length>0||a.length>0||u.length>0||l.length>0}}}const Vl=ve("type",[w({type:I("next_step_handoff"),newAgent:H()}),w({type:I("next_step_final_output"),output:f()}),w({type:I("next_step_run_again")}),w({type:I("next_step_interruption"),data:se(f(),H())})]);class ze{constructor(e,t,s,r,i){S(this,"originalInput");S(this,"modelResponse");S(this,"preStepItems");S(this,"newStepItems");S(this,"nextStep");this.originalInput=e,this.modelResponse=t,this.preStepItems=s,this.newStepItems=r,this.nextStep=i}get generatedItems(){return this.preStepItems.concat(this.newStepItems)}}function Hl(n,e,t){return n.resetToolChoice&&e.hasUsedTools(n)?{...t,toolChoice:void 0}:t}async function ha(n,e,t,s,r,i,o){const a=t.filter(x=>x instanceof Ie&&"callId"in x.rawItem&&x.rawItem.type==="function_call").map(x=>x.rawItem.callId),u=o.getInterruptions().filter(Jl);if(u.length>0){const x=new Set;for(const A of u){const D=da(A);D&&x.add(D)}if(x.size>0){let A=0;for(let D=t.length-1;D>=0;D--){const U=t[D];if(!(U instanceof Ie))continue;const G=da(U);if(G&&x.has(G)&&(A++,x.delete(G),x.size===0))break}A>0&&(o._currentTurnPersistedItemCount=Math.max(0,o._currentTurnPersistedItemCount-A))}}const l=r.functions.filter(x=>a.includes(x.toolCall.callId)),p=await ya(n,l,i,o),d=r.computerActions.length>0?await va(n,r.computerActions,i,o._context):[],m=new Set(t),g=[],_=new Set,T=x=>{m.has(x)||_.has(x)||(g.push(x),_.add(x))};for(const x of p)T(x.runItem);for(const x of d)T(x);const y=r.mcpApprovalRequests.filter(x=>{var A;return x.requestItem.type==="tool_approval_item"&&x.requestItem.rawItem.type==="hosted_tool_call"&&((A=x.requestItem.rawItem.providerData)==null?void 0:A.type)==="mcp_approval_request"}),h=new Set,v=new Set;for(const x of y){const A=x.requestItem.rawItem;if(A.type!=="hosted_tool_call")continue;const D=A.id,U=o._context.isToolApproved({toolName:A.name,callId:D});if(typeof U<"u"){const G={approve:U,approval_request_id:D,reason:void 0},L=new et({type:"hosted_tool_call",name:"mcp_approval_response",providerData:G},n);T(L)}else h.add(x.requestItem),v.add(D),p.push({type:"hosted_mcp_tool_approval",tool:x.mcpTool,runItem:x.requestItem}),T(x.requestItem)}const b=t.filter(x=>{var A;if(!(x instanceof Ie))return!0;if(x.rawItem.type==="hosted_tool_call"&&((A=x.rawItem.providerData)==null?void 0:A.type)==="mcp_approval_request"){if(h.has(x))return!0;const D=x.rawItem.id;return D?v.has(D):!1}return!1}),N=await ga({agent:n,runner:i,state:o,functionResults:p,originalInput:e,newResponse:s,preStepItems:b,newItems:g});return N||new ze(e,s,b,g,{type:"next_step_run_again"})}async function ma(n,e,t,s,r,i,o){var N,x,A,D,U,G;const a=t,u=new Set(t),l=[],p=L=>{u.has(L)||(l.push(L),u.add(L))};for(const L of r.newItems)p(L);const[d,m,g,_]=await Promise.all([ya(n,r.functions,i,o),va(n,r.computerActions,i,o._context),Ql(n,r.shellActions,i,o._context),ed(n,r.applyPatchActions,i,o._context)]);for(const L of d)p(L.runItem);for(const L of m)p(L);for(const L of g)p(L);for(const L of _)p(L);if(r.mcpApprovalRequests.length>0)for(const L of r.mcpApprovalRequests){const fe=L.mcpTool.providerData,Y=L.requestItem.rawItem.providerData;if(fe.on_approval){const ce=await fe.on_approval(o._context,L.requestItem),Me={approve:ce.approve,approval_request_id:Y.id,reason:ce.reason};l.push(new et({type:"hosted_tool_call",name:"mcp_approval_response",providerData:Me},n))}else{l.push(L.requestItem);const ce={type:"hosted_mcp_tool_approval",tool:L.mcpTool,runItem:new Ie({type:"hosted_tool_call",name:Y.name,id:Y.id,arguments:Y.arguments,status:"in_progress",providerData:Y},n)};d.push(ce)}}if(r.handoffs.length>0)return await td(n,e,a,l,s,r.handoffs,i,o._context);const T=await ga({agent:n,runner:i,state:o,functionResults:d,originalInput:e,newResponse:s,preStepItems:a,newItems:l});if(T)return T;if((((N=r.functions)==null?void 0:N.length)??0)>0||(((x=r.computerActions)==null?void 0:x.length)??0)>0||(((A=r.shellActions)==null?void 0:A.length)??0)>0||(((D=r.applyPatchActions)==null?void 0:D.length)??0)>0||(((U=r.mcpApprovalRequests)==null?void 0:U.length)??0)>0||(((G=r.handoffs)==null?void 0:G.length)??0)>0)return new ze(e,s,a,l,{type:"next_step_run_again"});const h=l.filter(L=>L instanceof As),v=h.length>0?Ki(h[h.length-1].rawItem):void 0;if(typeof v>"u")return new ze(e,s,a,l,{type:"next_step_run_again"});if(!d.some(L=>L.runItem instanceof Ie)){if(n.outputType==="text")return new ze(e,s,a,l,{type:"next_step_final_output",output:v});if(n.outputType!=="text"&&v){const{parser:L}=Qs(n.outputType,"final_output"),[fe]=await le(()=>L(v));if(fe){const Y=Gl(fe);throw nt({message:Y,data:{error:String(fe)}}),new Se(Y)}return new ze(e,s,a,l,{type:"next_step_final_output",output:v})}}return new ze(e,s,a,l,{type:"next_step_run_again"})}async function ga({agent:n,runner:e,state:t,functionResults:s,originalInput:r,newResponse:i,preStepItems:o,newItems:a}){const u=await nd(n,s,t);return u.isFinalOutput?(e.emit("agent_end",t._context,n,u.finalOutput),n.emit("agent_end",t._context,u.finalOutput),new ze(r,i,o,a,{type:"next_step_final_output",output:u.finalOutput})):u.isInterrupted?new ze(r,i,o,a,{type:"next_step_interruption",data:{interruptions:u.interruptions}}):null}function Os(n,e){const t=pd(e);if(t){const s=t.map(fd);return{type:"function_call_result",name:n.name,callId:n.callId,status:"completed",output:s}}return{type:"function_call_result",name:n.name,callId:n.callId,status:"completed",output:{type:"text",text:lt(e)}}}function Wl(n){const e=n.file;if(typeof e=="string"&&e.length>0)return e;const t=Kl(e);if(t)return t;const s=Yl(n);return s||null}function Kl(n){if(!Ct(n))return null;if("data"in n&&n.data!==void 0){const t=n.data,s=typeof t=="string"&&t.length>0,r=t instanceof Uint8Array&&t.length>0;return!s&&!r||!ge(n.mediaType)||!ge(n.filename)?null:{data:typeof t=="string"?t:new Uint8Array(t),mediaType:n.mediaType,filename:n.filename}}if(ge(n.url)){const t={url:n.url};return ge(n.filename)&&(t.filename=n.filename),t}const e=ge(n.id)&&n.id||ge(n.fileId)&&n.fileId;if(e){const t={id:e};return ge(n.filename)&&(t.filename=n.filename),t}return null}function Yl(n){const e=typeof n.filename=="string"&&n.filename.length>0?n.filename:void 0,t=typeof n.mediaType=="string"&&n.mediaType.length>0?n.mediaType:void 0;if(typeof n.fileData=="string"&&n.fileData.length>0)return!t||!e?null:{data:n.fileData,mediaType:t,filename:e};if(n.fileData instanceof Uint8Array&&n.fileData.length>0)return!t||!e?null:{data:new Uint8Array(n.fileData),mediaType:t,filename:e};if(typeof n.fileUrl=="string"&&n.fileUrl.length>0){const s={url:n.fileUrl};return e&&(s.filename=e),s}if(typeof n.fileId=="string"&&n.fileId.length>0){const s={id:n.fileId};return e&&(s.filename=e),s}return null}function Ct(n){return typeof n=="object"&&n!==null}function ge(n){return typeof n=="string"&&n.length>0}function Es(n,e){if(typeof n=="string")return e&&!n.startsWith("data:")?Kt(n,e):n;const t=Re(n);return Kt(t,e)}function Kt(n,e){return e?`data:${e};base64,${n}`:n}async function ya(n,e,t,s){async function r(i){let o=i.toolCall.arguments;if(i.tool.parameters&&(kt(i.tool.parameters)?o=i.tool.parameters.parse(o):o=JSON.parse(o)),await i.tool.needsApproval(s._context,o,i.toolCall.callId)){const u=s._context.isToolApproved({toolName:i.tool.name,callId:i.toolCall.callId});if(u===!1)return ca(async l=>{const p="Tool execution was not approved.";return l.setError({message:p,data:{tool_name:i.tool.name,error:`Tool execution for ${i.toolCall.callId} was manually rejected by user.`}}),l.spanData.output=p,{type:"function_output",tool:i.tool,output:p,runItem:new Le(Os(i.toolCall,p),n,p)}},{data:{name:i.tool.name}});if(u!==!0)return{type:"function_approval",tool:i.tool,runItem:new Ie(i.toolCall,n)}}return ca(async u=>{t.config.traceIncludeSensitiveData&&(u.spanData.input=i.toolCall.arguments);try{t.emit("agent_tool_start",s._context,n,i.tool,{toolCall:i.toolCall}),n.emit("agent_tool_start",s._context,i.tool,{toolCall:i.toolCall});const l=await i.tool.invoke(s._context,i.toolCall.arguments,{toolCall:i.toolCall}),p=lt(l);t.emit("agent_tool_end",s._context,n,i.tool,p,{toolCall:i.toolCall}),n.emit("agent_tool_end",s._context,i.tool,p,{toolCall:i.toolCall}),t.config.traceIncludeSensitiveData&&(u.spanData.output=p);const d={type:"function_output",tool:i.tool,output:l,runItem:new Le(Os(i.toolCall,l),n,l)},m=Gc(i.toolCall);if(m){d.agentRunResult=m;const g=m.interruptions;g.length>0&&(d.interruptions=g)}return d}catch(l){u.setError({message:"Error running tool",data:{tool_name:i.tool.name,error:String(l)}});const p=String(l);throw t.emit("agent_tool_end",s._context,n,i.tool,p,{toolCall:i.toolCall}),n.emit("agent_tool_end",s._context,i.tool,p,{toolCall:i.toolCall}),l}},{data:{name:i.tool.name}})}try{return await Promise.all(e.map(r))}catch(i){throw new Hu(`Failed to run function tools: ${i}`,i,s)}}async function Xl(n,e){const t=e.action;let s;switch(t.type){case"click":await n.click(t.x,t.y,t.button);break;case"double_click":await n.doubleClick(t.x,t.y);break;case"drag":await n.drag(t.path.map(r=>[r.x,r.y]));break;case"keypress":await n.keypress(t.keys);break;case"move":await n.move(t.x,t.y);break;case"screenshot":s=await n.screenshot();break;case"scroll":await n.scroll(t.x,t.y,t.scroll_x,t.scroll_y);break;case"type":await n.type(t.text);break;case"wait":await n.wait();break}if(typeof s<"u"||typeof n.screenshot=="function"&&(s=await n.screenshot(),typeof s<"u"))return s;throw new Error("Computer does not implement screenshot()")}function _a(n){if(n instanceof Error)return n.message||n.toString();try{return JSON.stringify(n)}catch{return String(n)}}async function Ql(n,e,t,s,r=void 0){const i=r??F,o=[];for(const a of e){const u=a.shell,l=a.toolCall,p=new Ie(l,n,u.name);if(await u.needsApproval(s,l.action,l.callId)){if(u.onApproval){const h=await u.onApproval(s,p);h.approve===!0?s.approveTool(p):h.approve===!1&&s.rejectTool(p)}const y=s.isToolApproved({toolName:u.name,callId:l.callId});if(y===!1){const h="Tool execution was not approved.",v={stdout:"",stderr:h,outcome:{type:"exit",exitCode:null}};o.push(new Le({type:"shell_call_output",callId:l.callId,output:[v]},n,h));continue}if(y!==!0){o.push(p);continue}}t.emit("agent_tool_start",s,n,u,{toolCall:l}),typeof n.emit=="function"&&n.emit("agent_tool_start",s,u,{toolCall:l});let m;const g={};let _;try{const y=await u.shell.run(l.action);m=y.output??[],y.providerData&&Object.assign(g,y.providerData),typeof y.maxOutputLength=="number"&&(_=y.maxOutputLength)}catch(y){m=[{stdout:"",stderr:_a(y),outcome:{type:"exit",exitCode:null}}],i.error("Failed to execute shell action:",y)}m=m??[],t.emit("agent_tool_end",s,n,u,JSON.stringify(m),{toolCall:l}),typeof n.emit=="function"&&n.emit("agent_tool_end",s,u,JSON.stringify(m),{toolCall:l});const T={type:"shell_call_output",callId:l.callId,output:m??[]};typeof _=="number"&&(T.maxOutputLength=_),Object.keys(g).length>0&&(T.providerData=g),o.push(new Le(T,n,T.output))}return o}async function ed(n,e,t,s,r=void 0){const i=r??F,o=[];for(const a of e){const u=a.applyPatch,l=a.toolCall,p=new Ie(l,n,u.name);if(await u.needsApproval(s,l.operation,l.callId)){if(u.onApproval){const y=await u.onApproval(s,p);y.approve===!0?s.approveTool(p):y.approve===!1&&s.rejectTool(p)}const T=s.isToolApproved({toolName:u.name,callId:l.callId});if(T===!1){const y="Tool execution was not approved.";o.push(new Le({type:"apply_patch_call_output",callId:l.callId,status:"failed",output:y},n,y));continue}if(T!==!0){o.push(p);continue}}t.emit("agent_tool_start",s,n,u,{toolCall:l}),typeof n.emit=="function"&&n.emit("agent_tool_start",s,u,{toolCall:l});let m="completed",g="";try{let T;switch(l.operation.type){case"create_file":T=await u.editor.createFile(l.operation);break;case"update_file":T=await u.editor.updateFile(l.operation);break;case"delete_file":T=await u.editor.deleteFile(l.operation);break;default:throw new Error("Unsupported apply_patch operation")}T&&typeof T.status=="string"&&(m=T.status),T&&typeof T.output=="string"&&(g=T.output)}catch(T){m="failed",g=_a(T),i.error("Failed to execute apply_patch operation:",T)}t.emit("agent_tool_end",s,n,u,g,{toolCall:l}),typeof n.emit=="function"&&n.emit("agent_tool_end",s,u,g,{toolCall:l});const _={type:"apply_patch_call_output",callId:l.callId,status:m};g&&(_.output=g),o.push(new Le(_,n,g))}return o}async function va(n,e,t,s,r=void 0){const i=r??F,o=[];for(const a of e){const u=a.toolCall;t.emit("agent_tool_start",s,n,a.computer,{toolCall:u}),typeof n.emit=="function"&&n.emit("agent_tool_start",s,a.computer,{toolCall:u});let l;try{const m=await zi({tool:a.computer,runContext:s});l=await Xl(m,u)}catch(m){i.error("Failed to execute computer action:",m),l=""}t.emit("agent_tool_end",s,n,a.computer,l,{toolCall:u}),typeof n.emit=="function"&&n.emit("agent_tool_end",s,a.computer,l,{toolCall:u});const p=l?`data:image/png;base64,${l}`:"",d={type:"computer_call_result",callId:u.callId,output:{type:"computer_screenshot",data:p}};o.push(new Le(d,n,p))}return o}async function td(n,e,t,s,r,i,o,a){if(s=[...s],i.length===0)return F.warn("Incorrectly called executeHandoffCalls with no handoffs. This should not happen. Moving on."),new ze(e,r,t,s,{type:"next_step_run_again"});if(i.length>1){const l="Multiple handoffs detected, ignoring this one.";for(let p=1;p<i.length;p++)s.push(new Le(Os(i[p].toolCall,l),n,l))}const u=i[0];return $l(async l=>{const p=u.handoff,d=await p.onInvokeHandoff(a,u.toolCall.arguments);if(l.spanData.to_agent=d.name,i.length>1){const g=i.map(_=>_.handoff.agentName);l.setError({message:"Multiple handoffs requested",data:{requested_agents:g}})}s.push(new yr(Os(u.toolCall,Vi(d)),n,d)),o.emit("agent_handoff",a,n,d),n.emit("agent_handoff",a,d);const m=p.inputFilter??o.config.handoffInputFilter;if(m){F.debug("Filtering inputs for handoff"),typeof m!="function"&&l.setError({message:"Invalid input filter",data:{details:"not callable"}});const g={inputHistory:Array.isArray(e)?[...e]:e,preHandoffItems:[...t],newItems:[...s],runContext:a},_=m(g);e=_.inputHistory,t=_.preHandoffItems,s=_.newItems}return new ze(e,r,t,s,{type:"next_step_handoff",newAgent:d})},{data:{from_agent:n.name}})}const Rs={isFinalOutput:!1,isInterrupted:void 0};async function nd(n,e,t){if(e.length===0)return Rs;const s=[];for(const o of e)if(o.runItem instanceof Ie&&s.push(o.runItem),o.type==="function_output"){if(Array.isArray(o.interruptions))s.push(...o.interruptions);else if(o.agentRunResult){const a=o.agentRunResult.interruptions;a.length>0&&s.push(...a)}}if(s.length>0)return{isFinalOutput:!1,isInterrupted:!0,interruptions:s};if(n.toolUseBehavior==="run_llm_again")return Rs;const r=e[0];if(n.toolUseBehavior==="stop_on_first_tool")return(r==null?void 0:r.type)==="function_output"?{isFinalOutput:!0,isInterrupted:void 0,finalOutput:lt(r.output)}:Rs;const i=n.toolUseBehavior;if(typeof i=="object"){const o=e.find(a=>i.stopAtToolNames.includes(a.tool.name));return(o==null?void 0:o.type)==="function_output"?{isFinalOutput:!0,isInterrupted:void 0,finalOutput:lt(o.output)}:Rs}if(typeof i=="function")return i(t._context,e);throw new re(`Invalid toolUseBehavior: ${i}`,t)}function sd(n){if(n instanceof As)return"message_output_created";if(n instanceof gr)return"handoff_requested";if(n instanceof yr)return"handoff_occurred";if(n instanceof et)return"tool_called";if(n instanceof Le)return"tool_output";if(n instanceof mr)return"reasoning_item_created";if(n instanceof Ie)return"tool_approval_requested"}function ba(n,e){const t=sd(e);if(!t){F.warn("Unknown item type: ",e);return}n._addItem(new Bl(t,e))}function rd(n,e){for(const t of e)ba(n,t)}function wa(n,e,t){const s=t==null?void 0:t.skipItems;for(const r of e.newStepItems)s!=null&&s.has(r)||ba(n,r)}class Ia{constructor(){R(this,nn,new Map)}addToolUse(e,t){c(this,nn).set(e,t)}hasUsedTools(e){return c(this,nn).has(e)}toJSON(){return Object.fromEntries(Array.from(c(this,nn).entries()).map(([e,t])=>[e.name,t]))}}nn=new WeakMap;function id(n){return typeof n=="string"?[{type:"message",role:"user",content:n}]:[...n]}function Sa(n){return n.filter(e=>e.type!=="tool_approval_item").map(e=>e.rawItem)}function _r(n){return n.map(e=>vr(br(e)))}function vr(n,e={}){if(n==null)return n;const t=ad(n);if(t)return od(t,e.mediaType);if(Array.isArray(n))return n.map(o=>vr(o,e));if(!Ta(n))return n;const s=n,r={},i=typeof s.mediaType=="string"&&s.mediaType.length>0?s.mediaType:e.mediaType;for(const[o,a]of Object.entries(s)){const u=o==="data"||o==="fileData"?{mediaType:i}:e;r[o]=vr(a,u)}return r}function ad(n){if(n instanceof ArrayBuffer)return new Uint8Array(n);if(wn(n)){const e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(nr(n)){const e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(vs(n)){const e=n;return Uint8Array.from(e.data)}}function od(n,e){const t=Re(n);return`data:${e&&!e.startsWith("data:")?e:"text/plain"};base64,${t}`}function Ta(n){if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function br(n){if(n==null)return n;if(Array.isArray(n))return n.map(i=>br(i));if(!Ta(n))return n;const e=n,t={},r=typeof e.type=="string"&&e.type.length>0&&ud(e.type);for(const[i,o]of Object.entries(e))r&&i==="id"||(t[i]=br(o));return t}function ud(n){switch(n){case"function_call":case"function_call_result":return!0;default:return!1}}async function Ns(n,e,t){if(!ql(n))return;const s=await n.runCompaction(typeof e>"u"?void 0:{responseId:e});if(!s)return;const r=s.usage;t._context.usage.add(new kn({requests:1,inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,inputTokensDetails:r.inputTokensDetails,outputTokensDetails:r.outputTokensDetails,requestUsageEntries:[r]}))}async function cd(n,e,t){if(!n)return;const s=e??[],r=t.state,i=r._currentTurnPersistedItemCount??0,o=t.newItems.slice(i);process.env.OPENAI_AGENTS__DEBUG_SAVE_SESSION&&console.debug("saveToSession:newRunItems",o.map(p=>p.type));const a=Sa(o),u=[...s,...a];if(u.length===0){r._currentTurnPersistedItemCount=i+o.length,await Ns(n,t.lastResponseId,r);return}const l=_r(u);await n.addItems(l),await Ns(n,t.lastResponseId,r),r._currentTurnPersistedItemCount=i+o.length}async function ld(n,e){if(!n||!e||e.length===0)return;const t=_r(e);await n.addItems(t)}async function xa(n,e){if(!n)return;const t=e.state,s=t._currentTurnPersistedItemCount??0,r=e.newItems.slice(s),i=Sa(r);if(i.length===0){t._currentTurnPersistedItemCount=s+r.length,await Ns(n,e.lastResponseId,t);return}const o=_r(i);await n.addItems(o),await Ns(n,e.lastResponseId,t),t._currentTurnPersistedItemCount=s+r.length}async function dd(n,e,t,s){if(!e)return{preparedInput:n,sessionItems:void 0};const r=(s==null?void 0:s.includeHistoryInPreparedInput)??!0,i=(s==null?void 0:s.preserveDroppedNewItems)??!1,o=await e.getItems(),a=Array.isArray(n)?[...n]:id(n);if(!t)return{preparedInput:r?[...o,...a]:a,sessionItems:a};const u=o.slice(),l=a.slice(),p=await t(o,a);if(!Array.isArray(p))throw new re("Session input callback must return an array of AgentInputItem objects.");const d=Aa(u),m=Aa(l),g=Ca(u),_=Ca(l),T=[];for(const h of p){const v=wr(h);if(Oa(_,v,h)){Ea(m,v),T.push(h);continue}if(Oa(g,v,h)){Ea(d,v);continue}const b=d.get(v)??0;if(b>0){d.set(v,b-1);continue}const N=m.get(v)??0;if(N>0){m.set(v,N-1),T.push(h);continue}T.push(h)}return{preparedInput:r?p:T.length>0?T:i?l:[],sessionItems:T}}function pd(n){if(Array.isArray(n)){const t=[];for(const s of n){const r=ka(s);if(!r)return null;t.push(r)}return t}const e=ka(n);return e?[e]:null}function ka(n){if(!Ct(n))return null;const e=n.type;if(e==="text"&&typeof n.text=="string"){const t={type:"text",text:n.text};return Ct(n.providerData)&&(t.providerData=n.providerData),t}if(e==="image"){const t={type:"image"};let s,r;const i=ge(n.mediaType)?n.mediaType:void 0,o=n.image;if(typeof o=="string"&&o.length>0)s=o;else if(Ct(o)){const a=o,u=ge(a.mediaType)?a.mediaType:i;if(ge(a.url)?s=a.url:(ge(a.data)||a.data instanceof Uint8Array&&a.data.length>0)&&(s=Es(a.data,u)),!s){const l=ge(a.fileId)&&a.fileId||ge(a.id)&&a.id||void 0;l&&(r=l)}}if(!s&&typeof n.imageUrl=="string"&&n.imageUrl.length>0&&(s=n.imageUrl),!r&&typeof n.fileId=="string"&&n.fileId.length>0&&(r=n.fileId),!s&&typeof n.data=="string"&&n.data.length>0?s=i?Es(n.data,i):n.data:!s&&n.data instanceof Uint8Array&&n.data.length>0&&(s=Es(n.data,i)),typeof n.detail=="string"&&n.detail.length>0&&(t.detail=n.detail),s)t.image=s;else if(r)t.image={fileId:r};else return null;return Ct(n.providerData)&&(t.providerData=n.providerData),t}if(e==="file"){const t=Wl(n);if(!t)return null;const s={type:"file",file:t};return Ct(n.providerData)&&(s.providerData=n.providerData),s}return null}function fd(n){if(n.type==="text"){const t={type:"input_text",text:n.text};return n.providerData&&(t.providerData=n.providerData),t}if(n.type==="image"){const t={type:"input_image"};if(typeof n.detail=="string"&&n.detail.length>0&&(t.detail=n.detail),typeof n.image=="string"&&n.image.length>0)t.image=n.image;else if(Ct(n.image)){const s=n.image,r=ge(s.mediaType)?s.mediaType:void 0;if(ge(s.url))t.image=s.url;else if(ge(s.data))t.image=r&&!s.data.startsWith("data:")?Kt(s.data,r):s.data;else if(s.data instanceof Uint8Array&&s.data.length>0){const i=Re(s.data);t.image=Kt(i,r)}else{const i=ge(s.fileId)&&s.fileId||ge(s.id)&&s.id||void 0;i&&(t.image={id:i})}}return n.providerData&&(t.providerData=n.providerData),t}if(n.type==="file"){const t={type:"input_file"},s=n.file;if(typeof s=="string")t.file=s;else if(s&&typeof s=="object"){const r=s;if("data"in r&&r.data){const i=r.mediaType??"text/plain";if(typeof r.data=="string")t.file=Kt(r.data,i);else{const o=Re(r.data);t.file=Kt(o,i)}}else if(typeof r.url=="string"&&r.url.length>0)t.file={url:r.url};else{const i=typeof r.id=="string"&&r.id.length>0&&r.id||(typeof r.fileId=="string"&&r.fileId.length>0?r.fileId:void 0);i&&(t.file={id:i})}typeof r.filename=="string"&&r.filename.length>0&&(t.filename=r.filename)}return n.providerData&&(t.providerData=n.providerData),t}return n}function Aa(n){const e=new Map;for(const t of n){const s=wr(t);e.set(s,(e.get(s)??0)+1)}return e}function Ca(n){const e=new Map;for(const t of n){const s=wr(t),r=e.get(s);r?r.push(t):e.set(s,[t])}return e}function Oa(n,e,t){const s=n.get(e);if(!s||s.length===0)return!1;const r=s.findIndex(i=>i===t);return r===-1?!1:(s.splice(r,1),s.length===0&&n.delete(e),!0)}function Ea(n,e){const t=(n.get(e)??0)-1;t<=0?n.delete(e):n.set(e,t)}function wr(n){return JSON.stringify(n,hd)}function hd(n,e){if(e instanceof ArrayBuffer)return{__type:"ArrayBuffer",data:Re(new Uint8Array(e))};if(wn(e)){const t=e;return{__type:t.constructor.name,data:Re(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}}if(nr(e)){const t=e;return{__type:"Buffer",data:Re(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}}return vs(e)?{__type:"Buffer",data:Re(Uint8Array.from(e.data))}:e}const Ps="1.0",md=I(Ps),Be=w({name:f()}),Ra=w({object:I("trace.span"),id:f(),trace_id:f(),parent_id:f().nullable(),started_at:f().nullable(),ended_at:f().nullable(),error:w({message:f(),data:se(f(),H()).optional()}).nullable(),span_data:se(f(),H())}).extend({previous_span:ru(()=>Ra).optional()}),gd=w({inputTokens:E(),outputTokens:E(),totalTokens:E(),inputTokensDetails:se(f(),E()).optional(),outputTokensDetails:se(f(),E()).optional(),endpoint:f().optional()}),Na=w({requests:E(),inputTokens:E(),outputTokens:E(),totalTokens:E(),inputTokensDetails:J(se(f(),E())).optional(),outputTokensDetails:J(se(f(),E())).optional(),requestUsageEntries:J(gd).optional()}),Pa=w({usage:Na,output:J(hr),responseId:f().optional(),providerData:se(f(),H()).optional()}),Da=ve("type",[w({type:I("message_output_item"),rawItem:Ss,agent:Be}),w({type:I("tool_call_item"),rawItem:xl.or(Sn),agent:Be}),w({type:I("tool_call_output_item"),rawItem:Ts,agent:Be,output:f()}),w({type:I("reasoning_item"),rawItem:fr,agent:Be}),w({type:I("handoff_call_item"),rawItem:Tn,agent:Be}),w({type:I("handoff_output_item"),rawItem:Ts,sourceAgent:Be,targetAgent:Be}),w({type:I("tool_approval_item"),rawItem:Tn.or(Sn).or(xs).or(ks),agent:Be,toolName:f().optional()})]),yd=w({object:I("trace"),id:f(),workflow_name:f(),group_id:f().nullable(),metadata:se(f(),H())}),_d=w({newItems:J(Da),toolsUsed:J(f()),handoffs:J(w({toolCall:H(),handoff:H()})),functions:J(w({toolCall:H(),tool:H()})),computerActions:J(w({toolCall:H(),computer:H()})),shellActions:J(w({toolCall:H(),shell:H()})).optional(),applyPatchActions:J(w({toolCall:H(),applyPatch:H()})).optional(),mcpApprovalRequests:J(w({requestItem:w({rawItem:w({type:I("hosted_tool_call"),name:f(),arguments:f().optional(),status:f().optional(),output:f().optional(),providerData:se(f(),H()).nullable().optional()})}),mcpTool:w({type:I("hosted_tool"),name:I("hosted_mcp"),providerData:se(f(),H())})})).optional()}),Ma=w({tripwireTriggered:St(),outputInfo:H()}),vd=w({guardrail:w({type:I("input"),name:f()}),output:Ma}),bd=w({guardrail:w({type:I("output"),name:f()}),agentOutput:H(),agent:Be,output:Ma}),Fa=w({$schemaVersion:md,currentTurn:E(),currentAgent:Be,originalInput:f().or(J(kl)),modelResponses:J(Pa),context:w({usage:Na,approvals:se(f(),w({approved:J(f()).or(St()),rejected:J(f()).or(St())})),context:se(f(),H())}),toolUseTracker:se(f(),J(f())),maxTurns:E(),currentAgentSpan:Ra.nullable().optional(),noActiveAgentRun:St(),inputGuardrailResults:J(vd),outputGuardrailResults:J(bd),currentStep:Vl.optional(),lastModelResponse:Pa.optional(),generatedItems:J(Da),lastProcessedResponse:_d.optional(),currentTurnPersistedItemCount:E().int().min(0).optional(),trace:yd.nullable()});class tt{constructor(e,t,s,r){S(this,"_currentTurn",0);S(this,"_currentAgent");S(this,"_originalInput");S(this,"_modelResponses");S(this,"_currentAgentSpan");S(this,"_context");S(this,"_toolUseTracker");S(this,"_generatedItems");S(this,"_currentTurnPersistedItemCount");S(this,"_maxTurns");S(this,"_noActiveAgentRun",!0);S(this,"_lastTurnResponse");S(this,"_inputGuardrailResults");S(this,"_outputGuardrailResults");S(this,"_currentStep");S(this,"_lastProcessedResponse");S(this,"_trace",null);this._context=e,this._originalInput=structuredClone(t),this._modelResponses=[],this._currentAgentSpan=void 0,this._currentAgent=s,this._toolUseTracker=new Ia,this._generatedItems=[],this._currentTurnPersistedItemCount=0,this._maxTurns=r,this._inputGuardrailResults=[],this._outputGuardrailResults=[],this._trace=Xt()}get usage(){return this._context.usage}get history(){return Yt(this._originalInput,this._generatedItems)}getInterruptions(){var e;return((e=this._currentStep)==null?void 0:e.type)!=="next_step_interruption"?[]:this._currentStep.data.interruptions}approve(e,t={alwaysApprove:!1}){this._context.approveTool(e,t)}reject(e,t={alwaysReject:!1}){this._context.rejectTool(e,t)}toJSON(){var s;const e={$schemaVersion:Ps,currentTurn:this._currentTurn,currentAgent:{name:this._currentAgent.name},originalInput:this._originalInput,modelResponses:this._modelResponses.map(r=>({usage:{requests:r.usage.requests,inputTokens:r.usage.inputTokens,outputTokens:r.usage.outputTokens,totalTokens:r.usage.totalTokens,inputTokensDetails:r.usage.inputTokensDetails,outputTokensDetails:r.usage.outputTokensDetails,...r.usage.requestUsageEntries&&r.usage.requestUsageEntries.length>0?{requestUsageEntries:r.usage.requestUsageEntries.map(i=>({inputTokens:i.inputTokens,outputTokens:i.outputTokens,totalTokens:i.totalTokens,inputTokensDetails:i.inputTokensDetails,outputTokensDetails:i.outputTokensDetails,...i.endpoint?{endpoint:i.endpoint}:{}}))}:{}},output:r.output,responseId:r.responseId,providerData:r.providerData})),context:this._context.toJSON(),toolUseTracker:this._toolUseTracker.toJSON(),maxTurns:this._maxTurns,currentAgentSpan:(s=this._currentAgentSpan)==null?void 0:s.toJSON(),noActiveAgentRun:this._noActiveAgentRun,inputGuardrailResults:this._inputGuardrailResults,outputGuardrailResults:this._outputGuardrailResults.map(r=>({...r,agent:r.agent.toJSON()})),currentStep:this._currentStep,lastModelResponse:this._lastTurnResponse,generatedItems:this._generatedItems.map(r=>r.toJSON()),currentTurnPersistedItemCount:this._currentTurnPersistedItemCount,lastProcessedResponse:this._lastProcessedResponse,trace:this._trace?this._trace.toJSON():null},t=Fa.safeParse(e);if(!t.success)throw new Vu(`Failed to serialize run state. ${t.error.message}`);return t.data}toString(){return JSON.stringify(this.toJSON())}static async fromString(e,t){var d,m,g,_,T;const[s,r]=await le(()=>JSON.parse(t));if(s)throw new re(`Failed to parse run state. ${s instanceof Error?s.message:String(s)}`);const i=r.$schemaVersion;if(!i)throw new re("Run state is missing schema version");if(i!==Ps)throw new re(`Run state schema version ${i} is not supported. Please use version ${Ps}`);const o=Fa.parse(JSON.parse(t)),a=wd(e),u=new Wt(o.context.context);u._rebuildApprovals(o.context.approvals);const l=a.get(o.currentAgent.name);if(!l)throw new re(`Agent ${o.currentAgent.name} not found`);const p=new tt(u,"",l,o.maxTurns);p._currentTurn=o.currentTurn,p._toolUseTracker=new Ia;for(const[y,h]of Object.entries(o.toolUseTracker))p._toolUseTracker.addToolUse(a.get(y),h);if(o.currentAgentSpan){o.trace||F.warn("Trace is not set, skipping tracing setup");const y=qe().createTrace({traceId:(d=o.trace)==null?void 0:d.id,name:(m=o.trace)==null?void 0:m.workflow_name,groupId:((g=o.trace)==null?void 0:g.group_id)??void 0,metadata:(_=o.trace)==null?void 0:_.metadata});p._currentAgentSpan=$a(y,o.currentAgentSpan),p._trace=y}return p._noActiveAgentRun=o.noActiveAgentRun,p._inputGuardrailResults=o.inputGuardrailResults,p._outputGuardrailResults=o.outputGuardrailResults.map(y=>({...y,agent:a.get(y.agent.name)})),p._currentStep=o.currentStep,p._originalInput=o.originalInput,p._modelResponses=o.modelResponses.map(ja),p._lastTurnResponse=o.lastModelResponse?ja(o.lastModelResponse):void 0,p._generatedItems=o.generatedItems.map(y=>Ua(y,a)),p._currentTurnPersistedItemCount=o.currentTurnPersistedItemCount??0,p._lastProcessedResponse=o.lastProcessedResponse?await Id(a,p._currentAgent,p._context,o.lastProcessedResponse):void 0,((T=o.currentStep)==null?void 0:T.type)==="next_step_handoff"&&(p._currentStep={type:"next_step_handoff",newAgent:a.get(o.currentStep.newAgent.name)}),p}}function wd(n){const e=new Map,t=[n];for(;t.length>0;){const s=t.shift();if(!e.has(s.name)){e.set(s.name,s);for(const r of s.handoffs)r instanceof Qe?e.has(r.name)||t.push(r):r.agent&&(e.has(r.agent.name)||t.push(r.agent))}}return e}function $a(n,e){const t=e.span_data,s=e.previous_span?$a(n,e.previous_span):void 0,r=qe().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:t},n);return r.previousSpan=s,r}function ja(n){return{usage:new kn(n.usage),output:n.output.map(t=>hr.parse(t)),responseId:n.responseId,providerData:n.providerData}}function Ua(n,e){switch(n.type){case"message_output_item":return new As(n.rawItem,e.get(n.agent.name));case"tool_call_item":return new et(n.rawItem,e.get(n.agent.name));case"tool_call_output_item":return new Le(n.rawItem,e.get(n.agent.name),n.output);case"reasoning_item":return new mr(n.rawItem,e.get(n.agent.name));case"handoff_call_item":return new gr(n.rawItem,e.get(n.agent.name));case"handoff_output_item":return new yr(n.rawItem,e.get(n.sourceAgent.name),e.get(n.targetAgent.name));case"tool_approval_item":return new Ie(n.rawItem,e.get(n.agent.name),n.toolName)}}async function Id(n,e,t,s){const r=await e.getAllTools(t),i=new Map(r.filter(d=>d.type==="function").map(d=>[d.name,d])),o=new Map(r.filter(d=>d.type==="computer").map(d=>[d.name,d])),a=new Map(r.filter(d=>d.type==="shell").map(d=>[d.name,d])),u=new Map(r.filter(d=>d.type==="apply_patch").map(d=>[d.name,d])),l=new Map(e.handoffs.map(d=>d instanceof Qe?[d.name,Wi(d)]:[d.toolName,d])),p={newItems:s.newItems.map(d=>Ua(d,n)),toolsUsed:s.toolsUsed,handoffs:s.handoffs.map(d=>{if(!l.has(d.handoff.toolName))throw new re(`Handoff ${d.handoff.toolName} not found`);return{toolCall:d.toolCall,handoff:l.get(d.handoff.toolName)}}),functions:await Promise.all(s.functions.map(async d=>{if(!i.has(d.tool.name))throw new re(`Tool ${d.tool.name} not found`);return{toolCall:d.toolCall,tool:i.get(d.tool.name)}})),computerActions:s.computerActions.map(d=>{const m=d.computer.name;if(!o.has(m))throw new re(`Computer tool ${m} not found`);return{toolCall:d.toolCall,computer:o.get(m)}}),shellActions:(s.shellActions??[]).map(d=>{const m=d.shell.name;if(!a.has(m))throw new re(`Shell tool ${m} not found`);return{toolCall:d.toolCall,shell:a.get(m)}}),applyPatchActions:(s.applyPatchActions??[]).map(d=>{const m=d.applyPatch.name;if(!u.has(m))throw new re(`Apply patch tool ${m} not found`);return{toolCall:d.toolCall,applyPatch:u.get(m)}}),mcpApprovalRequests:(s.mcpApprovalRequests??[]).map(d=>({requestItem:new Ie(d.requestItem.rawItem,e),mcpTool:d.mcpTool}))};return{...p,hasToolsOrApprovalsToRun(){return p.handoffs.length>0||p.functions.length>0||p.mcpApprovalRequests.length>0||p.computerActions.length>0||p.shellActions.length>0||p.applyPatchActions.length>0}}}class Sd extends jc{constructor(t={}){super();R(this,oe);S(this,"config");S(this,"inputGuardrailDefs");S(this,"outputGuardrailDefs");this.config={modelProvider:t.modelProvider??Hc(),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,sessionInputCallback:t.sessionInputCallback,callModelInputFilter:t.callModelInputFilter},this.inputGuardrailDefs=(t.inputGuardrails??[]).map(Yi),this.outputGuardrailDefs=(t.outputGuardrails??[]).map(cr)}async run(t,s,r={stream:!1,context:void 0}){const i=r??{stream:!1,context:void 0},o=i.sessionInputCallback??this.config.sessionInputCallback,a=i.callModelInputFilter??this.config.callModelInputFilter,u=!!a,l={...i,sessionInputCallback:o,callModelInputFilter:a},p=!!l.conversationId||!!l.previousResponseId,d=l.session,m=s instanceof tt;let g=d&&m?[]:void 0,_,T=d&&m?new Map:void 0;const y=(x,A)=>{const D=T;if(A!==void 0){if(!D){_=A.map(Y=>structuredClone(Y));return}const G=[],L=new WeakMap;for(const Y of x){if(!Y||typeof Y!="object")continue;const ce=(L.get(Y)??0)+1;L.set(Y,ce)}const fe=()=>{for(const[Y,ce]of D)if(ce>0)return D.set(Y,ce-1),!0;return!1};for(let Y=0;Y<A.length;Y++){const ce=A[Y];if(!ce)continue;let Me=!1;const Ve=x[Y];if(Ve&&typeof Ve=="object"){const lo=(L.get(Ve)??0)-1;if(L.set(Ve,lo),lo>0)continue;const po=Ot(Ve),fo=D.get(po)??0;if(fo>0){D.set(po,fo-1),G.push(structuredClone(ce)),Me=!0;continue}}const Qn=Ot(ce),$s=D.get(Qn)??0;if($s>0){D.set(Qn,$s-1),G.push(structuredClone(ce)),Me=!0;continue}!Ve&&fe()&&(G.push(structuredClone(ce)),Me=!0),!Me&&!Ve&&_===void 0&&G.push(structuredClone(ce))}(G.length>0||_===void 0)&&(_=G);return}const U=[];if(D)for(const G of x){if(!G)continue;const L=Ot(G),fe=D.get(L)??0;fe<=0||(D.set(L,fe-1),U.push(structuredClone(G)))}else for(const G of x)G&&U.push(structuredClone(G));U.length>0?_=U:_===void 0&&(_=[])},h=()=>{if(_!==void 0)return _;if(!u)return g};let v=s;if(!(v instanceof tt)){if(d&&Array.isArray(v)&&!o)throw new re("RunConfig.sessionInputCallback must be provided when using session history with list inputs.");const x=await dd(v,d,o,{includeHistoryInPreparedInput:!p,preserveDroppedNewItems:p});if(p&&d){const A=x.sessionItems;A&&A.length>0?v=A:v=x.preparedInput}else v=x.preparedInput;if(d){const A=x.sessionItems??[];g=A.map(D=>structuredClone(D)),T=new Map;for(const D of A){const U=Ot(D);T.set(U,(T.get(U)??0)+1)}}}let b;if(d&&!p){let x=!1;b=async()=>{if(x)return;const A=h();!A||A.length===0||(x=!0,await ld(d,A))}}const N=async()=>{if(l.stream)return await z(this,oe,_o).call(this,t,v,l,b,y);const x=await z(this,oe,go).call(this,t,v,l,y);return d&&!p&&await cd(d,h(),x),x};return v instanceof tt&&v._trace?Ed(v._trace,async()=>(v._currentAgentSpan&&Tr(v._currentAgentSpan),N())):Rd(async()=>N(),{traceId:this.config.traceId,name:this.config.workflowName,groupId:this.config.groupId,metadata:this.config.traceMetadata})}}oe=new WeakSet,$r=function(t){return this.inputGuardrailDefs.concat(t._currentAgent.inputGuardrails.map(Yi))},jr=function(t){const s=z(this,oe,$r).call(this,t),r=[],i=[];for(const o of s)o.runInParallel===!1?r.push(o):i.push(o);return{blocking:r,parallel:i}},mo=async function(t){const s=t.model!==void 0&&t.model!==Qe.DEFAULT_MODEL_PLACEHOLDER||this.config.model!==void 0&&this.config.model!==Qe.DEFAULT_MODEL_PLACEHOLDER;let r=Td(t.model,this.config.model);return typeof r=="string"&&(r=await this.config.modelProvider.getModel(r)),{model:r,explictlyModelSet:s}},go=async function(t,s,r,i){return xr(async()=>{var p,d,m;const o=s instanceof tt,a=o?s:new tt(r.context instanceof Wt?r.context:new Wt(r.context),s,t,r.maxTurns??La),u=r.conversationId||r.previousResponseId?new Ba({conversationId:r.conversationId,previousResponseId:r.previousResponseId}):void 0;u&&o&&u.primeFromState({originalInput:a._originalInput,generatedItems:a._generatedItems,modelResponses:a._modelResponses});let l=!1;try{for(;;){if(a._currentStep=a._currentStep??{type:"next_step_run_again"},a._currentStep.type==="next_step_interruption"){if(F.debug("Continuing from interruption"),!a._lastTurnResponse||!a._lastProcessedResponse)throw new re("No model response found in previous state",a);const g=await ha(a._currentAgent,a._originalInput,a._generatedItems,a._lastTurnResponse,a._lastProcessedResponse,this,a);if(a._toolUseTracker.addToolUse(a._currentAgent,a._lastProcessedResponse.toolsUsed),a._originalInput=g.originalInput,a._generatedItems=g.generatedItems,g.nextStep.type==="next_step_interruption")return a._currentStep=g.nextStep,new Sr(a);if(g.nextStep.type==="next_step_run_again"){l=!0,a._currentStep=void 0;continue}l=!1,a._currentStep=g.nextStep}if(a._currentStep.type==="next_step_run_again"){const g=await Za(a),_=o&&l;if(l=!1,_||(a._currentTurn++,a._currentTurnPersistedItemCount=0),a._currentTurn>a._maxTurns)throw(p=a._currentAgentSpan)==null||p.setError({message:"Max turns exceeded",data:{max_turns:a._maxTurns}}),new vi(`Max turns (${a._maxTurns}) exceeded`,a);F.debug(`Running agent ${a._currentAgent.name} (turn ${a._currentTurn})`);let T;if(a._currentTurn===1&&!_){const N=z(this,oe,jr).call(this,a);N.blocking.length>0&&await z(this,oe,es).call(this,a,N.blocking),N.parallel.length>0&&(T=z(this,oe,es).call(this,a,N.parallel),T.catch(()=>{}))}const y=u?u.prepareInput(a._originalInput,a._generatedItems):Yt(a._originalInput,a._generatedItems);a._noActiveAgentRun&&(a._currentAgent.emit("agent_start",a._context,a._currentAgent,y),this.emit("agent_start",a._context,a._currentAgent,y));const h=await z(this,oe,Lr).call(this,a,r,g,y,u,i);a._lastTurnResponse=await h.model.getResponse({systemInstructions:h.modelInput.instructions,prompt:h.prompt,...h.explictlyModelSet?{overridePromptModel:!0}:{},input:h.modelInput.input,previousResponseId:h.previousResponseId,conversationId:h.conversationId,modelSettings:h.modelSettings,tools:h.serializedTools,toolsExplicitlyProvided:h.toolsExplicitlyProvided,outputType:Ci(a._currentAgent.outputType),handoffs:h.serializedHandoffs,tracing:za(this.config.tracingDisabled,this.config.traceIncludeSensitiveData),signal:r.signal}),a._modelResponses.push(a._lastTurnResponse),a._context.usage.add(a._lastTurnResponse.usage),a._noActiveAgentRun=!1,u==null||u.trackServerItems(a._lastTurnResponse);const v=fa(a._lastTurnResponse,a._currentAgent,h.tools,h.handoffs);a._lastProcessedResponse=v;const b=await ma(a._currentAgent,a._originalInput,a._generatedItems,a._lastTurnResponse,a._lastProcessedResponse,this,a);a._toolUseTracker.addToolUse(a._currentAgent,a._lastProcessedResponse.toolsUsed),a._originalInput=b.originalInput,a._generatedItems=b.generatedItems,b.nextStep.type==="next_step_run_again"&&(a._currentTurnPersistedItemCount=0),a._currentStep=b.nextStep,T&&await T}if(a._currentStep&&a._currentStep.type==="next_step_final_output")return await z(this,oe,Ur).call(this,a,a._currentStep.output),this.emit("agent_end",a._context,a._currentAgent,a._currentStep.output),a._currentAgent.emit("agent_end",a._context,a._currentStep.output),new Sr(a);if(a._currentStep&&a._currentStep.type==="next_step_handoff")a._currentAgent=a._currentStep.newAgent,a._currentAgentSpan&&(a._currentAgentSpan.end(),Cn(),a._currentAgentSpan=void 0),a._noActiveAgentRun=!0,a._currentStep={type:"next_step_run_again"};else{if(a._currentStep&&a._currentStep.type==="next_step_interruption")return new Sr(a);F.debug("Running next loop")}}}catch(g){throw a._currentAgentSpan&&a._currentAgentSpan.setError({message:"Error in agent run",data:{error:String(g)}}),g}finally{if(((d=a._currentStep)==null?void 0:d.type)!=="next_step_interruption")try{await Bi({runContext:a._context})}catch(g){F.warn(`Failed to dispose computers after run: ${g}`)}a._currentAgentSpan&&(((m=a._currentStep)==null?void 0:m.type)!=="next_step_interruption"&&a._currentAgentSpan.end(),Cn())}})},yo=async function(t,s,r,i,o){var g,_,T,y;const a=!!s.conversationId||!!s.previousResponseId,u=a?new Ba({conversationId:s.conversationId,previousResponseId:s.previousResponseId}):void 0;let l=!1,p=!1;const d=async()=>{p||!i||(await i(),p=!0)};u&&r&&u.primeFromState({originalInput:t.state._originalInput,generatedItems:t.state._generatedItems,modelResponses:t.state._modelResponses});let m=!1;try{for(;;){const h=t.state._currentAgent;if(t.state._currentStep=t.state._currentStep??{type:"next_step_run_again"},t.state._currentStep.type==="next_step_interruption"){if(F.debug("Continuing from interruption"),!t.state._lastTurnResponse||!t.state._lastProcessedResponse)throw new re("No model response found in previous state",t.state);const v=await ha(t.state._currentAgent,t.state._originalInput,t.state._generatedItems,t.state._lastTurnResponse,t.state._lastProcessedResponse,this,t.state);if(wa(t,v),t.state._toolUseTracker.addToolUse(t.state._currentAgent,t.state._lastProcessedResponse.toolsUsed),t.state._originalInput=v.originalInput,t.state._generatedItems=v.generatedItems,v.nextStep.type==="next_step_interruption"){t.state._currentStep=v.nextStep;return}if(v.nextStep.type==="next_step_run_again"){m=!0,t.state._currentStep=void 0;continue}m=!1,t.state._currentStep=v.nextStep}if(t.state._currentStep.type==="next_step_run_again"){const v=await Za(t.state),b=r&&m;if(m=!1,b||(t.state._currentTurn++,t.state._currentTurnPersistedItemCount=0),t.state._currentTurn>t.state._maxTurns)throw(g=t.state._currentAgentSpan)==null||g.setError({message:"Max turns exceeded",data:{max_turns:t.state._maxTurns}}),new vi(`Max turns (${t.state._maxTurns}) exceeded`,t.state);F.debug(`Running agent ${h.name} (turn ${t.state._currentTurn})`);let N,x;if(t.state._currentTurn===1&&!b){const Y=z(this,oe,jr).call(this,t.state);Y.blocking.length>0&&await z(this,oe,es).call(this,t.state,Y.blocking),Y.parallel.length>0&&(x=z(this,oe,es).call(this,t.state,Y.parallel).catch(Me=>(N=Me,[])))}const A=u?u.prepareInput(t.input,t.newItems):Yt(t.input,t.newItems);t.state._noActiveAgentRun&&(h.emit("agent_start",t.state._context,h,A),this.emit("agent_start",t.state._context,h,A));let D;const U=await z(this,oe,Lr).call(this,t.state,s,v,A,u,o);if(N)throw N;l=!0,await d();for await(const Y of U.model.getStreamedResponse({systemInstructions:U.modelInput.instructions,prompt:U.prompt,...U.explictlyModelSet?{overridePromptModel:!0}:{},input:U.modelInput.input,previousResponseId:U.previousResponseId,conversationId:U.conversationId,modelSettings:U.modelSettings,tools:U.serializedTools,toolsExplicitlyProvided:U.toolsExplicitlyProvided,handoffs:U.serializedHandoffs,outputType:Ci(h.outputType),tracing:za(this.config.tracingDisabled,this.config.traceIncludeSensitiveData),signal:s.signal})){if(N)throw N;if(Y.type==="response_done"){const ce=ua.parse(Y);D={usage:new kn(ce.response.usage),output:ce.response.output,responseId:ce.response.id},t.state._context.usage.add(D.usage)}if(t.cancelled)return;t._addItem(new zl(Y))}if(x&&(await x,N))throw N;if(t.state._noActiveAgentRun=!1,!D)throw new Se("Model did not produce a final response!",t.state);t.state._lastTurnResponse=D,u==null||u.trackServerItems(D),t.state._modelResponses.push(t.state._lastTurnResponse);const G=fa(t.state._lastTurnResponse,h,U.tools,U.handoffs);t.state._lastProcessedResponse=G;const L=new Set(G.newItems);L.size>0&&rd(t,G.newItems);const fe=await ma(h,t.state._originalInput,t.state._generatedItems,t.state._lastTurnResponse,t.state._lastProcessedResponse,this,t.state);wa(t,fe,{skipItems:L}),t.state._toolUseTracker.addToolUse(h,G.toolsUsed),t.state._originalInput=fe.originalInput,t.state._generatedItems=fe.generatedItems,fe.nextStep.type==="next_step_run_again"&&(t.state._currentTurnPersistedItemCount=0),t.state._currentStep=fe.nextStep}if(t.state._currentStep.type==="next_step_final_output"){await z(this,oe,Ur).call(this,t.state,t.state._currentStep.output),await d(),a||await xa(s.session,t),this.emit("agent_end",t.state._context,h,t.state._currentStep.output),h.emit("agent_end",t.state._context,t.state._currentStep.output);return}else if(t.state._currentStep.type==="next_step_interruption"){await d(),a||await xa(s.session,t);return}else t.state._currentStep.type==="next_step_handoff"?(t.state._currentAgent=(_=t.state._currentStep)==null?void 0:_.newAgent,t.state._currentAgentSpan&&(t.state._currentAgentSpan.end(),Cn()),t.state._currentAgentSpan=void 0,t._addItem(new Zl(t.state._currentAgent)),t.state._noActiveAgentRun=!0,t.state._currentStep={type:"next_step_run_again"}):F.debug("Running next loop")}}catch(h){throw l&&!p&&await d(),t.state._currentAgentSpan&&t.state._currentAgentSpan.setError({message:"Error in agent run",data:{error:String(h)}}),h}finally{if(((T=t.state._currentStep)==null?void 0:T.type)!=="next_step_interruption")try{await Bi({runContext:t.state._context})}catch(h){F.warn(`Failed to dispose computers after run: ${h}`)}t.state._currentAgentSpan&&(((y=t.state._currentStep)==null?void 0:y.type)!=="next_step_interruption"&&t.state._currentAgentSpan.end(),Cn())}},_o=async function(t,s,r,i,o){return r=r??{},xr(async()=>{const a=s instanceof tt,u=a?s:new tt(r.context instanceof Wt?r.context:new Wt(r.context),s,t,r.maxTurns??La),l=new Ga({signal:r.signal,state:u});l.maxTurns=r.maxTurns??u._maxTurns;const p=z(this,oe,yo).call(this,l,r,a,i,o).then(()=>{l._done()},d=>{l._raiseError(d)});return l._setStreamLoopPromise(p),l})},es=async function(t,s){const r=s??z(this,oe,$r).call(this,t);if(r.length>0){const i={agent:t._currentAgent,input:t._originalInput,context:t._context};try{const o=await Promise.all(r.map(async a=>la(async u=>{const l=await a.run(i);return u.spanData.triggered=l.output.tripwireTriggered,l},{data:{name:a.name}},t._currentAgentSpan)));t._inputGuardrailResults.push(...o);for(const a of o)if(a.output.tripwireTriggered)throw t._currentAgentSpan&&t._currentAgentSpan.setError({message:"Guardrail tripwire triggered",data:{guardrail:a.guardrail.name}}),new wi(`Input guardrail triggered: ${JSON.stringify(a.output.outputInfo)}`,a,t);return o}catch(o){throw o instanceof wi?o:(t._currentTurn--,new bi(`Input guardrail failed to complete: ${o}`,o,t))}}return[]},Ur=async function(t,s){const r=this.outputGuardrailDefs.concat(t._currentAgent.outputGuardrails.map(cr));if(r.length>0){const i=t._currentAgent.processFinalOutput(s),o=Yt([],t._generatedItems),a={agent:t._currentAgent,agentOutput:i,context:t._context,details:{modelResponse:t._lastTurnResponse,output:o}};try{const u=await Promise.all(r.map(async l=>la(async p=>{const d=await l.run(a);return p.spanData.triggered=d.output.tripwireTriggered,d},{data:{name:l.name}},t._currentAgentSpan)));for(const l of u)if(l.output.tripwireTriggered)throw t._currentAgentSpan&&t._currentAgentSpan.setError({message:"Guardrail tripwire triggered",data:{guardrail:l.guardrail.name}}),new Ys(`Output guardrail triggered: ${JSON.stringify(l.output.outputInfo)}`,l,t)}catch(u){throw u instanceof Ys?u:new bi(`Output guardrail failed to complete: ${u}`,u,t)}}},Lr=async function(t,s,r,i,o,a){const{model:u,explictlyModelSet:l}=await z(this,oe,mo).call(this,t._currentAgent);let p={...this.config.modelSettings,...t._currentAgent.modelSettings};p=kd(l,t._currentAgent.modelSettings,u,p),p=Hl(t._currentAgent,t._toolUseTracker,p);const d=await t._currentAgent.getSystemPrompt(t._context),m=await t._currentAgent.getPrompt(t._context),{modelInput:g,sourceItems:_,persistedItems:T,filterApplied:y}=await xd(t._currentAgent,s.callModelInputFilter,t._context,i,d);o==null||o.markInputAsSent(_),a==null||a(_,y?T:void 0);const h=(o==null?void 0:o.previousResponseId)??s.previousResponseId,v=(o==null?void 0:o.conversationId)??s.conversationId;return{...r,model:u,explictlyModelSet:l,modelSettings:p,modelInput:g,prompt:m,previousResponseId:h,conversationId:v}};function Yt(n,e){const t=e.filter(s=>s.type!=="tool_approval_item").map(s=>s.rawItem);return[...Ir(n),...t]}const La=10;function Td(n,e){return typeof n=="string"&&n!==Qe.DEFAULT_MODEL_PLACEHOLDER||n?n:e??n??Qe.DEFAULT_MODEL_PLACEHOLDER}function za(n,e){return n?!1:e?!0:"enabled_without_data"}async function xd(n,e,t,s,r){const i=(g,_)=>g.map(T=>{const y=structuredClone(T);return _&&y&&typeof y=="object"&&_.set(y,T),y}),o=new WeakMap,a=Ad(s),u=[];for(const g of s)g&&typeof g=="object"&&u.push(g);const l=g=>{if(!g||typeof g!="object")return;const _=u.findIndex(T=>T===g);_!==-1&&u.splice(_,1)},p=()=>{const g=u.shift();return g&&qa(a,g),g},m={input:i(s,o),instructions:r};if(!e)return{modelInput:m,sourceItems:[...s],persistedItems:[],filterApplied:!1};try{const g=await e({modelData:m,agent:n,context:t.context});if(!g||!Array.isArray(g.input))throw new re("callModelInputFilter must return a ModelInputData object with an input array.");const _=g.input.map(y=>{if(!y||typeof y!="object")return;const h=o.get(y);if(h)return l(h),qa(a,h),h;const v=Ot(y),b=Cd(a,v);if(b)return l(b),b;const N=p();if(N)return N}),T=i(g.input);return{modelInput:{input:T,instructions:typeof g.instructions>"u"?r:g.instructions},sourceItems:_,persistedItems:T.map(y=>structuredClone(y)),filterApplied:!0}}catch(g){throw nt({message:"Error in callModelInputFilter",data:{error:String(g)}}),g}}class Ba{constructor({conversationId:e,previousResponseId:t}){S(this,"conversationId");S(this,"previousResponseId");S(this,"sentInitialInput",!1);S(this,"sentItems",new WeakSet);S(this,"serverItems",new WeakSet);S(this,"remainingInitialInput",null);this.conversationId=e??void 0,this.previousResponseId=t??void 0}primeFromState({originalInput:e,generatedItems:t,modelResponses:s}){if(this.sentInitialInput)return;for(const i of Ir(e))i&&typeof i=="object"&&this.sentItems.add(i);this.sentInitialInput=!0,this.remainingInitialInput=null;const r=s[s.length-1];for(const i of s)for(const o of i.output)o&&typeof o=="object"&&this.serverItems.add(o);!this.conversationId&&(r!=null&&r.responseId)&&(this.previousResponseId=r.responseId);for(const i of t){const o=i.rawItem;!o||typeof o!="object"||this.serverItems.has(o)&&this.sentItems.add(o)}}trackServerItems(e){if(e){for(const t of e.output)t&&typeof t=="object"&&this.serverItems.add(t);!this.conversationId&&e.responseId&&(this.previousResponseId=e.responseId)}}prepareInput(e,t){const s=[];if(this.sentInitialInput)this.remainingInitialInput&&this.remainingInitialInput.length>0&&s.push(...this.remainingInitialInput);else{const r=Ir(e);s.push(...r),this.remainingInitialInput=r.filter(i=>!!i&&typeof i=="object"),this.sentInitialInput=!0}for(const r of t){if(r.type==="tool_approval_item")continue;const i=r.rawItem;!i||typeof i!="object"||this.sentItems.has(i)||this.serverItems.has(i)||s.push(i)}return s}markInputAsSent(e){if(!e.length)return;const t=new Set;for(const s of e)!s||typeof s!="object"||t.has(s)||(t.add(s),this.sentItems.add(s));!this.remainingInitialInput||this.remainingInitialInput.length===0||(this.remainingInitialInput=this.remainingInitialInput.filter(s=>!t.has(s)),this.remainingInitialInput.length===0&&(this.remainingInitialInput=null))}}function kd(n,e,t,s){var r,i,o,a,u,l,p,d;if(Ji()&&n&&(typeof t!="string"||!Is(t))&&((r=e.providerData)!=null&&r.reasoning||(o=(i=e.providerData)==null?void 0:i.text)!=null&&o.verbosity||(a=e.providerData)!=null&&a.reasoning_effort)){const m={...s};return(u=m.providerData)==null||delete u.reasoning,(p=(l=m.providerData)==null?void 0:l.text)==null||delete p.verbosity,(d=m.providerData)==null||delete d.reasoning_effort,m.reasoning&&(delete m.reasoning.effort,delete m.reasoning.summary),m.text&&delete m.text.verbosity,m}return s}async function Za(n){const e=await n._currentAgent.getEnabledHandoffs(n._context),t=await n._currentAgent.getAllTools(n._context),s=t.filter(r=>r.type==="computer");if(s.length>0&&await Promise.all(s.map(async r=>{await zi({tool:r,runContext:n._context})})),n._currentAgentSpan)n._currentAgentSpan.spanData.tools=t.map(r=>r.name);else{const r=e.map(i=>i.agentName);n._currentAgentSpan=Dl({data:{name:n._currentAgent.name,handoffs:r,tools:t.map(i=>i.name),output_type:n._currentAgent.outputSchemaName}}),n._currentAgentSpan.start(),Tr(n._currentAgentSpan)}return{handoffs:e,tools:t,serializedHandoffs:e.map(r=>Pl(r)),serializedTools:t.map(r=>Nl(r)),toolsExplicitlyProvided:n._currentAgent.hasExplicitToolConfig()}}function Ot(n){return JSON.stringify(n,Od)}function Ad(n){const e=new Map;for(const t of n){const s=Ot(t),r=e.get(s);r?r.push(t):e.set(s,[t])}return e}function Cd(n,e){const t=n.get(e);if(!t||t.length===0)return;const[s]=t;return t.shift(),t.length===0&&n.delete(e),s}function qa(n,e){const t=Ot(e),s=n.get(t);if(!s||s.length===0)return;const r=s.findIndex(i=>i===e);r!==-1&&(s.splice(r,1),s.length===0&&n.delete(t))}function Od(n,e){if(e instanceof ArrayBuffer)return{__type:"ArrayBuffer",data:Re(new Uint8Array(e))};if(wn(e)){const t=e;return{__type:t.constructor.name,data:Re(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}}if(nr(e)){const t=e;return{__type:"Buffer",data:Re(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}}return vs(e)?{__type:"Buffer",data:Re(Uint8Array.from(e.data))}:e}function Ir(n){return typeof n=="string"?[{type:"message",role:"user",content:n}]:[...n]}class Ja{constructor(e){S(this,"state");this.state=e}get history(){return Yt(this.input,this.newItems)}get output(){return Yt([],this.newItems)}get input(){return this.state._originalInput}get newItems(){return this.state._generatedItems}get rawResponses(){return this.state._modelResponses}get lastResponseId(){const e=this.rawResponses;return e&&e.length>0?e[e.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(){var e;return((e=this.state._currentStep)==null?void 0:e.type)==="next_step_interruption"?this.state._currentStep.data.interruptions:[]}get finalOutput(){var e;if(((e=this.state._currentStep)==null?void 0:e.type)==="next_step_final_output")return this.state._currentAgent.processFinalOutput(this.state._currentStep.output);F.warn("Accessed finalOutput before agent run is completed.")}}class Sr extends Ja{constructor(e){super(e)}}class Ga extends Ja{constructor(t={}){super(t.state);S(this,"currentTurn",0);S(this,"maxTurns");R(this,Rn,null);R(this,pt);R(this,Ae);R(this,st);R(this,sn);R(this,rn);R(this,Nn);R(this,Pt,!1);R(this,Pn);if(k(this,pt,t.signal),k(this,st,new Nc({start:s=>{k(this,Ae,s)},cancel:()=>{k(this,Pt,!0)}})),k(this,sn,new Promise((s,r)=>{k(this,rn,s),k(this,Nn,r)})),c(this,pt)){const s=()=>{var i,o;if(c(this,Pt))return;k(this,Pt,!0);const r=c(this,Ae);if(k(this,Ae,void 0),c(this,st).locked){if(r)try{r.close()}catch(a){F.debug(`Failed to close readable stream on abort: ${a}`)}}else c(this,st).cancel((i=c(this,pt))==null?void 0:i.reason).catch(a=>{F.debug(`Failed to cancel readable stream on abort: ${a}`)});(o=c(this,rn))==null||o.call(this)};c(this,pt).aborted?s():c(this,pt).addEventListener("abort",s,{once:!0})}}get currentAgent(){return this.lastAgent}_addItem(t){var s;this.cancelled||(s=c(this,Ae))==null||s.enqueue(t)}_done(){var t;!this.cancelled&&c(this,Ae)&&(c(this,Ae).close(),k(this,Ae,void 0),(t=c(this,rn))==null||t.call(this))}_raiseError(t){var s;!this.cancelled&&c(this,Ae)&&(c(this,Ae).error(t),k(this,Ae,void 0)),k(this,Rn,t),(s=c(this,Nn))==null||s.call(this,t),c(this,sn).catch(r=>{F.debug(`Resulted in an error: ${r}`)})}get cancelled(){return c(this,Pt)}toStream(){return c(this,st)}get completed(){return c(this,sn)}get error(){return c(this,Rn)}toTextStream(t={}){const s=c(this,st).pipeThrough(new Pc({transform(r,i){if(r.type==="raw_model_stream_event"&&r.data.type==="output_text_delta"){const o=oa.parse(r.data);i.enqueue(o.delta)}}}));return t.compatibleWithNodeStreams?Rc.fromWeb(s):s}[Symbol.asyncIterator](){return c(this,st)[Symbol.asyncIterator]()}_setStreamLoopPromise(t){k(this,Pn,t)}_getStreamLoopPromise(){return c(this,Pn)}}Rn=new WeakMap,pt=new WeakMap,Ae=new WeakMap,st=new WeakMap,sn=new WeakMap,rn=new WeakMap,Nn=new WeakMap,Pt=new WeakMap,Pn=new WeakMap;let Va;function Ze(){return Va??(Va=new Dc),Va}function Xt(){const n=Ze().getStore();return n!=null&&n.trace?n.trace:null}function An(){const n=Ze().getStore();return n!=null&&n.span?n.span:null}function Ha(n){return async()=>{const e=Xt();if(!e)throw new Error("No trace found");await e.start();const t=await n(e);if(t instanceof Ga){const s=t._getStreamLoopPromise();if(s)return s.finally(()=>e.end()),t}return await e.end(),t}}async function Ed(n,e,t={}){const s=typeof n=="string"?qe().createTrace({...t,name:n}):n;return Ze().run({trace:s},Ha(e))}async function Rd(n,e={}){if(Xt())return await n();const s=qe().createTrace(e);return Ze().run({trace:s},Ha(n))}function Tr(n){const e=Ze().getStore();if(!e)throw new Error("No existing trace found");e.span&&(e.span.previousSpan=e.previousSpan,e.previousSpan=e.span),n.previousSpan=e.span??e.previousSpan,e.span=n,Ze().enterWith(e)}function Cn(){var e;const n=Ze().getStore();n&&(n.span=n.previousSpan,n.previousSpan=(e=n.previousSpan)==null?void 0:e.previousSpan,Ze().enterWith(n))}function nt(n){const e=An();e&&e.setError(n)}function Nd(n){var e,t,s;return{trace:(e=n.trace)==null?void 0:e.clone(),span:(t=n.span)==null?void 0:t.clone(),previousSpan:(s=n.previousSpan)==null?void 0:s.clone()}}function xr(n){const e=Ze().getStore();if(!e)throw new Error("No existing trace found");const t=Nd(e);return Ze().run(t,n)}class Pd{async export(e){if(Di.disabled){F.debug("Tracing is disabled. Skipping export");return}for(const t of e)t.type==="trace"?console.log(`[Exporter] Export trace traceId=${t.traceId} name=${t.name}${t.groupId?` groupId=${t.groupId}`:""}`):console.log(`[Exporter] Export span: ${JSON.stringify(t)}`)}}class Dd{constructor(e,{maxQueueSize:t=1e3,maxBatchSize:s=100,scheduleDelay:r=5e3,exportTriggerRatio:i=.8}={}){R(this,Te);R(this,Dn);R(this,an);R(this,Mn);R(this,Fn);R(this,on);R(this,be,[]);R(this,rt);R(this,ft,null);R(this,ht,!1);R(this,un,null);k(this,Dn,t),k(this,an,s),k(this,Mn,r),k(this,Fn,t*i),k(this,on,e),k(this,rt,Fc),F.debug("Automatic trace export loop is not supported in this environment. You need to manually call `getGlobalTraceProvider().forceFlush()` to export traces.")}start(){k(this,un,new AbortController),z(this,Te,Br).call(this)}async onTraceStart(e){await z(this,Te,zr).call(this,e)}async onTraceEnd(e){}async onSpanStart(e){}async onSpanEnd(e){await z(this,Te,zr).call(this,e)}async shutdown(e){var t;for(e&&c(this,rt).setTimeout(()=>{var s;(s=c(this,un))==null||s.abort()},e),F.debug("Shutting down gracefully");c(this,be).length>0;){if(F.debug(`Waiting for buffer to empty. Items left: ${c(this,be).length}`),c(this,ht)||await z(this,Te,gn).call(this,!0),(t=c(this,un))!=null&&t.signal.aborted){F.debug("Timeout reached, force flushing"),await z(this,Te,gn).call(this,!0);break}await new Promise(s=>c(this,rt).setTimeout(s,500))}F.debug("Buffer empty. Exiting"),c(this,rt)&&c(this,ft)&&c(this,rt).clearTimeout(c(this,ft))}async forceFlush(){c(this,be).length>0&&await z(this,Te,gn).call(this,!0)}}Dn=new WeakMap,an=new WeakMap,Mn=new WeakMap,Fn=new WeakMap,on=new WeakMap,be=new WeakMap,rt=new WeakMap,ft=new WeakMap,ht=new WeakMap,un=new WeakMap,Te=new WeakSet,zr=async function(e){if(c(this,be).length+1>c(this,Dn)){F.error("Dropping trace because buffer is full");return}c(this,be).push(e),c(this,be).length>c(this,Fn)&&await z(this,Te,gn).call(this)},Br=function(){k(this,ft,c(this,rt).setTimeout(async()=>{await z(this,Te,gn).call(this),z(this,Te,Br).call(this)},c(this,Mn))),typeof c(this,ft).unref=="function"&&c(this,ft).unref()},gn=async function(e=!1){if(c(this,be).length!==0){if(F.debug(`Exporting batches. Force: ${e}. Buffer size: ${c(this,be).length}`),e||c(this,be).length<c(this,an)){const t=[...c(this,be)];k(this,be,[]),k(this,ht,!0),await c(this,on).export(t),k(this,ht,!1)}else if(c(this,be).length>0){const t=c(this,be).splice(0,c(this,an));k(this,ht,!0),await c(this,on).export(t),k(this,ht,!1)}}};class Md{constructor(){R(this,Ce,[])}start(){for(const e of c(this,Ce))e.start&&e.start()}addTraceProcessor(e){c(this,Ce).push(e)}setProcessors(e){F.debug("Shutting down old processors");for(const t of c(this,Ce))t.shutdown();k(this,Ce,e)}async onTraceStart(e){for(const t of c(this,Ce))await t.onTraceStart(e)}async onTraceEnd(e){for(const t of c(this,Ce))await t.onTraceEnd(e)}async onSpanStart(e){for(const t of c(this,Ce))await t.onSpanStart(e)}async onSpanEnd(e){for(const t of c(this,Ce))await t.onSpanEnd(e)}async shutdown(e){for(const t of c(this,Ce))await t.shutdown(e)}async forceFlush(){for(const e of c(this,Ce))await e.forceFlush()}}Ce=new WeakMap;let kr=null,Ar=null;function Fd(){return kr||(kr=new Pd),kr}function Wa(){return Ar||(Ar=new Dd(Fd())),Ar}function Ka(){return new Date().toISOString()}function Ya(){return`trace_${qi().replace(/-/g,"")}`}function $d(){return`span_${qi().replace(/-/g,"").slice(0,24)}`}function jd(n){return Object.fromEntries(Object.entries(n).filter(([e])=>!e.startsWith("_")))}const Nr=class Nr{constructor(e,t){S(this,"type","trace.span");R(this,$n);R(this,jn);R(this,Un);R(this,Ln);R(this,Dt);R(this,mt);R(this,gt);R(this,Mt);R(this,zn);k(this,jn,e.traceId),k(this,Un,e.spanId??$d()),k(this,$n,e.data),k(this,Dt,t),k(this,Ln,e.parentId??null),k(this,Mt,e.error??null),k(this,mt,e.startedAt??null),k(this,gt,e.endedAt??null)}get traceId(){return c(this,jn)}get spanData(){return c(this,$n)}get spanId(){return c(this,Un)}get parentId(){return c(this,Ln)}get previousSpan(){return c(this,zn)}set previousSpan(e){k(this,zn,e)}start(){if(c(this,mt)){F.warn("Span already started");return}k(this,mt,Ka()),c(this,Dt).onSpanStart(this)}end(){if(c(this,gt)){F.debug("Span already finished",this.spanData);return}k(this,gt,Ka()),c(this,Dt).onSpanEnd(this)}setError(e){k(this,Mt,e)}get error(){return c(this,Mt)}get startedAt(){return c(this,mt)}get endedAt(){return c(this,gt)}clone(){var t;const e=new Nr({traceId:this.traceId,spanId:this.spanId,parentId:this.parentId??void 0,data:this.spanData,startedAt:c(this,mt)??void 0,endedAt:c(this,gt)??void 0,error:c(this,Mt)??void 0},c(this,Dt));return e.previousSpan=(t=this.previousSpan)==null?void 0:t.clone(),e}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:jd(this.spanData),error:this.error}}};$n=new WeakMap,jn=new WeakMap,Un=new WeakMap,Ln=new WeakMap,Dt=new WeakMap,mt=new WeakMap,gt=new WeakMap,Mt=new WeakMap,zn=new WeakMap;let On=Nr;class dt extends On{constructor(e,t){super({traceId:"no-op",spanId:"no-op",data:e},t)}start(){}end(){}setError(){}toJSON(){return null}}const Pr=class Pr{constructor(e,t){S(this,"type","trace");S(this,"traceId");S(this,"name");S(this,"groupId",null);S(this,"metadata");R(this,cn);R(this,it);this.traceId=e.traceId??Ya(),this.name=e.name??"Agent workflow",this.groupId=e.groupId??null,this.metadata=e.metadata??{},k(this,cn,t??Wa()),k(this,it,e.started??!1)}async start(){c(this,it)||(k(this,it,!0),await c(this,cn).onTraceStart(this))}async end(){c(this,it)&&(k(this,it,!1),await c(this,cn).onTraceEnd(this))}clone(){return new Pr({traceId:this.traceId,name:this.name,groupId:this.groupId??void 0,metadata:this.metadata,started:c(this,it)})}toJSON(){return{object:this.type,id:this.traceId,workflow_name:this.name,group_id:this.groupId,metadata:this.metadata}}};cn=new WeakMap,it=new WeakMap;let En=Pr;class Cr extends En{constructor(){super({})}async start(){}async end(){}toJSON(){return null}}class Ud{constructor(){R(this,Fs);R(this,_e);R(this,Ft);k(this,_e,new Md),k(this,Ft,Di.disabled),z(this,Fs,vo).call(this)}registerProcessor(e){c(this,_e).addTraceProcessor(e)}setProcessors(e){c(this,_e).setProcessors(e)}getCurrentTrace(){return Xt()}getCurrentSpan(){return An()}setDisabled(e){k(this,Ft,e)}startExportLoop(){c(this,_e).start()}createTrace(e){if(c(this,Ft))return F.debug("Tracing is disabled, Not creating trace %o",e),new Cr;const t=e.traceId??Ya(),s=e.name??"Agent workflow";return F.debug("Creating trace %s with name %s",t,s),new En({...e,name:s,traceId:t},c(this,_e))}createSpan(e,t){if(c(this,Ft)||e.disabled)return F.debug("Tracing is disabled, Not creating span %o",e),new dt(e.data,c(this,_e));let s,r;if(t){if(t instanceof En){if(t instanceof Cr)return F.debug("Parent trace is no-op, returning NoopSpan"),new dt(e.data,c(this,_e));r=t.traceId}else if(t instanceof On){if(t instanceof dt)return F.debug("Parent span is no-op, returning NoopSpan"),new dt(e.data,c(this,_e));s=t.spanId,r=t.traceId}}else{const i=Xt(),o=An();if(!i)return F.error("No active trace. Make sure to start a trace with `withTrace()` first. Returning NoopSpan."),new dt(e.data,c(this,_e));if(o instanceof dt||i instanceof Cr)return F.debug(`Parent ${o} or ${i} is no-op, returning NoopSpan`),new dt(e.data,c(this,_e));r=i.traceId,o?(F.debug("Using parent span %s",o.spanId),s=o.spanId):F.debug("No parent span, using current trace %s",i.traceId)}return r?(F.debug(`Creating span ${JSON.stringify(e.data)} with id ${e.spanId??r}`),new On({...e,traceId:r,parentId:s},c(this,_e))):(F.error("No traceId found. Make sure to start a trace with `withTrace()` first. Returning NoopSpan."),new dt(e.data,c(this,_e)))}async shutdown(e){try{F.debug("Shutting down tracing provider"),await c(this,_e).shutdown(e)}catch(t){F.error("Error shutting down tracing provider %o",t)}}async forceFlush(){await c(this,_e).forceFlush()}}_e=new WeakMap,Ft=new WeakMap,Fs=new WeakSet,vo=function(){if(typeof process<"u"&&typeof process.on=="function"){const e=async()=>{const t=setTimeout(()=>{console.warn("Cleanup timeout, forcing exit"),process.exit(1)},5e3);try{await this.shutdown()}finally{clearTimeout(t)}};process.on("beforeExit",e),process.on("SIGINT",async()=>{await e(),Xa("SIGINT")||process.exit(130)}),process.on("SIGTERM",async()=>{await e(),Xa("SIGTERM")||process.exit(0)}),process.on("unhandledRejection",async(t,s)=>{F.error("Unhandled rejection",t,s),await e(),Ld("unhandledRejection")||process.exit(1)})}};function Xa(n){return process.listeners(n).length>1}function Ld(n){return process.listeners(n).length>1}let Or;function qe(){return Or||(Or=new Ud),Or}function zd(n){qe().registerProcessor(n)}zd(Wa());function Bd(n){const e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return s.buffer}function Zd(n){const e=String.fromCharCode(...new Uint8Array(n));return btoa(e)}function qd(n){if(typeof n>"u"||n===null||typeof n!="object"||!("type"in n)||typeof n.type!="string"||!n.type||n.type!=="message"||!("content"in n)||!Array.isArray(n.content)||n.content.length<1)return;const e=n.content[n.content.length-1];if(!(!("type"in e)||typeof e.type!="string")){if(e.type==="output_text")return typeof e.text=="string"?e.text:void 0;if(e.type==="output_audio")return typeof e.transcript=="string"?e.transcript:void 0}}function Jd(n,e){const t=n.filter(i=>!e.some(o=>o.itemId===i.itemId)),s=e.filter(i=>!n.some(o=>o.itemId===i.itemId)),r=e.filter(i=>n.some(o=>o.itemId===i.itemId&&JSON.stringify(o)!==JSON.stringify(i)));return{removals:t,additions:s,updates:r}}function Gd(){return typeof window>"u"?!1:typeof window.RTCPeerConnection<"u"}function Qa(n){return n.role==="system"?n:n.role==="assistant"?{...n,content:n.content.map(e=>e.type==="output_audio"?{...e,audio:null}:e)}:n.role==="user"?{...n,content:n.content.map(e=>e.type==="input_audio"?{...e,audio:null}:e)}:n}function Vd(n,e){if(n.role!=="assistant"||e.role!=="assistant")return e;const t=e.content.map((s,r)=>{if(s.type!=="output_audio"||!(typeof s.transcript!="string"||s.transcript.length===0))return s;const o=n.content[r];return o&&o.type==="output_audio"&&typeof o.transcript=="string"&&o.transcript.length>0?{...s,transcript:o.transcript}:s});return{...e,content:t}}function eo(n,e,t){if(e.type==="conversation.item.input_audio_transcription.completed")return n.map(i=>{if(i.itemId===e.item_id&&i.type==="message"&&"role"in i&&i.role==="user"){const o=i.content.map(a=>a.type==="input_audio"?{...a,transcript:e.transcript}:a);return{...i,content:o,status:"completed"}}return i});const s=!t&&e.type==="message"?Qa(e):e,r=n.findIndex(i=>i.itemId===e.itemId);if(r!==-1){const i=n[r],o=s.type==="message"&&i.type==="message"?Vd(i,s):s;return n.map((a,u)=>u===r?o:!t&&a.type==="message"?Qa(a):a)}else if(e.previousItemId){const i=n.findIndex(o=>o.itemId===e.previousItemId);return i!==-1?[...n.slice(0,i+1),s,...n.slice(i+1)]:[...n,s]}else return[...n,s]}const to={"User-Agent":`Agents/JavaScript ${te.version}`,"X-OpenAI-Agents-SDK":`openai-agents-sdk.${te.version}`},Hd=`openai-agents-sdk.${te.version}`;function Wd(n,e){const{name:t,arguments:s,...r}=e;return new Ie({type:"hosted_tool_call",name:t,arguments:JSON.stringify(s),status:"in_progress",providerData:{...r}},n)}function no(n){if(n.rawItem.type!=="function_call"&&n.rawItem.type!=="hosted_tool_call")throw new Error("Invalid approval item type for Realtime MCP approval request");const{name:e,arguments:t,providerData:s}=n.rawItem,{itemId:r,serverLabel:i,...o}=s??{};if(!r||!i)throw new Error("Invalid approval item for Realtime MCP approval request");return{type:"mcp_approval_request",itemId:r,serverLabel:i,...o,name:e,arguments:t?JSON.parse(t):{},approved:null}}class Kd extends Qe{constructor(t){super(t);S(this,"voice");this.voice=t.voice}}function Yd(n){return{debounceTextLength:n.debounceTextLength??100}}function Xd({policyHint:n,...e}){const t=cr(e),s=n??t.name;return{...t,policyHint:s,run:async r=>{const i=await t.run(r);return{...i,guardrail:{...i.guardrail,policyHint:s}}}}}function Qd(n){return`
|
|
3
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const p=d[1];if(e===d[0]){a(d);continue}if(s.external){const f=s.external.registry.get(d[0])?.id;if(e!==d[0]&&f){a(d);continue}}if(this.metadataRegistry.get(d[0])?.id){a(d);continue}if(p.cycle){a(d);continue}if(p.count>1&&s.reused==="ref"){a(d);continue}}const o=(d,p)=>{const h=this.seen.get(d),f=h.def??h.schema,m={...f};if(h.ref===null)return;const g=h.ref;if(h.ref=null,g){o(g,p);const _=this.seen.get(g).schema;_.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(_)):(Object.assign(f,_),Object.assign(f,m))}h.isParent||this.override({zodSchema:d,jsonSchema:f,path:h.path??[]})};for(const d of[...this.seen.entries()].reverse())o(d[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),s.external?.uri){const d=s.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");u.$id=s.external.uri(d)}Object.assign(u,r.def);const l=s.external?.defs??{};for(const d of this.seen.entries()){const p=d[1];p.def&&p.defId&&(l[p.defId]=p.def)}s.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function wi(t,e){if(t instanceof Wn){const s=new Kn(e),r={};for(const o of t._idmap.entries()){const[u,l]=o;s.process(l)}const i={},a={registry:t,uri:e?.uri,defs:r};for(const o of t._idmap.entries()){const[u,l]=o;i[u]=s.emit(l,{...e,external:a})}if(Object.keys(r).length>0){const o=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[o]:r}}return{schemas:i}}const n=new Kn(e);return n.process(t),n.emit(t,e)}function W(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const r=t._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return W(r.element,n);case"object":{for(const i in r.shape)if(W(r.shape[i],n))return!0;return!1}case"union":{for(const i of r.options)if(W(i,n))return!0;return!1}case"intersection":return W(r.left,n)||W(r.right,n);case"tuple":{for(const i of r.items)if(W(i,n))return!0;return!!(r.rest&&W(r.rest,n))}case"record":return W(r.keyType,n)||W(r.valueType,n);case"map":return W(r.keyType,n)||W(r.valueType,n);case"set":return W(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return W(r.innerType,n);case"lazy":return W(r.getter(),n);case"default":return W(r.innerType,n);case"prefault":return W(r.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return W(r.in,n)||W(r.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${r.type}`)}function Ii(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}const Si=Symbol("Let zodToJsonSchema decide on which parser to use"),Yn={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"},Ti=t=>typeof t=="string"?{...Yn,basePath:["#"],definitions:{},name:t}:{...Yn,basePath:["#"],definitions:{},...t},tn=t=>"_def"in t?t._def:t;function xi(t){if(!t)return!0;for(const e in t)return!1;return!0}const ki=t=>{const e=Ti(t),n=e.name!==void 0?[...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(([s,r])=>[tn(r),{def:tn(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function Xn(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Z(t,e,n,s,r){t[e]=n,Xn(t,e,s,r)}var B;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const a of r)i[a]=a;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(const o of i)a[o]=r[o];return t.objectValues(a)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&i.push(a);return i},t.find=(r,i)=>{for(const a of r)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(B||(B={}));var Qn;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Qn||(Qn={}));const O=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Oe=t=>{switch(typeof t){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(t)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(t)?O.array:t===null?O.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?O.promise:typeof Map<"u"&&t instanceof Map?O.map:typeof Set<"u"&&t instanceof Set?O.set:typeof Date<"u"&&t instanceof Date?O.date:O.object;default:return O.unknown}},I=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class de extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)s._errors.push(n(a));else{let o=s,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(n(a))):o[l]=o[l]||{_errors:[]},o=o[l],u++}}};return r(this),s}static assert(e){if(!(e instanceof de))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}de.create=t=>new de(t);const nn=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===O.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,B.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:B.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,B.assertNever(t)}return{message:n}};let Ai=nn;function Ci(){return Ai}const Oi=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],a={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let o="";const u=s.filter(l=>!!l).slice().reverse();for(const l of u)o=l(a,{data:e,defaultError:o}).message;return{...r,path:i,message:o}};function A(t,e){const n=Ci(),s=Oi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===nn?void 0:nn].filter(r=>!!r)});t.common.issues.push(s)}class Q{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return P;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,a=await r.value;s.push({key:i,value:a})}return Q.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:a}=r;if(i.status==="aborted"||a.status==="aborted")return P;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(s[i.value]=a.value)}return{status:e.value,value:s}}}const P=Object.freeze({status:"aborted"}),ot=t=>({status:"dirty",value:t}),se=t=>({status:"valid",value:t}),es=t=>t.status==="aborted",ts=t=>t.status==="dirty",Ye=t=>t.status==="valid",wt=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));class pe{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ns=(t,e)=>{if(Ye(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new de(t.common.issues);return this._error=n,this._error}}};function j(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(a,o)=>{const{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??s??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:u??n??o.defaultError}},description:r}}class U{get description(){return this._def.description}_getType(e){return Oe(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Q,ctx:{common:e.parent.common,data:e.data,parsedType:Oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(wt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Oe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return ns(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Oe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Ye(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Ye(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Oe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(wt(r)?r:Promise.resolve(r));return ns(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const a=e(r),o=()=>i.addIssue({code:I.custom,...s(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new $e({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Se.create(this,this._def)}nullable(){return Ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fe.create(this)}promise(){return Ct.create(this,this._def)}or(e){return St.create([this,e],this._def)}and(e){return Tt.create(this,e,this._def)}transform(e){return new $e({...j(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Ot({...j(this._def),innerType:this,defaultValue:n,typeName:S.ZodDefault})}brand(){return new ds({typeName:S.ZodBranded,type:this,...j(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Et({...j(this._def),innerType:this,catchValue:n,typeName:S.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return dn.create(this,e)}readonly(){return Rt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ei=/^c[^\s-]{8,}$/i,Ri=/^[0-9a-z]+$/,Ni=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Di=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pi=/^[a-z0-9_-]{21}$/i,Mi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fi=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ji=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$i="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let sn;const Ui=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Li=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Bi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,zi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ss="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ji=new RegExp(`^${ss}$`);function rs(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Gi(t){return new RegExp(`^${rs(t)}$`)}function Vi(t){let e=`${ss}T${rs(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Hi(t,e){return!!((e==="v4"||!e)&&Ui.test(t)||(e==="v6"||!e)&&Bi.test(t))}function Wi(t,e){if(!Mi.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ki(t,e){return!!((e==="v4"||!e)&&Li.test(t)||(e==="v6"||!e)&&zi.test(t))}class we extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){const i=this._getOrReturnCtx(e);return A(i,{code:I.invalid_type,expected:O.string,received:i.parsedType}),P}const s=new Q;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),A(r,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),A(r,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(r=this._getOrReturnCtx(e,r),a?A(r,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&A(r,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")ji.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"email",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")sn||(sn=new RegExp($i,"u")),sn.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"emoji",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")Di.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"uuid",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Pi.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"nanoid",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Ei.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"cuid",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")Ri.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"cuid2",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Ni.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"ulid",code:I.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),A(r,{validation:"url",code:I.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"regex",code:I.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),A(r,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),A(r,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),A(r,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Vi(i).test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{code:I.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ji.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{code:I.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Gi(i).test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{code:I.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Fi.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"duration",code:I.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Hi(e.data,i.version)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"ip",code:I.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Wi(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"jwt",code:I.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ki(e.data,i.version)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"cidr",code:I.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Zi.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"base64",code:I.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?qi.test(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{validation:"base64url",code:I.invalid_string,message:i.message}),s.dirty()):B.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:I.invalid_string,...N.errToObj(s)})}_addCheck(e){return new we({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...N.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...N.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...N.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...N.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...N.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...N.errToObj(n)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new we({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new we({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new we({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}we.create=t=>new we({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...j(t)});function Yi(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),a=Number.parseInt(e.toFixed(r).replace(".",""));return i%a/10**r}class Xe extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){const i=this._getOrReturnCtx(e);return A(i,{code:I.invalid_type,expected:O.number,received:i.parsedType}),P}let s;const r=new Q;for(const i of this._def.checks)i.kind==="int"?B.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Yi(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),A(s,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:I.not_finite,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,s,r){return new Xe({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:N.toString(r)}]})}_addCheck(e){return new Xe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&B.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Xe.create=t=>new Xe({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...j(t)});class ut extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let s;const r=new Q;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),A(s,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return A(n,{code:I.invalid_type,expected:O.bigint,received:n.parsedType}),P}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,s,r){return new ut({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:N.toString(r)}]})}_addCheck(e){return new ut({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}ut.create=t=>new ut({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...j(t)});class rn extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){const s=this._getOrReturnCtx(e);return A(s,{code:I.invalid_type,expected:O.boolean,received:s.parsedType}),P}return se(e.data)}}rn.create=t=>new rn({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...j(t)});class It extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){const i=this._getOrReturnCtx(e);return A(i,{code:I.invalid_type,expected:O.date,received:i.parsedType}),P}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return A(i,{code:I.invalid_date}),P}const s=new Q;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),A(r,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),A(r,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):B.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new It({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}It.create=t=>new It({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...j(t)});class is extends U{_parse(e){if(this._getType(e)!==O.symbol){const s=this._getOrReturnCtx(e);return A(s,{code:I.invalid_type,expected:O.symbol,received:s.parsedType}),P}return se(e.data)}}is.create=t=>new is({typeName:S.ZodSymbol,...j(t)});class an extends U{_parse(e){if(this._getType(e)!==O.undefined){const s=this._getOrReturnCtx(e);return A(s,{code:I.invalid_type,expected:O.undefined,received:s.parsedType}),P}return se(e.data)}}an.create=t=>new an({typeName:S.ZodUndefined,...j(t)});class on extends U{_parse(e){if(this._getType(e)!==O.null){const s=this._getOrReturnCtx(e);return A(s,{code:I.invalid_type,expected:O.null,received:s.parsedType}),P}return se(e.data)}}on.create=t=>new on({typeName:S.ZodNull,...j(t)});class ct extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return se(e.data)}}ct.create=t=>new ct({typeName:S.ZodAny,...j(t)});class as extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return se(e.data)}}as.create=t=>new as({typeName:S.ZodUnknown,...j(t)});class Ee extends U{_parse(e){const n=this._getOrReturnCtx(e);return A(n,{code:I.invalid_type,expected:O.never,received:n.parsedType}),P}}Ee.create=t=>new Ee({typeName:S.ZodNever,...j(t)});class os extends U{_parse(e){if(this._getType(e)!==O.undefined){const s=this._getOrReturnCtx(e);return A(s,{code:I.invalid_type,expected:O.void,received:s.parsedType}),P}return se(e.data)}}os.create=t=>new os({typeName:S.ZodVoid,...j(t)});class fe extends U{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==O.array)return A(n,{code:I.invalid_type,expected:O.array,received:n.parsedType}),P;if(r.exactLength!==null){const a=n.data.length>r.exactLength.value,o=n.data.length<r.exactLength.value;(a||o)&&(A(n,{code:a?I.too_big:I.too_small,minimum:o?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(A(n,{code:I.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(A(n,{code:I.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>r.type._parseAsync(new pe(n,a,n.path,o)))).then(a=>Q.mergeArray(s,a));const i=[...n.data].map((a,o)=>r.type._parseSync(new pe(n,a,n.path,o)));return Q.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new fe({...this._def,minLength:{value:e,message:N.toString(n)}})}max(e,n){return new fe({...this._def,maxLength:{value:e,message:N.toString(n)}})}length(e,n){return new fe({...this._def,exactLength:{value:e,message:N.toString(n)}})}nonempty(e){return this.min(1,e)}}fe.create=(t,e)=>new fe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...j(e)});function Qe(t){if(t instanceof V){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=Se.create(Qe(s))}return new V({...t._def,shape:()=>e})}else return t instanceof fe?new fe({...t._def,type:Qe(t.element)}):t instanceof Se?Se.create(Qe(t.unwrap())):t instanceof Ue?Ue.create(Qe(t.unwrap())):t instanceof Fe?Fe.create(t.items.map(e=>Qe(e))):t}class V extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=B.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==O.object){const l=this._getOrReturnCtx(e);return A(l,{code:I.invalid_type,expected:O.object,received:l.parsedType}),P}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ee&&this._def.unknownKeys==="strip"))for(const l in r.data)a.includes(l)||o.push(l);const u=[];for(const l of a){const d=i[l],p=r.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new pe(r,p,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Ee){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of o)u.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(l==="strict")o.length>0&&(A(r,{code:I.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of o){const p=r.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new pe(r,p,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of u){const p=await d.key,h=await d.value;l.push({key:p,value:h,alwaysSet:d.alwaysSet})}return l}).then(l=>Q.mergeObjectSync(s,l)):Q.mergeObjectSync(s,u)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new V({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:N.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new V({...this._def,unknownKeys:"strip"})}passthrough(){return new V({...this._def,unknownKeys:"passthrough"})}extend(e){return new V({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new V({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new V({...this._def,catchall:e})}pick(e){const n={};for(const s of B.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new V({...this._def,shape:()=>n})}omit(e){const n={};for(const s of B.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new V({...this._def,shape:()=>n})}deepPartial(){return Qe(this)}partial(e){const n={};for(const s of B.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new V({...this._def,shape:()=>n})}required(e){const n={};for(const s of B.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Se;)i=i._def.innerType;n[s]=i}return new V({...this._def,shape:()=>n})}keyof(){return cs(B.objectKeys(this.shape))}}V.create=(t,e)=>new V({shape:()=>t,unknownKeys:"strip",catchall:Ee.create(),typeName:S.ZodObject,...j(e)}),V.strictCreate=(t,e)=>new V({shape:()=>t,unknownKeys:"strict",catchall:Ee.create(),typeName:S.ZodObject,...j(e)}),V.lazycreate=(t,e)=>new V({shape:t,unknownKeys:"strip",catchall:Ee.create(),typeName:S.ZodObject,...j(e)});class St extends U{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new de(o.ctx.common.issues));return A(n,{code:I.invalid_union,unionErrors:a}),P}if(n.common.async)return Promise.all(s.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(r);{let i;const a=[];for(const u of s){const l={...n,common:{...n.common,issues:[]},parent:null},d=u._parseSync({data:n.data,path:n.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(u=>new de(u));return A(n,{code:I.invalid_union,unionErrors:o}),P}}get options(){return this._def.options}}St.create=(t,e)=>new St({options:t,typeName:S.ZodUnion,...j(e)});const Ie=t=>t instanceof kt?Ie(t.schema):t instanceof $e?Ie(t.innerType()):t instanceof At?[t.value]:t instanceof je?t.options:t instanceof ln?B.objectValues(t.enum):t instanceof Ot?Ie(t._def.innerType):t instanceof an?[void 0]:t instanceof on?[null]:t instanceof Se?[void 0,...Ie(t.unwrap())]:t instanceof Ue?[null,...Ie(t.unwrap())]:t instanceof ds||t instanceof Rt?Ie(t.unwrap()):t instanceof Et?Ie(t._def.innerType):[];class un extends U{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.object)return A(n,{code:I.invalid_type,expected:O.object,received:n.parsedType}),P;const s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,s){const r=new Map;for(const i of n){const a=Ie(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(r.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);r.set(o,i)}}return new un({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:r,...j(s)})}}function cn(t,e){const n=Oe(t),s=Oe(e);if(t===e)return{valid:!0,data:t};if(n===O.object&&s===O.object){const r=B.objectKeys(e),i=B.objectKeys(t).filter(o=>r.indexOf(o)!==-1),a={...t,...e};for(const o of i){const u=cn(t[o],e[o]);if(!u.valid)return{valid:!1};a[o]=u.data}return{valid:!0,data:a}}else if(n===O.array&&s===O.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],u=cn(a,o);if(!u.valid)return{valid:!1};r.push(u.data)}return{valid:!0,data:r}}else return n===O.date&&s===O.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Tt extends U{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,a)=>{if(es(i)||es(a))return P;const o=cn(i.value,a.value);return o.valid?((ts(i)||ts(a))&&n.dirty(),{status:n.value,value:o.data}):(A(s,{code:I.invalid_intersection_types}),P)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,a])=>r(i,a)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Tt.create=(t,e,n)=>new Tt({left:t,right:e,typeName:S.ZodIntersection,...j(n)});class Fe extends U{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==O.array)return A(s,{code:I.invalid_type,expected:O.array,received:s.parsedType}),P;if(s.data.length<this._def.items.length)return A(s,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&s.data.length>this._def.items.length&&(A(s,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((a,o)=>{const u=this._def.items[o]||this._def.rest;return u?u._parse(new pe(s,a,s.path,o)):null}).filter(a=>!!a);return s.common.async?Promise.all(i).then(a=>Q.mergeArray(n,a)):Q.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Fe({...this._def,rest:e})}}Fe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Fe({items:t,typeName:S.ZodTuple,rest:null,...j(e)})};class xt extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==O.object)return A(s,{code:I.invalid_type,expected:O.object,received:s.parsedType}),P;const r=[],i=this._def.keyType,a=this._def.valueType;for(const o in s.data)r.push({key:i._parse(new pe(s,o,s.path,o)),value:a._parse(new pe(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?Q.mergeObjectAsync(n,r):Q.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof U?new xt({keyType:e,valueType:n,typeName:S.ZodRecord,...j(s)}):new xt({keyType:we.create(),valueType:e,typeName:S.ZodRecord,...j(n)})}}class us extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==O.map)return A(s,{code:I.invalid_type,expected:O.map,received:s.parsedType}),P;const r=this._def.keyType,i=this._def.valueType,a=[...s.data.entries()].map(([o,u],l)=>({key:r._parse(new pe(s,o,s.path,[l,"key"])),value:i._parse(new pe(s,u,s.path,[l,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const u of a){const l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return P;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),o.set(l.value,d.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const u of a){const l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return P;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),o.set(l.value,d.value)}return{status:n.value,value:o}}}}us.create=(t,e,n)=>new us({valueType:e,keyType:t,typeName:S.ZodMap,...j(n)});class lt extends U{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==O.set)return A(s,{code:I.invalid_type,expected:O.set,received:s.parsedType}),P;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(A(s,{code:I.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(A(s,{code:I.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function a(u){const l=new Set;for(const d of u){if(d.status==="aborted")return P;d.status==="dirty"&&n.dirty(),l.add(d.value)}return{status:n.value,value:l}}const o=[...s.data.values()].map((u,l)=>i._parse(new pe(s,u,s.path,l)));return s.common.async?Promise.all(o).then(u=>a(u)):a(o)}min(e,n){return new lt({...this._def,minSize:{value:e,message:N.toString(n)}})}max(e,n){return new lt({...this._def,maxSize:{value:e,message:N.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}lt.create=(t,e)=>new lt({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...j(e)});class kt extends U{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}kt.create=(t,e)=>new kt({getter:t,typeName:S.ZodLazy,...j(e)});class At extends U{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return A(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:e.data}}get value(){return this._def.value}}At.create=(t,e)=>new At({value:t,typeName:S.ZodLiteral,...j(e)});function cs(t,e){return new je({values:t,typeName:S.ZodEnum,...j(e)})}class je extends U{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return A(n,{expected:B.joinValues(s),received:n.parsedType,code:I.invalid_type}),P}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return A(n,{received:n.data,code:I.invalid_enum_value,options:s}),P}return se(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return je.create(e,{...this._def,...n})}exclude(e,n=this._def){return je.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}je.create=cs;class ln extends U{_parse(e){const n=B.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==O.string&&s.parsedType!==O.number){const r=B.objectValues(n);return A(s,{expected:B.joinValues(r),received:s.parsedType,code:I.invalid_type}),P}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=B.objectValues(n);return A(s,{received:s.data,code:I.invalid_enum_value,options:r}),P}return se(e.data)}get enum(){return this._def.values}}ln.create=(t,e)=>new ln({values:t,typeName:S.ZodNativeEnum,...j(e)});class Ct extends U{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.promise&&n.common.async===!1)return A(n,{code:I.invalid_type,expected:O.promise,received:n.parsedType}),P;const s=n.parsedType===O.promise?n.data:Promise.resolve(n.data);return se(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Ct.create=(t,e)=>new Ct({type:t,typeName:S.ZodPromise,...j(e)});class $e extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:a=>{A(s,a),a.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const a=r.transform(s.data,i);if(s.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return P;const u=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return u.status==="aborted"?P:u.status==="dirty"||n.value==="dirty"?ot(u.value):u});{if(n.value==="aborted")return P;const o=this._def.schema._parseSync({data:a,path:s.path,parent:s});return o.status==="aborted"?P:o.status==="dirty"||n.value==="dirty"?ot(o.value):o}}if(r.type==="refinement"){const a=o=>{const u=r.refinement(o,i);if(s.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?P:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?P:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(r.type==="transform")if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Ye(a))return P;const o=r.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>Ye(a)?Promise.resolve(r.transform(a.value,i)).then(o=>({status:n.value,value:o})):P);B.assertNever(r)}}$e.create=(t,e,n)=>new $e({schema:t,typeName:S.ZodEffects,effect:e,...j(n)}),$e.createWithPreprocess=(t,e,n)=>new $e({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...j(n)});class Se extends U{_parse(e){return this._getType(e)===O.undefined?se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Se.create=(t,e)=>new Se({innerType:t,typeName:S.ZodOptional,...j(e)});class Ue extends U{_parse(e){return this._getType(e)===O.null?se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ue.create=(t,e)=>new Ue({innerType:t,typeName:S.ZodNullable,...j(e)});class Ot extends U{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===O.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ot.create=(t,e)=>new Ot({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...j(e)});class Et extends U{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return wt(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new de(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new de(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Et.create=(t,e)=>new Et({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...j(e)});class ls extends U{_parse(e){if(this._getType(e)!==O.nan){const s=this._getOrReturnCtx(e);return A(s,{code:I.invalid_type,expected:O.nan,received:s.parsedType}),P}return{status:"valid",value:e.data}}}ls.create=t=>new ls({typeName:S.ZodNaN,...j(t)});class ds extends U{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class dn extends U{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?P:i.status==="dirty"?(n.dirty(),ot(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?P:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new dn({in:e,out:n,typeName:S.ZodPipeline})}}class Rt extends U{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Ye(r)&&(r.value=Object.freeze(r.value)),r);return wt(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Rt.create=(t,e)=>new Rt({innerType:t,typeName:S.ZodReadonly,...j(e)});function ps(t,e){const n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Xi(t,e={},n){return t?ct.create().superRefine((s,r)=>{const i=t(s);if(i instanceof Promise)return i.then(a=>{if(!a){const o=ps(e,s),u=o.fatal??n??!0;r.addIssue({code:"custom",...o,fatal:u})}});if(!i){const a=ps(e,s),o=a.fatal??n??!0;r.addIssue({code:"custom",...a,fatal:o})}}):ct.create()}var S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));const fs=(t,e={message:`Input not instance of ${t.name}`})=>Xi(n=>n instanceof t,e),c=we.create,T=Xe.create,Le=rn.create,$=ct.create;Ee.create;const M=fe.create,y=V.create,Te=St.create,X=un.create;Tt.create,Fe.create;const q=xt.create,Qi=kt.create,v=At.create,H=je.create;Ct.create,Se.create,Ue.create;function ea(){return{}}function ta(t,e){const n={type:"array"};return t.type?._def?.typeName!==S.ZodAny&&(n.items=z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Z(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Z(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Z(n,"minItems",t.exactLength.value,t.exactLength.message,e),Z(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function na(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?Z(n,"minimum",s.value,s.message,e):Z(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),Z(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?Z(n,"maximum",s.value,s.message,e):Z(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),Z(n,"maximum",s.value,s.message,e));break;case"multipleOf":Z(n,"multipleOf",s.value,s.message,e);break}return n}function sa(){return{type:"boolean"}}function ra(t,e){return z(t.type._def,e)}const ia=(t,e)=>z(t.innerType._def,e);function hs(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,i)=>hs(t,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return aa(t,e)}}const aa=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const s of t.checks)switch(s.kind){case"min":Z(n,"minimum",s.value,s.message,e);break;case"max":Z(n,"maximum",s.value,s.message,e);break}return n};function oa(t,e){return{...z(t.innerType._def,e),default:t.defaultValue()}}function ua(t,e,n){return e.effectStrategy==="input"?z(t.schema._def,e,n):{}}function ca(t){return{type:"string",enum:[...t.values]}}const la=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function da(t,e){const n=[z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(i=>{if(la(i))r.push(...i.allOf),i.unevaluatedProperties===void 0&&(s=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:o,...u}=i;a=u}else s=void 0;r.push(a)}}),r.length?{allOf:r,...s}:void 0}function pa(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let pn;const Be={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(pn===void 0&&(pn=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pn),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function ms(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?fa(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":Z(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":Z(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":oe(n,"email",r.message,e);break;case"format:idn-email":oe(n,"idn-email",r.message,e);break;case"pattern:zod":ue(n,Be.email,r.message,e);break}break;case"url":oe(n,"uri",r.message,e);break;case"uuid":oe(n,"uuid",r.message,e);break;case"regex":ue(n,r.regex,r.message,e);break;case"cuid":ue(n,Be.cuid,r.message,e);break;case"cuid2":ue(n,Be.cuid2,r.message,e);break;case"startsWith":ue(n,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":ue(n,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":oe(n,"date-time",r.message,e);break;case"date":oe(n,"date",r.message,e);break;case"time":oe(n,"time",r.message,e);break;case"duration":oe(n,"duration",r.message,e);break;case"length":Z(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),Z(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ue(n,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&oe(n,"ipv4",r.message,e),r.version!=="v4"&&oe(n,"ipv6",r.message,e);break}case"emoji":ue(n,Be.emoji,r.message,e);break;case"ulid":{ue(n,Be.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{oe(n,"binary",r.message,e);break}case"contentEncoding:base64":{Z(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ue(n,Be.base64,r.message,e);break}}break}case"nanoid":ue(n,Be.nanoid,r.message,e)}return n}const fa=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),oe=(t,e,n,s)=>{t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&s.errorMessages&&{errorMessage:{format:n}}})):Z(t,"format",e,n,s)},ue=(t,e,n,s)=>{t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:gs(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):Z(t,"pattern",gs(e,s),n,s)},gs=(t,e)=>{const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const s={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=s.i?n.source.toLowerCase():n.source;let i="",a=!1,o=!1,u=!1;for(let l=0;l<r.length;l++){if(a){i+=r[l],a=!1;continue}if(s.i){if(o){if(r[l].match(/[a-z]/)){u?(i+=r[l],i+=`${r[l-2]}-${r[l]}`.toUpperCase(),u=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(i+=r[l],u=!0):i+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){i+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(s.m){if(r[l]==="^"){i+=`(^|(?<=[\r
|
|
4
|
+
]))`;continue}else if(r[l]==="$"){i+=`($|(?=[\r
|
|
5
|
+
]))`;continue}}if(s.s&&r[l]==="."){i+=o?`${r[l]}\r
|
|
6
|
+
`:`[${r[l]}\r
|
|
7
|
+
]`;continue}i+=r[l],r[l]==="\\"?a=!0:o&&r[l]==="]"?o=!1:!o&&r[l]==="["&&(o=!0)}try{const l=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 ys(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,r)=>({...s,[r]:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){const s=Object.entries(ms(t.keyType._def,e)).reduce((r,[i,a])=>i==="type"?r:{...r,[i]:a},{});return{...n,propertyNames:s}}else if(t.keyType?._def.typeName===S.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function ha(t,e){if(e.mapStrategy==="record")return ys(t,e);const n=z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,s],minItems:2,maxItems:2}}}function ma(t){const e=t.values,s=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),r=Array.from(new Set(s.map(i=>typeof i)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:s}}function ga(){return{not:{}}}function ya(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Nt={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _a(t,e){if(e.target==="openApi3")return _s(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in Nt&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,i)=>{const a=Nt[i._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:s.length>1?s:s[0]}}else if(n.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=n.reduce((r,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(i._def.value===null)return[...r,"null"];default:return r}},[]);if(s.length===n.length){const r=s.filter((i,a,o)=>o.indexOf(i)===a);return{type:r.length>1?r:r[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((s,r)=>[...s,...r._def.values.filter(i=>!s.includes(i))],[])};return _s(t,e)}const _s=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>z(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return n.length?{anyOf:n}:void 0};function va(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Nt[t.innerType._def.typeName],nullable:!0}:{type:[Nt[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function ba(t,e){const n={type:"number"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"int":n.type="integer",Xn(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?Z(n,"minimum",s.value,s.message,e):Z(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),Z(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?Z(n,"maximum",s.value,s.message,e):Z(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),Z(n,"maximum",s.value,s.message,e));break;case"multipleOf":Z(n,"multipleOf",s.value,s.message,e);break}return n}function wa(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ia(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((s,[r,i])=>{if(i===void 0||i._def===void 0)return s;const a=[...e.currentPath,"properties",r],o=z(i._def,{...e,currentPath:a,propertyPath:a});if(o===void 0)return s;if(e.openaiStrictMode&&i.isOptional()&&!i.isNullable()&&typeof i._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.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:{...s.properties,[r]:o},required:i.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,r]}},{properties:{},required:[]}),additionalProperties:wa(t,e)};return n.required.length||delete n.required,n}const Sa=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return z(t.innerType._def,{...e,currentPath:e.currentPath});const n=z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Ta=(t,e)=>{if(e.pipeStrategy==="input")return z(t.in._def,e);if(e.pipeStrategy==="output")return z(t.out._def,e);const n=z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function xa(t,e){return z(t.type._def,e)}function ka(t,e){const s={type:"array",uniqueItems:!0,items:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Z(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Z(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function Aa(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>z(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>z(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function Ca(){return{not:{}}}function Oa(){return{}}const Ea=(t,e)=>z(t.innerType._def,e);function z(t,e,n=!1){const s=e.seen.get(t);if(e.override){const a=e.override?.(t,e,s,n);if(a!==Si)return a}if(s&&!n){const a=Ra(s,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}const r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);const i=Da(t,t.typeName,e,n);return i&&Pa(t,e,i),r.jsonSchema=i,i}const Ra=(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&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:Na(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,r)=>e.currentPath[r]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Na=(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("/")},Da=(t,e,n,s)=>{switch(e){case S.ZodString:return ms(t,n);case S.ZodNumber:return ba(t,n);case S.ZodObject:return Ia(t,n);case S.ZodBigInt:return na(t,n);case S.ZodBoolean:return sa();case S.ZodDate:return hs(t,n);case S.ZodUndefined:return Ca();case S.ZodNull:return ya(n);case S.ZodArray:return ta(t,n);case S.ZodUnion:case S.ZodDiscriminatedUnion:return _a(t,n);case S.ZodIntersection:return da(t,n);case S.ZodTuple:return Aa(t,n);case S.ZodRecord:return ys(t,n);case S.ZodLiteral:return pa(t,n);case S.ZodEnum:return ca(t);case S.ZodNativeEnum:return ma(t);case S.ZodNullable:return va(t,n);case S.ZodOptional:return Sa(t,n);case S.ZodMap:return ha(t,n);case S.ZodSet:return ka(t,n);case S.ZodLazy:return z(t.getter()._def,n);case S.ZodPromise:return xa(t,n);case S.ZodNaN:case S.ZodNever:return ga();case S.ZodEffects:return ua(t,n,s);case S.ZodAny:return ea();case S.ZodUnknown:return Oa();case S.ZodDefault:return oa(t,n);case S.ZodBranded:return ra(t,n);case S.ZodReadonly:return Ea(t,n);case S.ZodCatch:return ia(t,n);case S.ZodPipeline:return Ta(t,n);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(r=>{})()}},Pa=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Ma=(t,e)=>{const n=ki(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=z(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(r.title=i);const a=(()=>{if(xi(n.definitions))return;const u={},l=new Set;for(let d=0;d<500;d++){const p=Object.entries(n.definitions).filter(([h])=>!l.has(h));if(p.length===0)break;for(const[h,f]of p)u[h]=z(tn(f),{...n,currentPath:[...n.basePath,n.definitionPath,h]},!0)??{},l.add(h)}return u})(),o=s===void 0?a?{...r,[n.definitionPath]:a}:r:n.nameStrategy==="duplicate-ref"?{...r,...a||n.seenRefs.size?{[n.definitionPath]:{...a,...n.seenRefs.size?{[s]:r}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...a,[s]:r}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Fa(t,{parser:e,callback:n}){const s={...t};return Object.defineProperties(s,{$brand:{value:"auto-parseable-tool",enumerable:!1},$parseRaw:{value:e,enumerable:!1},$callback:{value:n,enumerable:!1}}),s}function ja(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return xe(e,[],e)}function fn(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(fn(e))return!0;for(const e of t.anyOf??[])if(fn(e))return!0;return!1}function xe(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ze(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const s=t.$defs;if(ze(s))for(const[h,f]of Object.entries(s))xe(f,[...e,"$defs",h],n);const r=t.definitions;if(ze(r))for(const[h,f]of Object.entries(r))xe(f,[...e,"definitions",h],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const a=t.required??[],o=t.properties;if(ze(o)){for(const[h,f]of Object.entries(o))if(!fn(f)&&!a.includes(h))throw new Error(`Zod field at \`${[...e,"properties",h].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`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([h,f])=>[h,xe(f,[...e,"properties",h],n)]))}const u=t.items;ze(u)&&(t.items=xe(u,[...e,"items"],n));const l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((h,f)=>xe(h,[...e,"anyOf",String(f)],n)));const d=t.allOf;if(Array.isArray(d))if(d.length===1){const h=xe(d[0],[...e,"allOf","0"],n);Object.assign(t,h),delete t.allOf}else t.allOf=d.map((h,f)=>xe(h,[...e,"allOf",String(f)],n));t.default===null&&delete t.default;const p=t.$ref;if(p&&Ua(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);const h=$a(n,p);if(typeof h=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!ze(h))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(h)}`);return Object.assign(t,{...h,...t}),delete t.$ref,xe(t,e,n)}return t}function $a(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let s=t;for(const r of n){if(!ze(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);const i=s[r];if(i===void 0)throw new Error(`Key ${r} not found while resolving ${e}`);s=i}return s}function ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ua(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function vs(t,e){return Ma(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function bs(t){return ja(wi(t,{target:"draft-7"}))}function ws(t){return"_zod"in t}function La(t,e,n){return Ii({type:"json_schema",...n,name:e,strict:!0,schema:ws(t)?bs(t):vs(t,{name:e})},s=>t.parse(JSON.parse(s)))}function Ba(t){return Fa({type:"function",name:t.name,parameters:ws(t.parameters)?bs(t.parameters):vs(t.parameters,{name:t.name}),strict:!0,...t.description?{description:t.description}:void 0},{callback:t.function,parser:e=>t.parameters.parse(JSON.parse(e))})}class Re extends Error{state;constructor(e,n){super(e),this.state=n}}class za extends Re{}class Is extends Re{}class te extends Re{}class J extends Re{}class Ss extends Re{error;constructor(e,n,s){super(e,s),this.error=n}}class Za extends Re{error;constructor(e,n,s){super(e,s),this.error=n}}class Ts extends Re{result;constructor(e,n,s){super(e,s),this.result=n}}class hn extends Re{result;constructor(e,n,s){super(e,s),this.result=n}}function fd(t){return t}function et(t){if(typeof t!="object"||t===null)return;const e=t;return e._zod?.def||e._def||e.def}function Dt(t){const e=et(t);if(!e)return;const n=typeof e.typeName=="string"&&e.typeName||typeof e.type=="string"&&e.type;if(typeof n!="string")return;const s=n.toLowerCase();return s.startsWith("zod")?s.slice(3):s}function Ze(t){return et(t)?Dt(t)==="object":!1}function qa(t){return typeof t=="object"&&t!==null&&"input"in t&&typeof t.input=="string"}const Ja="http://json-schema.org/draft-07/schema#",Ga=new Set(["optional"]),Va=new Set(["brand","branded","catch","default","effects","pipeline","pipe","prefault","readonly","refinement","transform"]),xs={string:{type:"string"},number:{type:"number"},bigint:{type:"integer"},boolean:{type:"boolean"},date:{type:"string",format:"date-time"}};function ks(t){return typeof t=="object"&&t!==null&&t.type==="object"&&"properties"in t&&"additionalProperties"in t}function Ha(t){const e=As(t);if(e)return Array.isArray(e.required)||(e.required=[]),typeof e.additionalProperties>"u"&&(e.additionalProperties=!1),typeof e.$schema!="string"&&(e.$schema=Ja),e}function As(t){const e=ao(t);if(!e)return;const n={},s=[];for(const[r,i]of Object.entries(e)){const{schema:a,optional:o}=Wa(i);if(!a)return;n[r]=a,o||s.push(r)}return{type:"object",properties:n,required:s,additionalProperties:!1}}function Wa(t){let e=mn(t),n=!1;for(;Ga.has(Dt(e)??"");){n=!0;const s=et(e),r=mn(s?.innerType);if(!r||r===e)break;e=r}return{schema:he(e),optional:n}}function he(t){if(t===void 0)return;const e=mn(t),n=Dt(e),s=et(e);if(n){if(n in xs)return xs[n];switch(n){case"object":return As(e);case"array":return Ka(s);case"tuple":return Ya(s);case"union":return Xa(s);case"intersection":return Qa(s);case"literal":return ro(s);case"enum":case"nativeenum":return io(s);case"record":return eo(s);case"map":return to(s);case"set":return no(s);case"nullable":return so(s);default:return}}}function Ka(t){const e=he(Cs(t,"element","items","type"));return e?{type:"array",items:e}:void 0}function Ya(t){const e=Os(t?.items).map(s=>he(s)).filter(Boolean);if(!e.length)return;const n={type:"array",items:e,minItems:e.length};return t?.rest||(n.maxItems=e.length),n}function Xa(t){const e=Os(t?.options??t?.schemas).map(n=>he(n)).filter(Boolean);return e.length?{anyOf:e}:void 0}function Qa(t){const e=he(t?.left),n=he(t?.right);return e&&n?{allOf:[e,n]}:void 0}function eo(t){const e=he(t?.valueType??t?.values);return e?{type:"object",additionalProperties:e}:void 0}function to(t){const e=he(t?.valueType??t?.values);return e?{type:"array",items:e}:void 0}function no(t){const e=he(t?.valueType);return e?{type:"array",items:e,uniqueItems:!0}:void 0}function so(t){const e=he(t?.innerType??t?.type);return e?{anyOf:[e,{type:"null"}]}:void 0}function mn(t){let e=t;for(;Va.has(Dt(e)??"");){const n=et(e),s=n?.innerType??n?.schema??n?.base??n?.type??n?.wrapped??n?.underlying;if(!s||s===e)return e;e=s}return e}function Cs(t,...e){if(t){for(const n of e)if(n in t&&t[n]!==void 0)return t[n]}}function Os(t){return Array.isArray(t)?t:t===void 0?[]:[t]}function ro(t){if(!t)return;const e=Cs(t,"value","literal");if(e!==void 0)return{const:e,type:e===null?"null":typeof e}}function io(t){if(t){if(Array.isArray(t.values))return{enum:t.values};if(Array.isArray(t.options))return{enum:t.options};if(t.values&&typeof t.values=="object")return{enum:Object.values(t.values)};if(t.enum&&typeof t.enum=="object")return{enum:Object.values(t.enum)}}}function ao(t){if(typeof t!="object"||t===null)return;const e=t;if(e.shape&&typeof e.shape=="object")return e.shape;if(typeof e.shape=="function")try{return e.shape()}catch{return}const s=et(e)?.shape;if(s&&typeof s=="object")return s;if(typeof s=="function")try{return s()}catch{return}}const oo=Ba,uo=La;function Es(t){return Ha(t)}function Pt(t){if(t=t.replace(/\s/g,"_"),t=t.replace(/[^a-zA-Z0-9]/g,"_"),t.length===0)throw new Error("Tool name cannot be empty");return t}function gn(t,e){const n=s=>JSON.parse(s);if(Ze(t)){const s=i=>{const a=Es(t);if(a)return{schema:a,parser:u=>t.parse(JSON.parse(u))};const o=i instanceof Error?` Upstream helper error: ${i.message}`:"";throw new J(`Unable to convert the provided Zod schema to JSON Schema. Ensure that the \`zod\` package is available at runtime or provide a JSON schema object instead.${o}`)};let r;try{r=oo({name:e,parameters:t,function:()=>{},description:""})}catch(i){return s(i)}return ks(r.parameters)?{schema:r.parameters,parser:r.$parseRaw}:s()}else if(typeof t=="object"&&t!==null)return{schema:t,parser:n};throw new J("Input type is not a ZodObject or a valid JSON schema")}function Rs(t){if(t==="text")return"text";if(Ze(t)){const e=(s,r)=>{const i=Es(t);if(i)return{type:s?.type??"json_schema",name:s?.name??"output",strict:s?.strict??!1,schema:i};const a=r instanceof Error?` Upstream helper error: ${r.message}`:"";throw new J(`Unable to convert the provided Zod schema to JSON Schema. Ensure that the \`zod\` package is available at runtime or provide a JSON schema object instead.${a}`)};let n;try{n=uo(t,"output")}catch(s){return e(void 0,s)}return ks(n.schema)?{type:n.type,name:n.name,strict:n.strict||!1,schema:n.schema}:e(n)}return t}function co(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Mt={exports:{}},yn,Ns;function lo(){if(Ns)return yn;Ns=1;var t=1e3,e=t*60,n=e*60,s=n*24,r=s*7,i=s*365.25;yn=function(d,p){p=p||{};var h=typeof d;if(h==="string"&&d.length>0)return a(d);if(h==="number"&&isFinite(d))return p.long?u(d):o(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function a(d){if(d=String(d),!(d.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(p){var h=parseFloat(p[1]),f=(p[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return h*i;case"weeks":case"week":case"w":return h*r;case"days":case"day":case"d":return h*s;case"hours":case"hour":case"hrs":case"hr":case"h":return h*n;case"minutes":case"minute":case"mins":case"min":case"m":return h*e;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function o(d){var p=Math.abs(d);return p>=s?Math.round(d/s)+"d":p>=n?Math.round(d/n)+"h":p>=e?Math.round(d/e)+"m":p>=t?Math.round(d/t)+"s":d+"ms"}function u(d){var p=Math.abs(d);return p>=s?l(d,p,s,"day"):p>=n?l(d,p,n,"hour"):p>=e?l(d,p,e,"minute"):p>=t?l(d,p,t,"second"):d+" ms"}function l(d,p,h,f){var m=p>=h*1.5;return Math.round(d/h)+" "+f+(m?"s":"")}return yn}var _n,Ds;function po(){if(Ds)return _n;Ds=1;function t(e){s.debug=s,s.default=s,s.coerce=l,s.disable=o,s.enable=i,s.enabled=u,s.humanize=lo(),s.destroy=d,Object.keys(e).forEach(p=>{s[p]=e[p]}),s.names=[],s.skips=[],s.formatters={};function n(p){let h=0;for(let f=0;f<p.length;f++)h=(h<<5)-h+p.charCodeAt(f),h|=0;return s.colors[Math.abs(h)%s.colors.length]}s.selectColor=n;function s(p){let h,f=null,m,g;function _(...w){if(!_.enabled)return;const b=_,C=Number(new Date),k=C-(h||C);b.diff=k,b.prev=h,b.curr=C,h=C,w[0]=s.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let x=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(F,L)=>{if(F==="%%")return"%";x++;const G=s.formatters[L];if(typeof G=="function"){const Pe=w[x];F=G.call(b,Pe),w.splice(x,1),x--}return F}),s.formatArgs.call(b,w),(b.log||s.log).apply(b,w)}return _.namespace=p,_.useColors=s.useColors(),_.color=s.selectColor(p),_.extend=r,_.destroy=s.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(m!==s.namespaces&&(m=s.namespaces,g=s.enabled(p)),g),set:w=>{f=w}}),typeof s.init=="function"&&s.init(_),_}function r(p,h){const f=s(this.namespace+(typeof h>"u"?":":h)+p);return f.log=this.log,f}function i(p){s.save(p),s.namespaces=p,s.names=[],s.skips=[];const h=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of h)f[0]==="-"?s.skips.push(f.slice(1)):s.names.push(f)}function a(p,h){let f=0,m=0,g=-1,_=0;for(;f<p.length;)if(m<h.length&&(h[m]===p[f]||h[m]==="*"))h[m]==="*"?(g=m,_=f,m++):(f++,m++);else if(g!==-1)m=g+1,_++,f=_;else return!1;for(;m<h.length&&h[m]==="*";)m++;return m===h.length}function o(){const p=[...s.names,...s.skips.map(h=>"-"+h)].join(",");return s.enable(""),p}function u(p){for(const h of s.skips)if(a(p,h))return!1;for(const h of s.names)if(a(p,h))return!0;return!1}function l(p){return p instanceof Error?p.stack||p.message:p}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return s.enable(s.load()),s}return _n=t,_n}var Ps;function fo(){return Ps||(Ps=1,(function(t,e){e.formatArgs=s,e.save=r,e.load=i,e.useColors=n,e.storage=a(),e.destroy=(()=>{let u=!1;return()=>{u||(u=!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"];function n(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let u;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function s(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;u.splice(1,0,l,"color: inherit");let d=0,p=0;u[0].replace(/%[a-zA-Z%]/g,h=>{h!=="%%"&&(d++,h==="%c"&&(p=d))}),u.splice(p,0,l)}e.log=console.debug||console.log||(()=>{});function r(u){try{u?e.storage.setItem("debug",u):e.storage.removeItem("debug")}catch{}}function i(){let u;try{u=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u=process.env.DEBUG),u}function a(){try{return localStorage}catch{}}t.exports=po()(e);const{formatters:o}=t.exports;o.j=function(u){try{return JSON.stringify(u)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(Mt,Mt.exports)),Mt.exports}var ho=fo();const mo=co(ho);function Ms(){return ko()}function Fs(t){const e=Ms();return typeof e<"u"&&(e[t]==="true"||e[t]==="1")}const js={get disabled(){return!0}},$s={get dontLogModelData(){return Fs("OPENAI_AGENTS_DONT_LOG_MODEL_DATA")},get dontLogToolData(){return Fs("OPENAI_AGENTS_DONT_LOG_TOOL_DATA")}},go=$s.dontLogModelData,yo=$s.dontLogToolData;function Us(t="openai-agents"){return{namespace:t,debug:mo(t),error:console.error,warn:console.warn,dontLogModelData:go,dontLogToolData:yo}}const R=Us("openai-agents:core"),Ls=20;function Ne(t){if(t==null)return String(t);if(Bs(t))return pt(new Uint8Array(t));if(dt(t)){const e=t;return pt(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}if(typeof t=="string")return t;if(typeof t=="object")try{return JSON.stringify(t,vo)}catch{return"[object with circular references]"}return String(t)}function Bs(t){if(t instanceof ArrayBuffer)return!0;const e=globalThis.SharedArrayBuffer;return!!(e&&t instanceof e)}function dt(t){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)}function Ft(t){return typeof t=="object"&&t!==null&&t.type==="Buffer"&&Array.isArray(t.data)}function vn(t){const e=globalThis.Buffer;return!!(e&&typeof e.isBuffer=="function"&&e.isBuffer(t))}function pt(t){if(t.length===0)return"[byte array (0 bytes)]";const e=Math.min(t.length,Ls),n=[];for(let i=0;i<e;i++)n.push(_o(t[i]));const s=t.length>Ls?" …":"";return`[byte array ${n.join(" ")}${s} (${t.length} bytes)]`}function _o(t){return`0x${t.toString(16).padStart(2,"0")}`}function vo(t,e){if(Bs(e))return pt(new Uint8Array(e));if(dt(e)){const n=e;return pt(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}return Ft(e)?pt(Uint8Array.from(e.data)):e}function bn(t){return!!t&&typeof t=="object"&&typeof t.create=="function"}const wn=new WeakMap,bo=new WeakMap,jt=new WeakMap;function zs(t){const e=bo.get(t);if(e)return e;if(typeof t.computer=="function"||bn(t.computer))return t.computer}function Zs(t,e,n){let s=jt.get(e);s||(s=new Map,jt.set(e,s)),s.set(t,n)}async function qs(t){const{tool:e,runContext:n}=t,s=e;let r=wn.get(s);r||(r=new WeakMap,wn.set(s,r));const i=r.get(n);if(i)return Zs(e,n,i),i.computer;const a=zs(e),o=a&&bn(a)?a:bn(e.computer)?e.computer:void 0,u=typeof a=="function"?a:o?.create??(typeof e.computer=="function"?e.computer:void 0),l=o?.dispose,d=u&&typeof u=="function"?await u({runContext:n}):e.computer;if(!d)throw new J("The computer tool did not provide a computer instance.");const p={computer:d,dispose:l};return r.set(n,p),Zs(e,n,p),e.computer=d,d}async function Js({runContext:t}){const e=jt.get(t);if(!e)return;jt.delete(t);const n=[];for(const[s,r]of e.entries()){wn.get(s)?.delete(t);const a=zs(s);a&&(s.computer=a),r.dispose&&n.push(async()=>{await r.dispose?.({runContext:t,computer:r.computer})})}for(const s of n)try{await s()}catch(r){R.warn(`Failed to dispose computer for run context: ${r}`)}}function wo(t,e){return`An error occurred while running the tool. Please try again. Error: ${e instanceof Error?e.toString():String(e)}`}function tt(t){const e=t.name?Pt(t.name):Pt(t.execute.name),n=typeof t.errorFunction>"u"?wo:t.errorFunction;if(!e)throw new Error("Tool name cannot be empty. Either name your function or provide a name in the options.");const s=t.strict??!0;if(!s&&Ze(t.parameters))throw new J("Strict mode is required for Zod parameters");const{parser:r,schema:i}=gn(t.parameters,e);async function a(d,p,h){const[f,m]=await en(()=>r(p));if(f!==null)throw R.dontLogToolData?R.debug(`Invalid JSON input for tool ${e}`):R.debug(`Invalid JSON input for tool ${e}: ${p}`),new te("Invalid JSON input for tool");R.dontLogToolData?R.debug(`Invoking tool ${e}`):R.debug(`Invoking tool ${e} with input ${p}`);const g=await t.execute(m,d,h),_=Ne(g);return R.dontLogToolData?R.debug(`Tool ${e} completed`):R.debug(`Tool ${e} returned: ${_}`),g}async function o(d,p,h){return a(d,p,h).catch(f=>{if(n)return yt()?.setError({message:"Error running tool (non-fatal)",data:{tool_name:e,error:f.toString()}}),n(d,f);throw f})}const u=typeof t.needsApproval=="function"?t.needsApproval:async()=>typeof t.needsApproval=="boolean"?t.needsApproval:!1,l=typeof t.isEnabled=="function"?async(d,p)=>{const h=t.isEnabled;return!!await h({runContext:d,agent:p})}:async()=>typeof t.isEnabled=="boolean"?t.isEnabled:!0;return{type:"function",name:e,description:t.description,parameters:i,strict:s,invoke:o,needsApproval:u,isEnabled:l}}y({name:c(),description:c().optional(),inputSchema:y({type:v("object"),properties:q(c(),$()),required:M(c()),additionalProperties:Le()})});const In={},Sn={},Io=({server:t,agent:e})=>t.toolFilter&&typeof t.toolFilter=="function"&&e?`${t.name}:${e.name}`:t.name;async function So({server:t,convertSchemasToStrict:e,runContext:n,agent:s,generateMCPToolCacheKey:r}){const i=(r||Io)({server:t,agent:s,runContext:n});if(t.cacheToolsList&&In[i])return In[i].map(o=>Gs(o,t,e));const a=async o=>{const u=await t.listTools();let l=u;if(n&&s){const p={runContext:n,agent:s,serverName:t.name},h=[];for(const f of u){const m=t.toolFilter;if(m)if(typeof m=="function"){if(!await m(p,f)){R.debug(`MCP Tool (server: ${t.name}, tool: ${f.name}) is blocked by the callable filter.`);continue}}else{const g=m.allowedToolNames??[],_=m.blockedToolNames??[];if(g.length>0||_.length>0){const w=g.length>0?g.includes(f.name):!0,b=_.length>0?_.includes(f.name):!1;if(!w||b){b?R.debug(`MCP Tool (server: ${t.name}, tool: ${f.name}) is blocked by the static filter.`):w||R.debug(`MCP Tool (server: ${t.name}, tool: ${f.name}) is not allowed by the static filter.`);continue}}}h.push(f)}l=h}o&&(o.spanData.result=l.map(p=>p.name));const d=l.map(p=>Gs(p,t,e));return t.cacheToolsList&&(In[i]=l,Sn[t.name]||(Sn[t.name]=new Set),Sn[t.name].add(i)),d};return it()?Fu(a,{data:{server:t.name}}):a()}async function To(t,e,n,s=!1){const r=Array.isArray(t)?{mcpServers:t,runContext:e,agent:n,convertSchemasToStrict:s}:t,{mcpServers:i,convertSchemasToStrict:a=!1,runContext:o,agent:u,generateMCPToolCacheKey:l}=r,d=[],p=new Set;for(const h of i){const f=await So({server:h,convertSchemasToStrict:a,runContext:o,agent:u,generateMCPToolCacheKey:l}),g=[...new Set(f.map(_=>_.name))].filter(_=>p.has(_));if(g.length>0)throw new J(`Duplicate tool names found across MCP servers: ${g.join(", ")}`);for(const _ of f)p.add(_.name),d.push(_)}return d}function Gs(t,e,n){async function s(a,o){let u={};typeof a=="string"&&a?u=JSON.parse(a):typeof a=="object"&&a!=null&&(u=a);const l=yt();l&&(l.spanData.mcp_data={server:e.name});const d=await e.callTool(t.name,u);return d.length===1?d[0]:d}const r={...t.inputSchema,type:t.inputSchema?.type??"object",properties:t.inputSchema?.properties??{},required:t.inputSchema?.required??[],additionalProperties:t.inputSchema?.additionalProperties??!1};if(n||r.additionalProperties===!0)try{const a=xo(r);return tt({name:t.name,description:t.description||"",parameters:a,strict:!0,execute:s})}catch(a){R.warn(`Error converting MCP schema to strict mode: ${a}`)}const i={...r,additionalProperties:!0};return tt({name:t.name,description:t.description||"",parameters:i,strict:!1,execute:s})}function xo(t){const e={...t,additionalProperties:!1};return e.required||(e.required=[]),e}function ko(){return{}}class $t{#e=new EventTarget;#t=new Map;on(e,n){const s=e;let r=this.#t.get(s);r||(r=new Map,this.#t.set(s,r));let i=r.get(n);i||(i=new Set,r.set(n,i));const a=(o=>n(...o.detail??[]));return i.add(a),this.#e.addEventListener(s,a),this}off(e,n){const s=e,r=this.#t.get(s),i=r?.get(n);if(i?.size){for(const a of i)this.#e.removeEventListener(s,a);r?.delete(n),r?.size===0&&this.#t.delete(s)}return this}emit(e,...n){const s=new CustomEvent(e,{detail:n});return this.#e.dispatchEvent(s)}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};return this.on(e,s),this}}const Vs=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)}),Ao=class{constructor(){}pipeTo(e,n){}pipeThrough(e,n){}},Co=globalThis.ReadableStream,Oo=globalThis.TransformStream;class Eo{context=null;constructor(){}run(e,n){return this.context=e,n()}getStore(){return this.context}enterWith(e){this.context=e}}class Ro{constructor(){}setTimeout(e,n){const s=setTimeout(e,n);return s.ref=typeof s.ref=="function"?s.ref:()=>s,s.unref=typeof s.unref=="function"?s.unref:()=>s,s.hasRef=typeof s.hasRef=="function"?s.hasRef:()=>!0,s.refresh=typeof s.refresh=="function"?s.refresh:()=>s,s}clearTimeout(e){window.clearTimeout(e)}}const No=new Ro;class Tn{on(e,n){return this.eventEmitter.on(e,n),this.eventEmitter}off(e,n){return this.eventEmitter.off(e,n),this.eventEmitter}emit(e,...n){return this.eventEmitter.emit(e,...n)}once(e,n){return this.eventEmitter.once(e,n),this.eventEmitter}}class Do extends Tn{eventEmitter=new $t}class Po extends Tn{eventEmitter=new $t}const Mo="OPENAI_DEFAULT_MODEL";function Ut(t){return t.startsWith("gpt-5-chat")?!1:t.startsWith("gpt-5")}function Hs(){return Ut(Ws())}function Ws(){return Ms()[Mo]?.toLowerCase()??"gpt-4.1"}function Fo(t){const e=Ws();return Ut(e)?{reasoning:{effort:"low"},text:{verbosity:"low"}}:{}}function Ks(t){return JSON.stringify({assistant:t.name})}function jo(t){return`transfer_to_${Pt(t.name)}`}function $o(t){return`Handoff to the ${t.name} agent to handle the request. ${t.handoffDescription??""}`}class Ys{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(e,n){this.agentName=e.name,this.onInvokeHandoff=n,this.toolName=jo(e),this.toolDescription=$o(e),this.agent=e}}function Xs(t,e={}){let n;const s=!!e.onHandoff,r=!!e.inputType;if(!(s===r))throw new J("You must provide either both `onHandoff` and `inputType` or neither.");async function a(u,l){if(n){if(!l)throw Ce({message:`Handoff function expected non empty input but got: ${l}`,data:{details:"input is empty"}}),new te("Handoff function expected non empty input");try{const d=await n(l);e.onHandoff&&await e.onHandoff(u,d)}catch(d){throw Ce({message:"Invalid JSON provided",data:{}}),R.dontLogToolData||R.error(`Invalid JSON when parsing: ${l}. Error: ${d}`),new te("Invalid JSON provided")}}else await e.onHandoff?.(u);return t}const o=new Ys(t,a);if(typeof e.isEnabled=="function"){const u=e.isEnabled;o.isEnabled=async({runContext:l,agent:d})=>!!await u({runContext:l,agent:d})}else typeof e.isEnabled=="boolean"&&(o.isEnabled=async()=>e.isEnabled);if(e.inputType){const u=gn(e.inputType,o.toolName);o.inputJsonSchema=u.schema,o.strictJsonSchema=!0,n=u.parser}return e.toolNameOverride&&(o.toolName=e.toolNameOverride),e.toolDescriptionOverride&&(o.toolDescription=e.toolDescriptionOverride),e.inputFilter&&(o.inputFilter=e.inputFilter),o}function Uo(t){return t instanceof Ys?t:Xs(t)}function Qs(t){if(t.type!=="message"||t.role!=="assistant")return;const e=t.content[t.content.length-1];if(e.type==="output_text")return e.text}function Lo(t){return t.output.length===0?"":Qs(t.output[t.output.length-1])||""}const xn=new WeakMap;function Bo(t,e){t&&xn.set(t,e)}function zo(t){const e=xn.get(t);return e&&xn.delete(t),e}const Zo=y({input:c()});class ce extends Do{static create(e){return new ce({...e,handoffs:e.handoffs,outputType:e.outputType,handoffOutputTypeWarningEnabled:!1})}static DEFAULT_MODEL_PLACEHOLDER="";name;instructions;prompt;handoffDescription;handoffs;model;modelSettings;tools;mcpServers;inputGuardrails;outputGuardrails;outputType="text";toolUseBehavior;resetToolChoice;_toolsExplicitlyConfigured;constructor(e){if(super(),typeof e.name!="string"||e.name.trim()==="")throw new J("Agent must have a name.");if(this.name=e.name,this.instructions=e.instructions??ce.DEFAULT_MODEL_PLACEHOLDER,this.prompt=e.prompt,this.handoffDescription=e.handoffDescription??"",this.handoffs=e.handoffs??[],this.model=e.model??"",this.modelSettings=e.modelSettings??Fo(),this.tools=e.tools??[],this._toolsExplicitlyConfigured=e.tools!==void 0,this.mcpServers=e.mcpServers??[],this.inputGuardrails=e.inputGuardrails??[],this.outputGuardrails=e.outputGuardrails??[],e.outputType&&(this.outputType=e.outputType),this.toolUseBehavior=e.toolUseBehavior??"run_llm_again",this.resetToolChoice=e.resetToolChoice??!0,e.model!==void 0&&Hs()&&(typeof e.model!="string"||!Ut(e.model))&&e.modelSettings===void 0&&(this.modelSettings={}),(e.handoffOutputTypeWarningEnabled===void 0||e.handoffOutputTypeWarningEnabled)&&this.handoffs&&this.outputType){const n=new Set([JSON.stringify(this.outputType)]);for(const s of this.handoffs)"outputType"in s&&s.outputType?n.add(JSON.stringify(s.outputType)):"agent"in s&&s.agent.outputType&&n.add(JSON.stringify(s.agent.outputType));n.size>1&&R.warn(`[Agent] Warning: Handoff agents have different output types: ${Array.from(n).join(", ")}. You can make it type-safe by using Agent.create({ ... }) method instead.`)}}get outputSchemaName(){if(this.outputType==="text")return"text";if(Ze(this.outputType))return"ZodOutput";if(typeof this.outputType=="object")return this.outputType.name;throw new Error(`Unknown output type: ${this.outputType}`)}clone(e){return new ce({...this,...e})}asTool(e){const{toolName:n,toolDescription:s,customOutputExtractor:r,needsApproval:i,runConfig:a,runOptions:o,isEnabled:u,onStream:l}=e,d=new Map,p=async m=>{const g=d.get(m.event.type),_=d.get("*"),w=[...l?[l]:[],...g?Array.from(g):[],..._?Array.from(_):[]];await Promise.allSettled(w.map(b=>Promise.resolve().then(()=>b(m))))},f={...tt({name:n??Pt(this.name),description:s??"",parameters:Zo,strict:!0,needsApproval:i,isEnabled:u,execute:async(m,g,_)=>{if(!qa(m))throw new te("Agent tool called with invalid input");const w=new vc(a??{}),b=typeof l=="function"||d.size>0,C=b?await w.run(this,m.input,{context:g,...o??{},stream:!0}):await w.run(this,m.input,{context:g,...o??{}}),k={agent:this,toolCall:_?.toolCall};if(b){const L=C;for await(const G of L)await p({event:G,...k});await L.completed}const x=C,D=typeof this.toolUseBehavior=="object"&&this.toolUseBehavior!==null&&"stopAtToolNames"in this.toolUseBehavior;typeof r!="function"&&D&&R.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 F=typeof r=="function"?await r(x):Lo(x.rawResponses[x.rawResponses.length-1]);return _?.toolCall&&Bo(_.toolCall,x),F}}),on:(m,g)=>{const _=d.get(m)??new Set;return _.add(g),d.set(m,_),f}};return f}async getSystemPrompt(e){return typeof this.instructions=="function"?await this.instructions(e,this):this.instructions}async getPrompt(e){return typeof this.prompt=="function"?await this.prompt(e,this):this.prompt}async getMcpTools(e){return this.mcpServers.length>0?To({mcpServers:this.mcpServers,runContext:e,agent:this,convertSchemasToStrict:!1}):[]}async getAllTools(e){const n=await this.getMcpTools(e),s=[];for(const r of this.tools){if(r.type==="function"){const i=r.isEnabled;if(!(typeof i=="function"?await i(e,this):typeof i=="boolean"?i:!0))continue}s.push(r)}return[...n,...s]}hasExplicitToolConfig(){return this._toolsExplicitlyConfigured}async getEnabledHandoffs(e){const n=this.handoffs?.map(r=>Uo(r))??[],s=[];for(const r of n)await r.isEnabled({runContext:e,agent:this})&&s.push(r);return s}processFinalOutput(e){if(this.outputType==="text")return e;if(typeof this.outputType=="object"){const n=JSON.parse(e);return Ze(this.outputType)?this.outputType.parse(n):n}throw new Error(`Unknown output type: ${this.outputType}`)}toJSON(){return{name:this.name}}}function er({name:t,execute:e,runInParallel:n=!0}){return{type:"input",name:t,runInParallel:n,guardrailFunction:e,async run(s){return{guardrail:{type:"input",name:t},output:await e(s)}}}}function kn({name:t,execute:e}){return{type:"output",name:t,guardrailFunction:e,async run(n){return{guardrail:{type:"output",name:t},agent:n.agent,agentOutput:n.agentOutput,output:await e(n)}}}}function qo(){throw new Error("No default model provider set. Make sure to set a provider using setDefaultModelProvider before calling getDefaultModelProvider or pass an explicit provider.")}const K=y({providerData:q(c(),$()).optional()}),re=K.extend({id:c().optional()}),Jo=K.extend({type:v("refusal"),refusal:c()}),Go=K.extend({type:v("output_text"),text:c()}),An=K.extend({type:v("input_text"),text:c()}),Vo=K.extend({type:v("reasoning_text"),text:c()}),tr=K.extend({type:v("input_image"),image:c().or(y({id:c().describe("OpenAI file ID")})).describe("Either base64 encoded image data, a data URL, or an object with a file ID.").optional(),detail:c().optional()}),nr=K.extend({type:v("input_file"),file:c().describe("Either base64 encoded file data or a publicly accessible file URL").or(y({id:c().describe("OpenAI file ID")})).or(y({url:c().describe("Publicly accessible file URL")})).describe("Contents of the file or an object with a file ID.").optional(),filename:c().optional()}),sr=K.extend({type:v("audio"),audio:c().or(y({id:c()})).describe("Base64 encoded audio data or file id"),format:c().nullable().optional(),transcript:c().nullable().optional()}),Ho=K.extend({type:v("image"),image:c().describe("Base64 encoded image data")}),Wo=K.extend({type:v("text"),text:c()}),Ko=y({data:Te([c(),fs(Uint8Array)]).describe("Base64 image data, or raw bytes that will be base64 encoded automatically."),mediaType:c().optional()}),Yo=y({url:c().describe("Publicly accessible URL pointing to the image content")}),Xo=y({fileId:c().describe("OpenAI file ID referencing uploaded image content")}),Qo=Te([Ko,Yo,Xo]).describe("Inline image data or references to uploaded content."),eu=y({data:Te([c(),fs(Uint8Array)]).describe("Base64 encoded file data, or raw bytes that will be encoded automatically."),mediaType:c().describe("IANA media type describing the file contents"),filename:c().describe("Filename associated with the inline data")}),tu=y({url:c().describe("Publicly accessible URL for the file content"),filename:c().optional()}),nu=y({id:c().describe("OpenAI file ID referencing uploaded content"),filename:c().optional()}),su=Te([c().describe("Existing data URL or base64 string"),eu,tu,nu]).describe("Inline data (with metadata) or references pointing to file contents."),ru=(...t)=>c(),iu=K.extend({type:v("image"),image:c().or(Qo).optional(),detail:ru("low","high","auto").optional()}),au=K.extend({type:v("file"),file:su}),ou=K.extend({type:v("computer_screenshot"),data:c().describe("Base64 encoded image data or URL")}),uu=X("type",[y({type:v("screenshot")}),y({type:v("click"),x:T(),y:T(),button:H(["left","right","wheel","back","forward"])}),y({type:v("double_click"),x:T(),y:T()}),y({type:v("scroll"),x:T(),y:T(),scroll_x:T(),scroll_y:T()}),y({type:v("type"),text:c()}),y({type:v("wait")}),y({type:v("move"),x:T(),y:T()}),y({type:v("keypress"),keys:M(c())}),y({type:v("drag"),path:M(y({x:T(),y:T()}))})]),cu=X("type",[Go,Jo,sr,Ho]),Cn=re.extend({type:v("message").optional()}),Lt=Cn.extend({role:v("assistant"),status:H(["in_progress","completed","incomplete"]),content:M(cu)}),lu=X("type",[An,tr,nr,sr]),rr=Cn.extend({role:v("user"),content:M(lu).or(c())}),ir=Cn.extend({role:v("system"),content:c()});X("role",[ir,Lt,rr]);const ft=re.extend({type:v("hosted_tool_call"),name:c().describe("The name of the hosted tool"),arguments:c().describe("The arguments of the hosted tool call").optional(),status:c().optional(),output:c().optional()}),ht=re.extend({type:v("function_call"),callId:c().describe("The ID of the tool call"),name:c().describe("The name of the function"),status:H(["in_progress","completed","incomplete"]).optional(),arguments:c()}),du=X("type",[Wo,iu,au]),pu=X("type",[An,tr,nr]),Bt=re.extend({type:v("function_call_result"),name:c().describe("The name of the tool"),callId:c().describe("The ID of the tool call"),status:H(["in_progress","completed","incomplete"]),output:Te([c(),du,M(pu)]).describe("Output returned by the tool call. Supports plain strings, legacy ToolOutput items, or structured input_* items.")}),On=re.extend({type:v("computer_call"),callId:c().describe("The ID of the computer call"),status:H(["in_progress","completed","incomplete"]),action:uu}),fu=re.extend({type:v("computer_call_result"),callId:c().describe("The ID of the computer call"),output:ou}),hu=y({commands:M(c()),timeoutMs:T().int().min(0).optional(),maxOutputLength:T().int().min(0).optional()}),zt=re.extend({type:v("shell_call"),callId:c(),status:H(["in_progress","completed","incomplete"]).optional(),action:hu}),mu=X("type",[y({type:v("timeout")}),y({type:v("exit"),exitCode:T().int().nullable()})]),gu=y({stdout:c(),stderr:c(),outcome:mu}).passthrough(),ar=re.extend({type:v("shell_call_output"),callId:c(),maxOutputLength:T().optional(),output:M(gu)}),yu=y({type:v("create_file"),path:c(),diff:c()}),_u=y({type:v("update_file"),path:c(),diff:c()}),vu=y({type:v("delete_file"),path:c()}),bu=X("type",[yu,_u,vu]),Zt=re.extend({type:v("apply_patch_call"),callId:c(),status:H(["in_progress","completed"]),operation:bu}),or=re.extend({type:v("apply_patch_call_output"),callId:c(),status:H(["completed","failed"]),output:c().optional()}),wu=X("type",[On,zt,Zt,ht,ft]),En=K.extend({id:c().optional(),type:v("reasoning"),content:M(An),rawContent:M(Vo).optional()}),ur=re.extend({type:v("compaction"),encrypted_content:c(),id:c().optional(),created_by:c().optional()}),cr=re.extend({type:v("unknown")}),Rn=X("type",[Lt,ft,ht,On,zt,Zt,Bt,ar,or,En,ur,cr]),Iu=Te([rr,Lt,ir,ft,ht,On,zt,Zt,Bt,fu,ar,or,En,ur,cr]),Su=y({inputTokens:T(),outputTokens:T(),totalTokens:T(),inputTokensDetails:q(c(),T()).optional(),outputTokensDetails:q(c(),T()).optional(),endpoint:c().optional()}),Tu=y({requests:T().optional(),inputTokens:T(),outputTokens:T(),totalTokens:T(),inputTokensDetails:Te([q(c(),T()),M(q(c(),T()))]).optional(),outputTokensDetails:Te([q(c(),T()),M(q(c(),T()))]).optional(),requestUsageEntries:M(Su).optional()}),lr=K.extend({type:v("output_text_delta"),delta:c()}),xu=K.extend({type:v("response_started")}),dr=K.extend({type:v("response_done"),response:K.extend({id:c(),usage:Tu,output:M(Rn)})}),ku=K.extend({type:v("model"),event:$().describe("The event from the model")});X("type",[lr,dr,xu,ku]);class mt{inputTokens;outputTokens;totalTokens;inputTokensDetails;outputTokensDetails;endpoint;constructor(e){this.inputTokens=e?.inputTokens??e?.input_tokens??0,this.outputTokens=e?.outputTokens??e?.output_tokens??0,this.totalTokens=e?.totalTokens??e?.total_tokens??this.inputTokens+this.outputTokens;const n=e?.inputTokensDetails??e?.input_tokens_details;this.inputTokensDetails=n||{};const s=e?.outputTokensDetails??e?.output_tokens_details;this.outputTokensDetails=s||{},typeof e?.endpoint<"u"&&(this.endpoint=e.endpoint)}}class gt{requests;inputTokens;outputTokens;totalTokens;inputTokensDetails=[];outputTokensDetails=[];requestUsageEntries;constructor(e){if(typeof e>"u")this.requests=0,this.inputTokens=0,this.outputTokens=0,this.totalTokens=0,this.inputTokensDetails=[],this.outputTokensDetails=[],this.requestUsageEntries=void 0;else{this.requests=e?.requests??1,this.inputTokens=e?.inputTokens??e?.input_tokens??0,this.outputTokens=e?.outputTokens??e?.output_tokens??0,this.totalTokens=e?.totalTokens??e?.total_tokens??this.inputTokens+this.outputTokens;const n=e?.inputTokensDetails??e?.input_tokens_details;Array.isArray(n)?this.inputTokensDetails=n:this.inputTokensDetails=n?[n]:[];const s=e?.outputTokensDetails??e?.output_tokens_details;Array.isArray(s)?this.outputTokensDetails=s:this.outputTokensDetails=s?[s]:[];const r=e?.requestUsageEntries??e?.request_usage_entries,i=Array.isArray(r)?r.map(a=>a instanceof mt?a:new mt(a)):void 0;this.requestUsageEntries=i&&i.length>0?i:void 0}}add(e){this.requests+=e.requests??0,this.inputTokens+=e.inputTokens??0,this.outputTokens+=e.outputTokens??0,this.totalTokens+=e.totalTokens??0,e.inputTokensDetails&&this.inputTokensDetails.push(...e.inputTokensDetails),e.outputTokensDetails&&this.outputTokensDetails.push(...e.outputTokensDetails),Array.isArray(e.requestUsageEntries)&&e.requestUsageEntries.length>0?(this.requestUsageEntries??=[],this.requestUsageEntries.push(...e.requestUsageEntries.map(n=>n instanceof mt?n:new mt(n)))):e.requests===1&&e.totalTokens>0&&(this.requestUsageEntries??=[],this.requestUsageEntries.push(new mt({inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,inputTokensDetails:e.inputTokensDetails?.[0],outputTokensDetails:e.outputTokensDetails?.[0]})))}}class nt{context;usage;#e;constructor(e={}){this.context=e,this.usage=new gt,this.#e=new Map}_rebuildApprovals(e){this.#e=new Map(Object.entries(e))}isToolApproved(e){const{toolName:n,callId:s}=e,r=this.#e.get(n);if(r?.approved===!0&&r.rejected===!0)return R.warn("Tool is permanently approved and rejected at the same time. Approval takes precedence"),!0;if(r?.approved===!0)return!0;if(r?.rejected===!0)return!1;const i=Array.isArray(r?.approved)?r.approved.includes(s):!1,a=Array.isArray(r?.rejected)?r.rejected.includes(s):!1;if(i&&a)return R.warn(`Tool call ${s} is both approved and rejected at the same time. Approval takes precedence`),!0;if(i)return!0;if(a)return!1}approveTool(e,{alwaysApprove:n=!1}={}){const s=e.toolName??e.rawItem.name;if(n){this.#e.set(s,{approved:!0,rejected:[]});return}const r=this.#e.get(s)??{approved:[],rejected:[]};if(Array.isArray(r.approved)){const i="callId"in e.rawItem?e.rawItem.callId:e.rawItem.id;r.approved.push(i)}this.#e.set(s,r)}rejectTool(e,{alwaysReject:n=!1}={}){const s=e.toolName??e.rawItem.name;if(n){this.#e.set(s,{approved:!1,rejected:!0});return}const r=this.#e.get(s)??{approved:[],rejected:[]};if(Array.isArray(r.rejected)){const i="callId"in e.rawItem?e.rawItem.callId:e.rawItem.id;r.rejected.push(i)}this.#e.set(s,r)}toJSON(){return{context:this.context,usage:this.usage,approvals:Object.fromEntries(this.#e.entries())}}}function Au(t){return!!t&&typeof t=="object"&&"environment"in t&&"dimensions"in t}function Cu(t){if(t.type==="function")return{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict};if(t.type==="computer"){if(!Au(t.computer))throw new J("Computer tool is not initialized for serialization. Call resolveComputer({ tool, runContext }) first (for example, when building a model payload outside Runner.run).");return{type:"computer",name:t.name,environment:t.computer.environment,dimensions:t.computer.dimensions}}return t.type==="shell"?{type:"shell",name:t.name}:t.type==="apply_patch"?{type:"apply_patch",name:t.name}:{type:"hosted_tool",name:t.name,providerData:t.providerData}}function Ou(t){return{toolName:t.toolName,toolDescription:t.toolDescription,inputJsonSchema:t.inputJsonSchema,strictJsonSchema:t.strictJsonSchema}}class qe{type="base_item";rawItem;toJSON(){return{type:this.type,rawItem:this.rawItem}}}class qt extends qe{rawItem;agent;type="message_output_item";constructor(e,n){super(),this.rawItem=e,this.agent=n}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}get content(){let e="";for(const n of this.rawItem.content)n.type==="output_text"&&(e+=n.text);return e}}class ke extends qe{rawItem;agent;type="tool_call_item";constructor(e,n){super(),this.rawItem=e,this.agent=n}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class me extends qe{rawItem;agent;output;type="tool_call_output_item";constructor(e,n,s){super(),this.rawItem=e,this.agent=n,this.output=s}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON(),output:Ne(this.output)}}}class Nn extends qe{rawItem;agent;type="reasoning_item";constructor(e,n){super(),this.rawItem=e,this.agent=n}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class Dn extends qe{rawItem;agent;type="handoff_call_item";constructor(e,n){super(),this.rawItem=e,this.agent=n}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON()}}}class Pn extends qe{rawItem;sourceAgent;targetAgent;type="handoff_output_item";constructor(e,n,s){super(),this.rawItem=e,this.sourceAgent=n,this.targetAgent=s}toJSON(){return{...super.toJSON(),sourceAgent:this.sourceAgent.toJSON(),targetAgent:this.targetAgent.toJSON()}}}class ee extends qe{rawItem;agent;toolName;type="tool_approval_item";constructor(e,n,s){super(),this.rawItem=e,this.agent=n,this.toolName=s,this.toolName=s??e.name}get name(){return this.toolName??this.rawItem.name}get arguments(){return"arguments"in this.rawItem?this.rawItem.arguments:void 0}toJSON(){return{...super.toJSON(),agent:this.agent.toJSON(),toolName:this.toolName}}}function Jt(t){return async(e,...n)=>zn(async()=>{const s=t(...n);Bn(s);try{return s.start(),await e(s)}catch(r){throw s.setError({message:r.message,data:r.data}),r}finally{s.end(),_t()}})}function Eu(t,e){return ve().createSpan({...t,data:{type:"agent",name:t?.data?.name??"Agent",...t?.data}},e)}function Ru(t,e){return ve().createSpan({...t,data:{type:"function",input:t?.data?.input??"",output:t?.data?.output??"",...t?.data}},e)}const pr=Jt(Ru);function Nu(t,e){return ve().createSpan({...t,data:{type:"handoff",...t?.data}},e)}const Du=Jt(Nu);function Pu(t,e){return ve().createSpan({...t,data:{type:"guardrail",triggered:!1,...t?.data}},e)}const fr=Jt(Pu);function Mu(t,e){return ve().createSpan({...t,data:{type:"mcp_tools",...t?.data}},e)}const Fu=Jt(Mu);function ie(t){if(t.length===0)return"";const e=typeof globalThis<"u"&&globalThis.Buffer?globalThis.Buffer:void 0;if(e)return e.from(t).toString("base64");let n="";for(let a=0;a<t.length;a+=1)n+=String.fromCharCode(t[a]);if(typeof globalThis.btoa=="function")return globalThis.btoa(n);const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let r="",i=0;for(;i<n.length;){const a=n.charCodeAt(i++),o=n.charCodeAt(i++),u=n.charCodeAt(i++),l=a>>2,d=(a&3)<<4|o>>4,p=isNaN(o)?64:(o&15)<<2|u>>6,h=isNaN(u)?64:u&63;r+=s.charAt(l)+s.charAt(d)+s.charAt(p)+s.charAt(h)}return r}class ju{data;type="raw_model_stream_event";constructor(e){this.data=e}}class $u{name;item;type="run_item_stream_event";constructor(e,n){this.name=e,this.item=n}}class Uu{agent;type="agent_updated_stream_event";constructor(e){this.agent=e}}function Lu(t){return!!t&&typeof t.runCompaction=="function"}function Bu(t){if(!t||typeof t!="object"||!("rawItem"in t))return!1;const e=t.rawItem;if(!e||typeof e!="object")return!1;const n=e.type;return n==="function_call"||n==="hosted_tool_call"}function hr(t){const e=t.rawItem;if(!e)return;if(e.type==="function_call"&&e.callId)return`function_call:${e.callId}`;if("callId"in e&&e.callId)return`${e.type}:${e.callId}`;const n="id"in e?e.id:void 0;if(n)return`${e.type}:${n}`;const s=typeof e.providerData=="object"&&e.providerData?e.providerData:void 0;if(s?.id)return`${e.type}:provider:${s.id}`;const r="agent"in t&&t.agent?t.agent.name:"";try{return`${r}:${e.type}:${JSON.stringify(e)}`}catch{return`${r}:${e.type}`}}function zu(t){try{if(t instanceof de){const e=t.issues[0];if(e){const n=Array.isArray(e.path)?e.path:[],s=n.length>0?n.map(i=>String(i)).join("."):"(root)",r=mr(e.message??"");return`Invalid output type: final assistant output failed schema validation at "${s}" (${r}).`}return"Invalid output type: final assistant output failed schema validation."}if(t instanceof Error&&t.message)return`Invalid output type: ${mr(t.message)}`}catch{}return"Invalid output type: final assistant output did not match the expected schema."}function mr(t,e=160){const n=t.trim();return n?n.length<=e?n:`${n.slice(0,e-3)}...`:"Schema validation failed."}function gr(t,e,n,s){const r=[],i=[],a=[],o=[],u=[],l=[],d=[],p=[],h=new Map(s.map(b=>[b.toolName,b])),f=new Map(n.filter(b=>b.type==="function").map(b=>[b.name,b])),m=n.find(b=>b.type==="computer"),g=n.find(b=>b.type==="shell"),_=n.find(b=>b.type==="apply_patch"),w=new Map(n.filter(b=>b.type==="hosted_tool"&&b.providerData?.type==="mcp").map(b=>b).map(b=>[b.providerData.server_label,b]));for(const b of t.output){if(b.type==="message")b.role==="assistant"&&r.push(new qt(b,e));else if(b.type==="hosted_tool_call"){r.push(new ke(b,e));const k=b.name;if(p.push(k),b.providerData?.type==="mcp_approval_request"||b.name==="mcp_approval_request"){const x=b.providerData,D=x.server_label,F=w.get(D);if(typeof F>"u"){const G=`MCP server (${D}) not found in Agent (${e.name})`;throw Ce({message:G,data:{mcp_server_label:D}}),new te(G)}const L=new ee({type:"hosted_tool_call",name:x.name,id:x.id,status:"in_progress",providerData:x},e);d.push({requestItem:L,mcpTool:F}),F.providerData.on_approval||r.push(L)}}else if(b.type==="reasoning")r.push(new Nn(b,e));else if(b.type==="computer_call"){if(r.push(new ke(b,e)),p.push("computer_use"),!m)throw Ce({message:"Model produced computer action without a computer tool.",data:{agent_name:e.name}}),new te("Model produced computer action without a computer tool.");o.push({toolCall:b,computer:m})}else if(b.type==="shell_call"){if(r.push(new ke(b,e)),p.push("shell"),!g)throw Ce({message:"Model produced shell action without a shell tool.",data:{agent_name:e.name}}),new te("Model produced shell action without a shell tool.");u.push({toolCall:b,shell:g})}else if(b.type==="apply_patch_call"){if(r.push(new ke(b,e)),p.push("apply_patch"),!_)throw Ce({message:"Model produced apply_patch action without an apply_patch tool.",data:{agent_name:e.name}}),new te("Model produced apply_patch action without an apply_patch tool.");l.push({toolCall:b,applyPatch:_})}if(b.type!=="function_call")continue;p.push(b.name);const C=h.get(b.name);if(C)r.push(new Dn(b,e)),i.push({toolCall:b,handoff:C});else{const k=f.get(b.name);if(!k)throw Ce({message:`Tool ${b.name} not found in agent ${e.name}.`,data:{tool_name:b.name,agent_name:e.name}}),new te(`Tool ${b.name} not found in agent ${e.name}.`);r.push(new ke(b,e)),a.push({toolCall:b,tool:k})}}return{newItems:r,handoffs:i,functions:a,computerActions:o,shellActions:u,applyPatchActions:l,mcpApprovalRequests:d,toolsUsed:p,hasToolsOrApprovalsToRun(){return i.length>0||a.length>0||d.length>0||o.length>0||u.length>0||l.length>0}}}const Zu=X("type",[y({type:v("next_step_handoff"),newAgent:$()}),y({type:v("next_step_final_output"),output:c()}),y({type:v("next_step_run_again")}),y({type:v("next_step_interruption"),data:q(c(),$())})]);class ge{originalInput;modelResponse;preStepItems;newStepItems;nextStep;constructor(e,n,s,r,i){this.originalInput=e,this.modelResponse=n,this.preStepItems=s,this.newStepItems=r,this.nextStep=i}get generatedItems(){return this.preStepItems.concat(this.newStepItems)}}function qu(t,e,n){return t.resetToolChoice&&e.hasUsedTools(t)?{...n,toolChoice:void 0}:n}async function yr(t,e,n,s,r,i,a){const o=n.filter(x=>x instanceof ee&&"callId"in x.rawItem&&x.rawItem.type==="function_call").map(x=>x.rawItem.callId),u=a.getInterruptions().filter(Bu);if(u.length>0){const x=new Set;for(const D of u){const F=hr(D);F&&x.add(F)}if(x.size>0){let D=0;for(let F=n.length-1;F>=0;F--){const L=n[F];if(!(L instanceof ee))continue;const G=hr(L);if(G&&x.has(G)&&(D++,x.delete(G),x.size===0))break}D>0&&(a._currentTurnPersistedItemCount=Math.max(0,a._currentTurnPersistedItemCount-D))}}const l=r.functions.filter(x=>o.includes(x.toolCall.callId)),d=await br(t,l,i,a),p=r.computerActions.length>0?await Ir(t,r.computerActions,i,a._context):[],h=new Set(n),f=[],m=new Set,g=x=>{h.has(x)||m.has(x)||(f.push(x),m.add(x))};for(const x of d)g(x.runItem);for(const x of p)g(x);const _=r.mcpApprovalRequests.filter(x=>x.requestItem.type==="tool_approval_item"&&x.requestItem.rawItem.type==="hosted_tool_call"&&x.requestItem.rawItem.providerData?.type==="mcp_approval_request"),w=new Set,b=new Set;for(const x of _){const D=x.requestItem.rawItem;if(D.type!=="hosted_tool_call")continue;const F=D.id,L=a._context.isToolApproved({toolName:D.name,callId:F});if(typeof L<"u"){const G={approve:L,approval_request_id:F,reason:void 0},Pe=new ke({type:"hosted_tool_call",name:"mcp_approval_response",providerData:G},t);g(Pe)}else w.add(x.requestItem),b.add(F),d.push({type:"hosted_mcp_tool_approval",tool:x.mcpTool,runItem:x.requestItem}),g(x.requestItem)}const C=n.filter(x=>{if(!(x instanceof ee))return!0;if(x.rawItem.type==="hosted_tool_call"&&x.rawItem.providerData?.type==="mcp_approval_request"){if(w.has(x))return!0;const D=x.rawItem.id;return D?b.has(D):!1}return!1}),k=await vr({agent:t,runner:i,state:a,functionResults:d,originalInput:e,newResponse:s,preStepItems:C,newItems:f});return k||new ge(e,s,C,f,{type:"next_step_run_again"})}async function _r(t,e,n,s,r,i,a){const o=n,u=new Set(n),l=[],d=k=>{u.has(k)||(l.push(k),u.add(k))};for(const k of r.newItems)d(k);const[p,h,f,m]=await Promise.all([br(t,r.functions,i,a),Ir(t,r.computerActions,i,a._context),Wu(t,r.shellActions,i,a._context),Ku(t,r.applyPatchActions,i,a._context)]);for(const k of p)d(k.runItem);for(const k of h)d(k);for(const k of f)d(k);for(const k of m)d(k);if(r.mcpApprovalRequests.length>0)for(const k of r.mcpApprovalRequests){const x=k.mcpTool.providerData,D=k.requestItem.rawItem.providerData;if(x.on_approval){const F=await x.on_approval(a._context,k.requestItem),L={approve:F.approve,approval_request_id:D.id,reason:F.reason};l.push(new ke({type:"hosted_tool_call",name:"mcp_approval_response",providerData:L},t))}else{l.push(k.requestItem);const F={type:"hosted_mcp_tool_approval",tool:k.mcpTool,runItem:new ee({type:"hosted_tool_call",name:D.name,id:D.id,arguments:D.arguments,status:"in_progress",providerData:D},t)};p.push(F)}}if(r.handoffs.length>0)return await Yu(t,e,o,l,s,r.handoffs,i,a._context);const g=await vr({agent:t,runner:i,state:a,functionResults:p,originalInput:e,newResponse:s,preStepItems:o,newItems:l});if(g)return g;if((r.functions?.length??0)>0||(r.computerActions?.length??0)>0||(r.shellActions?.length??0)>0||(r.applyPatchActions?.length??0)>0||(r.mcpApprovalRequests?.length??0)>0||(r.handoffs?.length??0)>0)return new ge(e,s,o,l,{type:"next_step_run_again"});const w=l.filter(k=>k instanceof qt),b=w.length>0?Qs(w[w.length-1].rawItem):void 0;if(typeof b>"u")return new ge(e,s,o,l,{type:"next_step_run_again"});if(!p.some(k=>k.runItem instanceof ee)){if(t.outputType==="text")return new ge(e,s,o,l,{type:"next_step_final_output",output:b});if(t.outputType!=="text"&&b){const{parser:k}=gn(t.outputType,"final_output"),[x]=await en(()=>k(b));if(x){const D=zu(x);throw Ce({message:D,data:{error:String(x)}}),new te(D)}return new ge(e,s,o,l,{type:"next_step_final_output",output:b})}}return new ge(e,s,o,l,{type:"next_step_run_again"})}async function vr({agent:t,runner:e,state:n,functionResults:s,originalInput:r,newResponse:i,preStepItems:a,newItems:o}){const u=await Xu(t,s,n);return u.isFinalOutput?(e.emit("agent_end",n._context,t,u.finalOutput),t.emit("agent_end",n._context,u.finalOutput),new ge(r,i,a,o,{type:"next_step_final_output",output:u.finalOutput})):u.isInterrupted?new ge(r,i,a,o,{type:"next_step_interruption",data:{interruptions:u.interruptions}}):null}function Gt(t,e){const n=uc(e);if(n){const s=n.map(cc);return{type:"function_call_result",name:t.name,callId:t.callId,status:"completed",output:s}}return{type:"function_call_result",name:t.name,callId:t.callId,status:"completed",output:{type:"text",text:Ne(e)}}}function Ju(t){const e=t.file;if(typeof e=="string"&&e.length>0)return e;const n=Gu(e);if(n)return n;const s=Vu(t);return s||null}function Gu(t){if(!Je(t))return null;if("data"in t&&t.data!==void 0){const n=t.data,s=typeof n=="string"&&n.length>0,r=n instanceof Uint8Array&&n.length>0;return!s&&!r||!Y(t.mediaType)||!Y(t.filename)?null:{data:typeof n=="string"?n:new Uint8Array(n),mediaType:t.mediaType,filename:t.filename}}if(Y(t.url)){const n={url:t.url};return Y(t.filename)&&(n.filename=t.filename),n}const e=Y(t.id)&&t.id||Y(t.fileId)&&t.fileId;if(e){const n={id:e};return Y(t.filename)&&(n.filename=t.filename),n}return null}function Vu(t){const e=typeof t.filename=="string"&&t.filename.length>0?t.filename:void 0,n=typeof t.mediaType=="string"&&t.mediaType.length>0?t.mediaType:void 0;if(typeof t.fileData=="string"&&t.fileData.length>0)return!n||!e?null:{data:t.fileData,mediaType:n,filename:e};if(t.fileData instanceof Uint8Array&&t.fileData.length>0)return!n||!e?null:{data:new Uint8Array(t.fileData),mediaType:n,filename:e};if(typeof t.fileUrl=="string"&&t.fileUrl.length>0){const s={url:t.fileUrl};return e&&(s.filename=e),s}if(typeof t.fileId=="string"&&t.fileId.length>0){const s={id:t.fileId};return e&&(s.filename=e),s}return null}function Je(t){return typeof t=="object"&&t!==null}function Y(t){return typeof t=="string"&&t.length>0}function Vt(t,e){if(typeof t=="string")return e&&!t.startsWith("data:")?st(t,e):t;const n=ie(t);return st(n,e)}function st(t,e){return e?`data:${e};base64,${t}`:t}async function br(t,e,n,s){async function r(i){let a=i.toolCall.arguments;if(i.tool.parameters&&(Ze(i.tool.parameters)?a=i.tool.parameters.parse(a):a=JSON.parse(a)),await i.tool.needsApproval(s._context,a,i.toolCall.callId)){const u=s._context.isToolApproved({toolName:i.tool.name,callId:i.toolCall.callId});if(u===!1)return pr(async l=>{const d="Tool execution was not approved.";return l.setError({message:d,data:{tool_name:i.tool.name,error:`Tool execution for ${i.toolCall.callId} was manually rejected by user.`}}),l.spanData.output=d,{type:"function_output",tool:i.tool,output:d,runItem:new me(Gt(i.toolCall,d),t,d)}},{data:{name:i.tool.name}});if(u!==!0)return{type:"function_approval",tool:i.tool,runItem:new ee(i.toolCall,t)}}return pr(async u=>{n.config.traceIncludeSensitiveData&&(u.spanData.input=i.toolCall.arguments);try{n.emit("agent_tool_start",s._context,t,i.tool,{toolCall:i.toolCall}),t.emit("agent_tool_start",s._context,i.tool,{toolCall:i.toolCall});const l=await i.tool.invoke(s._context,i.toolCall.arguments,{toolCall:i.toolCall}),d=Ne(l);n.emit("agent_tool_end",s._context,t,i.tool,d,{toolCall:i.toolCall}),t.emit("agent_tool_end",s._context,i.tool,d,{toolCall:i.toolCall}),n.config.traceIncludeSensitiveData&&(u.spanData.output=d);const p={type:"function_output",tool:i.tool,output:l,runItem:new me(Gt(i.toolCall,l),t,l)},h=zo(i.toolCall);if(h){p.agentRunResult=h;const f=h.interruptions;f.length>0&&(p.interruptions=f)}return p}catch(l){u.setError({message:"Error running tool",data:{tool_name:i.tool.name,error:String(l)}});const d=String(l);throw n.emit("agent_tool_end",s._context,t,i.tool,d,{toolCall:i.toolCall}),t.emit("agent_tool_end",s._context,i.tool,d,{toolCall:i.toolCall}),l}},{data:{name:i.tool.name}})}try{return await Promise.all(e.map(r))}catch(i){throw new Za(`Failed to run function tools: ${i}`,i,s)}}async function Hu(t,e){const n=e.action;let s;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(r=>[r.x,r.y]));break;case"keypress":await t.keypress(n.keys);break;case"move":await t.move(n.x,n.y);break;case"screenshot":s=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();break}if(typeof s<"u"||typeof t.screenshot=="function"&&(s=await t.screenshot(),typeof s<"u"))return s;throw new Error("Computer does not implement screenshot()")}function wr(t){if(t instanceof Error)return t.message||t.toString();try{return JSON.stringify(t)}catch{return String(t)}}async function Wu(t,e,n,s,r=void 0){const i=r??R,a=[];for(const o of e){const u=o.shell,l=o.toolCall,d=new ee(l,t,u.name);if(await u.needsApproval(s,l.action,l.callId)){if(u.onApproval){const w=await u.onApproval(s,d);w.approve===!0?s.approveTool(d):w.approve===!1&&s.rejectTool(d)}const _=s.isToolApproved({toolName:u.name,callId:l.callId});if(_===!1){const w="Tool execution was not approved.",b={stdout:"",stderr:w,outcome:{type:"exit",exitCode:null}};a.push(new me({type:"shell_call_output",callId:l.callId,output:[b]},t,w));continue}if(_!==!0){a.push(d);continue}}n.emit("agent_tool_start",s,t,u,{toolCall:l}),typeof t.emit=="function"&&t.emit("agent_tool_start",s,u,{toolCall:l});let h;const f={};let m;try{const _=await u.shell.run(l.action);h=_.output??[],_.providerData&&Object.assign(f,_.providerData),typeof _.maxOutputLength=="number"&&(m=_.maxOutputLength)}catch(_){h=[{stdout:"",stderr:wr(_),outcome:{type:"exit",exitCode:null}}],i.error("Failed to execute shell action:",_)}h=h??[],n.emit("agent_tool_end",s,t,u,JSON.stringify(h),{toolCall:l}),typeof t.emit=="function"&&t.emit("agent_tool_end",s,u,JSON.stringify(h),{toolCall:l});const g={type:"shell_call_output",callId:l.callId,output:h??[]};typeof m=="number"&&(g.maxOutputLength=m),Object.keys(f).length>0&&(g.providerData=f),a.push(new me(g,t,g.output))}return a}async function Ku(t,e,n,s,r=void 0){const i=r??R,a=[];for(const o of e){const u=o.applyPatch,l=o.toolCall,d=new ee(l,t,u.name);if(await u.needsApproval(s,l.operation,l.callId)){if(u.onApproval){const _=await u.onApproval(s,d);_.approve===!0?s.approveTool(d):_.approve===!1&&s.rejectTool(d)}const g=s.isToolApproved({toolName:u.name,callId:l.callId});if(g===!1){const _="Tool execution was not approved.";a.push(new me({type:"apply_patch_call_output",callId:l.callId,status:"failed",output:_},t,_));continue}if(g!==!0){a.push(d);continue}}n.emit("agent_tool_start",s,t,u,{toolCall:l}),typeof t.emit=="function"&&t.emit("agent_tool_start",s,u,{toolCall:l});let h="completed",f="";try{let g;switch(l.operation.type){case"create_file":g=await u.editor.createFile(l.operation);break;case"update_file":g=await u.editor.updateFile(l.operation);break;case"delete_file":g=await u.editor.deleteFile(l.operation);break;default:throw new Error("Unsupported apply_patch operation")}g&&typeof g.status=="string"&&(h=g.status),g&&typeof g.output=="string"&&(f=g.output)}catch(g){h="failed",f=wr(g),i.error("Failed to execute apply_patch operation:",g)}n.emit("agent_tool_end",s,t,u,f,{toolCall:l}),typeof t.emit=="function"&&t.emit("agent_tool_end",s,u,f,{toolCall:l});const m={type:"apply_patch_call_output",callId:l.callId,status:h};f&&(m.output=f),a.push(new me(m,t,f))}return a}async function Ir(t,e,n,s,r=void 0){const i=r??R,a=[];for(const o of e){const u=o.toolCall;n.emit("agent_tool_start",s,t,o.computer,{toolCall:u}),typeof t.emit=="function"&&t.emit("agent_tool_start",s,o.computer,{toolCall:u});let l;try{const h=await qs({tool:o.computer,runContext:s});l=await Hu(h,u)}catch(h){i.error("Failed to execute computer action:",h),l=""}n.emit("agent_tool_end",s,t,o.computer,l,{toolCall:u}),typeof t.emit=="function"&&t.emit("agent_tool_end",s,o.computer,l,{toolCall:u});const d=l?`data:image/png;base64,${l}`:"",p={type:"computer_call_result",callId:u.callId,output:{type:"computer_screenshot",data:d}};a.push(new me(p,t,d))}return a}async function Yu(t,e,n,s,r,i,a,o){if(s=[...s],i.length===0)return R.warn("Incorrectly called executeHandoffCalls with no handoffs. This should not happen. Moving on."),new ge(e,r,n,s,{type:"next_step_run_again"});if(i.length>1){const l="Multiple handoffs detected, ignoring this one.";for(let d=1;d<i.length;d++)s.push(new me(Gt(i[d].toolCall,l),t,l))}const u=i[0];return Du(async l=>{const d=u.handoff,p=await d.onInvokeHandoff(o,u.toolCall.arguments);if(l.spanData.to_agent=p.name,i.length>1){const f=i.map(m=>m.handoff.agentName);l.setError({message:"Multiple handoffs requested",data:{requested_agents:f}})}s.push(new Pn(Gt(u.toolCall,Ks(p)),t,p)),a.emit("agent_handoff",o,t,p),t.emit("agent_handoff",o,p);const h=d.inputFilter??a.config.handoffInputFilter;if(h){R.debug("Filtering inputs for handoff"),typeof h!="function"&&l.setError({message:"Invalid input filter",data:{details:"not callable"}});const f={inputHistory:Array.isArray(e)?[...e]:e,preHandoffItems:[...n],newItems:[...s],runContext:o},m=h(f);e=m.inputHistory,n=m.preHandoffItems,s=m.newItems}return new ge(e,r,n,s,{type:"next_step_handoff",newAgent:p})},{data:{from_agent:t.name}})}const Ht={isFinalOutput:!1,isInterrupted:void 0};async function Xu(t,e,n){if(e.length===0)return Ht;const s=[];for(const a of e)if(a.runItem instanceof ee&&s.push(a.runItem),a.type==="function_output"){if(Array.isArray(a.interruptions))s.push(...a.interruptions);else if(a.agentRunResult){const o=a.agentRunResult.interruptions;o.length>0&&s.push(...o)}}if(s.length>0)return{isFinalOutput:!1,isInterrupted:!0,interruptions:s};if(t.toolUseBehavior==="run_llm_again")return Ht;const r=e[0];if(t.toolUseBehavior==="stop_on_first_tool")return r?.type==="function_output"?{isFinalOutput:!0,isInterrupted:void 0,finalOutput:Ne(r.output)}:Ht;const i=t.toolUseBehavior;if(typeof i=="object"){const a=e.find(o=>i.stopAtToolNames.includes(o.tool.name));return a?.type==="function_output"?{isFinalOutput:!0,isInterrupted:void 0,finalOutput:Ne(a.output)}:Ht}if(typeof i=="function")return i(n._context,e);throw new J(`Invalid toolUseBehavior: ${i}`,n)}function Qu(t){if(t instanceof qt)return"message_output_created";if(t instanceof Dn)return"handoff_requested";if(t instanceof Pn)return"handoff_occurred";if(t instanceof ke)return"tool_called";if(t instanceof me)return"tool_output";if(t instanceof Nn)return"reasoning_item_created";if(t instanceof ee)return"tool_approval_requested"}function Sr(t,e){const n=Qu(e);if(!n){R.warn("Unknown item type: ",e);return}t._addItem(new $u(n,e))}function ec(t,e){for(const n of e)Sr(t,n)}function Tr(t,e,n){const s=n?.skipItems;for(const r of e.newStepItems)s?.has(r)||Sr(t,r)}class xr{#e=new Map;addToolUse(e,n){this.#e.set(e,n)}hasUsedTools(e){return this.#e.has(e)}toJSON(){return Object.fromEntries(Array.from(this.#e.entries()).map(([e,n])=>[e.name,n]))}}function tc(t){return typeof t=="string"?[{type:"message",role:"user",content:t}]:[...t]}function kr(t){return t.filter(e=>e.type!=="tool_approval_item").map(e=>e.rawItem)}function Mn(t){return t.map(e=>Fn(jn(e)))}function Fn(t,e={}){if(t==null)return t;const n=nc(t);if(n)return sc(n,e.mediaType);if(Array.isArray(t))return t.map(a=>Fn(a,e));if(!Ar(t))return t;const s=t,r={},i=typeof s.mediaType=="string"&&s.mediaType.length>0?s.mediaType:e.mediaType;for(const[a,o]of Object.entries(s)){const u=a==="data"||a==="fileData"?{mediaType:i}:e;r[a]=Fn(o,u)}return r}function nc(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(dt(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(vn(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(Ft(t))return Uint8Array.from(t.data)}function sc(t,e){const n=ie(t);return`data:${e&&!e.startsWith("data:")?e:"text/plain"};base64,${n}`}function Ar(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function jn(t){if(t==null)return t;if(Array.isArray(t))return t.map(i=>jn(i));if(!Ar(t))return t;const e=t,n={},r=typeof e.type=="string"&&e.type.length>0&&rc(e.type);for(const[i,a]of Object.entries(e))r&&i==="id"||(n[i]=jn(a));return n}function rc(t){switch(t){case"function_call":case"function_call_result":return!0;default:return!1}}async function Wt(t,e,n){if(!Lu(t))return;const s=await t.runCompaction(typeof e>"u"?void 0:{responseId:e});if(!s)return;const r=s.usage;n._context.usage.add(new gt({requests:1,inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,inputTokensDetails:r.inputTokensDetails,outputTokensDetails:r.outputTokensDetails,requestUsageEntries:[r]}))}async function ic(t,e,n){if(!t)return;const s=e??[],r=n.state,i=r._currentTurnPersistedItemCount??0,a=n.newItems.slice(i);process.env.OPENAI_AGENTS__DEBUG_SAVE_SESSION&&console.debug("saveToSession:newRunItems",a.map(d=>d.type));const o=kr(a),u=[...s,...o];if(u.length===0){r._currentTurnPersistedItemCount=i+a.length,await Wt(t,n.lastResponseId,r);return}const l=Mn(u);await t.addItems(l),await Wt(t,n.lastResponseId,r),r._currentTurnPersistedItemCount=i+a.length}async function ac(t,e){if(!t||!e||e.length===0)return;const n=Mn(e);await t.addItems(n)}async function Cr(t,e){if(!t)return;const n=e.state,s=n._currentTurnPersistedItemCount??0,r=e.newItems.slice(s),i=kr(r);if(i.length===0){n._currentTurnPersistedItemCount=s+r.length,await Wt(t,e.lastResponseId,n);return}const a=Mn(i);await t.addItems(a),await Wt(t,e.lastResponseId,n),n._currentTurnPersistedItemCount=s+r.length}async function oc(t,e,n,s){if(!e)return{preparedInput:t,sessionItems:void 0};const r=s?.includeHistoryInPreparedInput??!0,i=s?.preserveDroppedNewItems??!1,a=await e.getItems(),o=Array.isArray(t)?[...t]:tc(t);if(!n)return{preparedInput:r?[...a,...o]:o,sessionItems:o};const u=a.slice(),l=o.slice(),d=await n(a,o);if(!Array.isArray(d))throw new J("Session input callback must return an array of AgentInputItem objects.");const p=Er(u),h=Er(l),f=Rr(u),m=Rr(l),g=[];for(const w of d){const b=$n(w);if(Nr(m,b,w)){Dr(h,b),g.push(w);continue}if(Nr(f,b,w)){Dr(p,b);continue}const C=p.get(b)??0;if(C>0){p.set(b,C-1);continue}const k=h.get(b)??0;if(k>0){h.set(b,k-1),g.push(w);continue}g.push(w)}return{preparedInput:r?d:g.length>0?g:i?l:[],sessionItems:g}}function uc(t){if(Array.isArray(t)){const n=[];for(const s of t){const r=Or(s);if(!r)return null;n.push(r)}return n}const e=Or(t);return e?[e]:null}function Or(t){if(!Je(t))return null;const e=t.type;if(e==="text"&&typeof t.text=="string"){const n={type:"text",text:t.text};return Je(t.providerData)&&(n.providerData=t.providerData),n}if(e==="image"){const n={type:"image"};let s,r;const i=Y(t.mediaType)?t.mediaType:void 0,a=t.image;if(typeof a=="string"&&a.length>0)s=a;else if(Je(a)){const o=a,u=Y(o.mediaType)?o.mediaType:i;if(Y(o.url)?s=o.url:(Y(o.data)||o.data instanceof Uint8Array&&o.data.length>0)&&(s=Vt(o.data,u)),!s){const l=Y(o.fileId)&&o.fileId||Y(o.id)&&o.id||void 0;l&&(r=l)}}if(!s&&typeof t.imageUrl=="string"&&t.imageUrl.length>0&&(s=t.imageUrl),!r&&typeof t.fileId=="string"&&t.fileId.length>0&&(r=t.fileId),!s&&typeof t.data=="string"&&t.data.length>0?s=i?Vt(t.data,i):t.data:!s&&t.data instanceof Uint8Array&&t.data.length>0&&(s=Vt(t.data,i)),typeof t.detail=="string"&&t.detail.length>0&&(n.detail=t.detail),s)n.image=s;else if(r)n.image={fileId:r};else return null;return Je(t.providerData)&&(n.providerData=t.providerData),n}if(e==="file"){const n=Ju(t);if(!n)return null;const s={type:"file",file:n};return Je(t.providerData)&&(s.providerData=t.providerData),s}return null}function cc(t){if(t.type==="text"){const n={type:"input_text",text:t.text};return t.providerData&&(n.providerData=t.providerData),n}if(t.type==="image"){const n={type:"input_image"};if(typeof t.detail=="string"&&t.detail.length>0&&(n.detail=t.detail),typeof t.image=="string"&&t.image.length>0)n.image=t.image;else if(Je(t.image)){const s=t.image,r=Y(s.mediaType)?s.mediaType:void 0;if(Y(s.url))n.image=s.url;else if(Y(s.data))n.image=r&&!s.data.startsWith("data:")?st(s.data,r):s.data;else if(s.data instanceof Uint8Array&&s.data.length>0){const i=ie(s.data);n.image=st(i,r)}else{const i=Y(s.fileId)&&s.fileId||Y(s.id)&&s.id||void 0;i&&(n.image={id:i})}}return t.providerData&&(n.providerData=t.providerData),n}if(t.type==="file"){const n={type:"input_file"},s=t.file;if(typeof s=="string")n.file=s;else if(s&&typeof s=="object"){const r=s;if("data"in r&&r.data){const i=r.mediaType??"text/plain";if(typeof r.data=="string")n.file=st(r.data,i);else{const a=ie(r.data);n.file=st(a,i)}}else if(typeof r.url=="string"&&r.url.length>0)n.file={url:r.url};else{const i=typeof r.id=="string"&&r.id.length>0&&r.id||(typeof r.fileId=="string"&&r.fileId.length>0?r.fileId:void 0);i&&(n.file={id:i})}typeof r.filename=="string"&&r.filename.length>0&&(n.filename=r.filename)}return t.providerData&&(n.providerData=t.providerData),n}return t}function Er(t){const e=new Map;for(const n of t){const s=$n(n);e.set(s,(e.get(s)??0)+1)}return e}function Rr(t){const e=new Map;for(const n of t){const s=$n(n),r=e.get(s);r?r.push(n):e.set(s,[n])}return e}function Nr(t,e,n){const s=t.get(e);if(!s||s.length===0)return!1;const r=s.findIndex(i=>i===n);return r===-1?!1:(s.splice(r,1),s.length===0&&t.delete(e),!0)}function Dr(t,e){const n=(t.get(e)??0)-1;n<=0?t.delete(e):t.set(e,n)}function $n(t){return JSON.stringify(t,lc)}function lc(t,e){if(e instanceof ArrayBuffer)return{__type:"ArrayBuffer",data:ie(new Uint8Array(e))};if(dt(e)){const n=e;return{__type:n.constructor.name,data:ie(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}}if(vn(e)){const n=e;return{__type:"Buffer",data:ie(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}}return Ft(e)?{__type:"Buffer",data:ie(Uint8Array.from(e.data))}:e}const Kt="1.0",dc=v(Kt),ye=y({name:c()}),Pr=y({object:v("trace.span"),id:c(),trace_id:c(),parent_id:c().nullable(),started_at:c().nullable(),ended_at:c().nullable(),error:y({message:c(),data:q(c(),$()).optional()}).nullable(),span_data:q(c(),$())}).extend({previous_span:Qi(()=>Pr).optional()}),pc=y({inputTokens:T(),outputTokens:T(),totalTokens:T(),inputTokensDetails:q(c(),T()).optional(),outputTokensDetails:q(c(),T()).optional(),endpoint:c().optional()}),Mr=y({requests:T(),inputTokens:T(),outputTokens:T(),totalTokens:T(),inputTokensDetails:M(q(c(),T())).optional(),outputTokensDetails:M(q(c(),T())).optional(),requestUsageEntries:M(pc).optional()}),Fr=y({usage:Mr,output:M(Rn),responseId:c().optional(),providerData:q(c(),$()).optional()}),jr=X("type",[y({type:v("message_output_item"),rawItem:Lt,agent:ye}),y({type:v("tool_call_item"),rawItem:wu.or(ft),agent:ye}),y({type:v("tool_call_output_item"),rawItem:Bt,agent:ye,output:c()}),y({type:v("reasoning_item"),rawItem:En,agent:ye}),y({type:v("handoff_call_item"),rawItem:ht,agent:ye}),y({type:v("handoff_output_item"),rawItem:Bt,sourceAgent:ye,targetAgent:ye}),y({type:v("tool_approval_item"),rawItem:ht.or(ft).or(zt).or(Zt),agent:ye,toolName:c().optional()})]),fc=y({object:v("trace"),id:c(),workflow_name:c(),group_id:c().nullable(),metadata:q(c(),$())}),hc=y({newItems:M(jr),toolsUsed:M(c()),handoffs:M(y({toolCall:$(),handoff:$()})),functions:M(y({toolCall:$(),tool:$()})),computerActions:M(y({toolCall:$(),computer:$()})),shellActions:M(y({toolCall:$(),shell:$()})).optional(),applyPatchActions:M(y({toolCall:$(),applyPatch:$()})).optional(),mcpApprovalRequests:M(y({requestItem:y({rawItem:y({type:v("hosted_tool_call"),name:c(),arguments:c().optional(),status:c().optional(),output:c().optional(),providerData:q(c(),$()).nullable().optional()})}),mcpTool:y({type:v("hosted_tool"),name:v("hosted_mcp"),providerData:q(c(),$())})})).optional()}),$r=y({tripwireTriggered:Le(),outputInfo:$()}),mc=y({guardrail:y({type:v("input"),name:c()}),output:$r}),gc=y({guardrail:y({type:v("output"),name:c()}),agentOutput:$(),agent:ye,output:$r}),Ur=y({$schemaVersion:dc,currentTurn:T(),currentAgent:ye,originalInput:c().or(M(Iu)),modelResponses:M(Fr),context:y({usage:Mr,approvals:q(c(),y({approved:M(c()).or(Le()),rejected:M(c()).or(Le())})),context:q(c(),$())}),toolUseTracker:q(c(),M(c())),maxTurns:T(),currentAgentSpan:Pr.nullable().optional(),noActiveAgentRun:Le(),inputGuardrailResults:M(mc),outputGuardrailResults:M(gc),currentStep:Zu.optional(),lastModelResponse:Fr.optional(),generatedItems:M(jr),lastProcessedResponse:hc.optional(),currentTurnPersistedItemCount:T().int().min(0).optional(),trace:fc.nullable()});class Ae{_currentTurn=0;_currentAgent;_originalInput;_modelResponses;_currentAgentSpan;_context;get usage(){return this._context.usage}_toolUseTracker;_generatedItems;_currentTurnPersistedItemCount;_maxTurns;_noActiveAgentRun=!0;_lastTurnResponse;_inputGuardrailResults;_outputGuardrailResults;_currentStep=void 0;_lastProcessedResponse=void 0;_trace=null;constructor(e,n,s,r){this._context=e,this._originalInput=structuredClone(n),this._modelResponses=[],this._currentAgentSpan=void 0,this._currentAgent=s,this._toolUseTracker=new xr,this._generatedItems=[],this._currentTurnPersistedItemCount=0,this._maxTurns=r,this._inputGuardrailResults=[],this._outputGuardrailResults=[],this._trace=it()}get history(){return rt(this._originalInput,this._generatedItems)}getInterruptions(){return this._currentStep?.type!=="next_step_interruption"?[]:this._currentStep.data.interruptions}approve(e,n={alwaysApprove:!1}){this._context.approveTool(e,n)}reject(e,n={alwaysReject:!1}){this._context.rejectTool(e,n)}toJSON(){const e={$schemaVersion:Kt,currentTurn:this._currentTurn,currentAgent:{name:this._currentAgent.name},originalInput:this._originalInput,modelResponses:this._modelResponses.map(s=>({usage:{requests:s.usage.requests,inputTokens:s.usage.inputTokens,outputTokens:s.usage.outputTokens,totalTokens:s.usage.totalTokens,inputTokensDetails:s.usage.inputTokensDetails,outputTokensDetails:s.usage.outputTokensDetails,...s.usage.requestUsageEntries&&s.usage.requestUsageEntries.length>0?{requestUsageEntries:s.usage.requestUsageEntries.map(r=>({inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,inputTokensDetails:r.inputTokensDetails,outputTokensDetails:r.outputTokensDetails,...r.endpoint?{endpoint:r.endpoint}:{}}))}:{}},output:s.output,responseId:s.responseId,providerData:s.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(s=>({...s,agent:s.agent.toJSON()})),currentStep:this._currentStep,lastModelResponse:this._lastTurnResponse,generatedItems:this._generatedItems.map(s=>s.toJSON()),currentTurnPersistedItemCount:this._currentTurnPersistedItemCount,lastProcessedResponse:this._lastProcessedResponse,trace:this._trace?this._trace.toJSON():null},n=Ur.safeParse(e);if(!n.success)throw new za(`Failed to serialize run state. ${n.error.message}`);return n.data}toString(){return JSON.stringify(this.toJSON())}static async fromString(e,n){const[s,r]=await en(()=>JSON.parse(n));if(s)throw new J(`Failed to parse run state. ${s instanceof Error?s.message:String(s)}`);const i=r.$schemaVersion;if(!i)throw new J("Run state is missing schema version");if(i!==Kt)throw new J(`Run state schema version ${i} is not supported. Please use version ${Kt}`);const a=Ur.parse(JSON.parse(n)),o=yc(e),u=new nt(a.context.context);u._rebuildApprovals(a.context.approvals);const l=o.get(a.currentAgent.name);if(!l)throw new J(`Agent ${a.currentAgent.name} not found`);const d=new Ae(u,"",l,a.maxTurns);d._currentTurn=a.currentTurn,d._toolUseTracker=new xr;for(const[p,h]of Object.entries(a.toolUseTracker))d._toolUseTracker.addToolUse(o.get(p),h);if(a.currentAgentSpan){a.trace||R.warn("Trace is not set, skipping tracing setup");const p=ve().createTrace({traceId:a.trace?.id,name:a.trace?.workflow_name,groupId:a.trace?.group_id??void 0,metadata:a.trace?.metadata});d._currentAgentSpan=Lr(p,a.currentAgentSpan),d._trace=p}return d._noActiveAgentRun=a.noActiveAgentRun,d._inputGuardrailResults=a.inputGuardrailResults,d._outputGuardrailResults=a.outputGuardrailResults.map(p=>({...p,agent:o.get(p.agent.name)})),d._currentStep=a.currentStep,d._originalInput=a.originalInput,d._modelResponses=a.modelResponses.map(Br),d._lastTurnResponse=a.lastModelResponse?Br(a.lastModelResponse):void 0,d._generatedItems=a.generatedItems.map(p=>zr(p,o)),d._currentTurnPersistedItemCount=a.currentTurnPersistedItemCount??0,d._lastProcessedResponse=a.lastProcessedResponse?await _c(o,d._currentAgent,d._context,a.lastProcessedResponse):void 0,a.currentStep?.type==="next_step_handoff"&&(d._currentStep={type:"next_step_handoff",newAgent:o.get(a.currentStep.newAgent.name)}),d}}function yc(t){const e=new Map,n=[t];for(;n.length>0;){const s=n.shift();if(!e.has(s.name)){e.set(s.name,s);for(const r of s.handoffs)r instanceof ce?e.has(r.name)||n.push(r):r.agent&&(e.has(r.agent.name)||n.push(r.agent))}}return e}function Lr(t,e){const n=e.span_data,s=e.previous_span?Lr(t,e.previous_span):void 0,r=ve().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 r.previousSpan=s,r}function Br(t){return{usage:new gt(t.usage),output:t.output.map(n=>Rn.parse(n)),responseId:t.responseId,providerData:t.providerData}}function zr(t,e){switch(t.type){case"message_output_item":return new qt(t.rawItem,e.get(t.agent.name));case"tool_call_item":return new ke(t.rawItem,e.get(t.agent.name));case"tool_call_output_item":return new me(t.rawItem,e.get(t.agent.name),t.output);case"reasoning_item":return new Nn(t.rawItem,e.get(t.agent.name));case"handoff_call_item":return new Dn(t.rawItem,e.get(t.agent.name));case"handoff_output_item":return new Pn(t.rawItem,e.get(t.sourceAgent.name),e.get(t.targetAgent.name));case"tool_approval_item":return new ee(t.rawItem,e.get(t.agent.name),t.toolName)}}async function _c(t,e,n,s){const r=await e.getAllTools(n),i=new Map(r.filter(p=>p.type==="function").map(p=>[p.name,p])),a=new Map(r.filter(p=>p.type==="computer").map(p=>[p.name,p])),o=new Map(r.filter(p=>p.type==="shell").map(p=>[p.name,p])),u=new Map(r.filter(p=>p.type==="apply_patch").map(p=>[p.name,p])),l=new Map(e.handoffs.map(p=>p instanceof ce?[p.name,Xs(p)]:[p.toolName,p])),d={newItems:s.newItems.map(p=>zr(p,t)),toolsUsed:s.toolsUsed,handoffs:s.handoffs.map(p=>{if(!l.has(p.handoff.toolName))throw new J(`Handoff ${p.handoff.toolName} not found`);return{toolCall:p.toolCall,handoff:l.get(p.handoff.toolName)}}),functions:await Promise.all(s.functions.map(async p=>{if(!i.has(p.tool.name))throw new J(`Tool ${p.tool.name} not found`);return{toolCall:p.toolCall,tool:i.get(p.tool.name)}})),computerActions:s.computerActions.map(p=>{const h=p.computer.name;if(!a.has(h))throw new J(`Computer tool ${h} not found`);return{toolCall:p.toolCall,computer:a.get(h)}}),shellActions:(s.shellActions??[]).map(p=>{const h=p.shell.name;if(!o.has(h))throw new J(`Shell tool ${h} not found`);return{toolCall:p.toolCall,shell:o.get(h)}}),applyPatchActions:(s.applyPatchActions??[]).map(p=>{const h=p.applyPatch.name;if(!u.has(h))throw new J(`Apply patch tool ${h} not found`);return{toolCall:p.toolCall,applyPatch:u.get(h)}}),mcpApprovalRequests:(s.mcpApprovalRequests??[]).map(p=>({requestItem:new ee(p.requestItem.rawItem,e),mcpTool:p.mcpTool}))};return{...d,hasToolsOrApprovalsToRun(){return d.handoffs.length>0||d.functions.length>0||d.mcpApprovalRequests.length>0||d.computerActions.length>0||d.shellActions.length>0||d.applyPatchActions.length>0}}}class vc extends Po{config;constructor(e={}){super(),this.config={modelProvider:e.modelProvider??qo(),model:e.model,modelSettings:e.modelSettings,handoffInputFilter:e.handoffInputFilter,inputGuardrails:e.inputGuardrails,outputGuardrails:e.outputGuardrails,tracingDisabled:e.tracingDisabled??!1,traceIncludeSensitiveData:e.traceIncludeSensitiveData??!0,workflowName:e.workflowName??"Agent workflow",traceId:e.traceId,groupId:e.groupId,traceMetadata:e.traceMetadata,sessionInputCallback:e.sessionInputCallback,callModelInputFilter:e.callModelInputFilter},this.inputGuardrailDefs=(e.inputGuardrails??[]).map(er),this.outputGuardrailDefs=(e.outputGuardrails??[]).map(kn)}async run(e,n,s={stream:!1,context:void 0}){const r=s??{stream:!1,context:void 0},i=r.sessionInputCallback??this.config.sessionInputCallback,a=r.callModelInputFilter??this.config.callModelInputFilter,o=!!a,u={...r,sessionInputCallback:i,callModelInputFilter:a},l=!!u.conversationId||!!u.previousResponseId,d=u.session,p=n instanceof Ae;let h=d&&p?[]:void 0,f,m=d&&p?new Map:void 0;const g=(k,x)=>{const D=m;if(x!==void 0){if(!D){f=x.map(ne=>structuredClone(ne));return}const L=[],G=new WeakMap;for(const ne of k){if(!ne||typeof ne!="object")continue;const le=(G.get(ne)??0)+1;G.set(ne,le)}const Pe=()=>{for(const[ne,le]of D)if(le>0)return D.set(ne,le-1),!0;return!1};for(let ne=0;ne<x.length;ne++){const le=x[ne];if(!le)continue;let Qt=!1;const We=k[ne];if(We&&typeof We=="object"){const mi=(G.get(We)??0)-1;if(G.set(We,mi),mi>0)continue;const gi=Ge(We),yi=D.get(gi)??0;if(yi>0){D.set(gi,yi-1),L.push(structuredClone(le)),Qt=!0;continue}}const fi=Ge(le),hi=D.get(fi)??0;if(hi>0){D.set(fi,hi-1),L.push(structuredClone(le)),Qt=!0;continue}!We&&Pe()&&(L.push(structuredClone(le)),Qt=!0),!Qt&&!We&&f===void 0&&L.push(structuredClone(le))}(L.length>0||f===void 0)&&(f=L);return}const F=[];if(D)for(const L of k){if(!L)continue;const G=Ge(L),Pe=D.get(G)??0;Pe<=0||(D.set(G,Pe-1),F.push(structuredClone(L)))}else for(const L of k)L&&F.push(structuredClone(L));F.length>0?f=F:f===void 0&&(f=[])},_=()=>{if(f!==void 0)return f;if(!o)return h};let w=n;if(!(w instanceof Ae)){if(d&&Array.isArray(w)&&!i)throw new J("RunConfig.sessionInputCallback must be provided when using session history with list inputs.");const k=await oc(w,d,i,{includeHistoryInPreparedInput:!l,preserveDroppedNewItems:l});if(l&&d){const x=k.sessionItems;x&&x.length>0?w=x:w=k.preparedInput}else w=k.preparedInput;if(d){const x=k.sessionItems??[];h=x.map(D=>structuredClone(D)),m=new Map;for(const D of x){const F=Ge(D);m.set(F,(m.get(F)??0)+1)}}}let b;if(d&&!l){let k=!1;b=async()=>{if(k)return;const x=_();!x||x.length===0||(k=!0,await ac(d,x))}}const C=async()=>{if(u.stream)return await this.#i(e,w,u,b,g);const k=await this.#n(e,w,u,g);return d&&!l&&await ic(d,_(),k),k};return w instanceof Ae&&w._trace?kc(w._trace,async()=>(w._currentAgentSpan&&Bn(w._currentAgentSpan),C())):Ac(async()=>C(),{traceId:this.config.traceId,name:this.config.workflowName,groupId:this.config.groupId,metadata:this.config.traceMetadata})}inputGuardrailDefs;outputGuardrailDefs;#e(e){return this.inputGuardrailDefs.concat(e._currentAgent.inputGuardrails.map(er))}#t(e){const n=this.#e(e),s=[],r=[];for(const i of n)i.runInParallel===!1?s.push(i):r.push(i);return{blocking:s,parallel:r}}async#r(e){const n=e.model!==void 0&&e.model!==ce.DEFAULT_MODEL_PLACEHOLDER||this.config.model!==void 0&&this.config.model!==ce.DEFAULT_MODEL_PLACEHOLDER;let s=bc(e.model,this.config.model);return typeof s=="string"&&(s=await this.config.modelProvider.getModel(s)),{model:s,explictlyModelSet:n}}async#n(e,n,s,r){return zn(async()=>{const i=n instanceof Ae,a=i?n:new Ae(s.context instanceof nt?s.context:new nt(s.context),n,e,s.maxTurns??Zr),o=s.conversationId||s.previousResponseId?new Jr({conversationId:s.conversationId,previousResponseId:s.previousResponseId}):void 0;o&&i&&o.primeFromState({originalInput:a._originalInput,generatedItems:a._generatedItems,modelResponses:a._modelResponses});let u=!1;try{for(;;){if(a._currentStep=a._currentStep??{type:"next_step_run_again"},a._currentStep.type==="next_step_interruption"){if(R.debug("Continuing from interruption"),!a._lastTurnResponse||!a._lastProcessedResponse)throw new J("No model response found in previous state",a);const l=await yr(a._currentAgent,a._originalInput,a._generatedItems,a._lastTurnResponse,a._lastProcessedResponse,this,a);if(a._toolUseTracker.addToolUse(a._currentAgent,a._lastProcessedResponse.toolsUsed),a._originalInput=l.originalInput,a._generatedItems=l.generatedItems,l.nextStep.type==="next_step_interruption")return a._currentStep=l.nextStep,new Ln(a);if(l.nextStep.type==="next_step_run_again"){u=!0,a._currentStep=void 0;continue}u=!1,a._currentStep=l.nextStep}if(a._currentStep.type==="next_step_run_again"){const l=await Gr(a),d=i&&u;if(u=!1,d||(a._currentTurn++,a._currentTurnPersistedItemCount=0),a._currentTurn>a._maxTurns)throw a._currentAgentSpan?.setError({message:"Max turns exceeded",data:{max_turns:a._maxTurns}}),new Is(`Max turns (${a._maxTurns}) exceeded`,a);R.debug(`Running agent ${a._currentAgent.name} (turn ${a._currentTurn})`);let p;if(a._currentTurn===1&&!d){const _=this.#t(a);_.blocking.length>0&&await this.#a(a,_.blocking),_.parallel.length>0&&(p=this.#a(a,_.parallel),p.catch(()=>{}))}const h=o?o.prepareInput(a._originalInput,a._generatedItems):rt(a._originalInput,a._generatedItems);a._noActiveAgentRun&&(a._currentAgent.emit("agent_start",a._context,a._currentAgent,h),this.emit("agent_start",a._context,a._currentAgent,h));const f=await this.#u(a,s,l,h,o,r);a._lastTurnResponse=await f.model.getResponse({systemInstructions:f.modelInput.instructions,prompt:f.prompt,...f.explictlyModelSet?{overridePromptModel:!0}:{},input:f.modelInput.input,previousResponseId:f.previousResponseId,conversationId:f.conversationId,modelSettings:f.modelSettings,tools:f.serializedTools,toolsExplicitlyProvided:f.toolsExplicitlyProvided,outputType:Rs(a._currentAgent.outputType),handoffs:f.serializedHandoffs,tracing:qr(this.config.tracingDisabled,this.config.traceIncludeSensitiveData),signal:s.signal}),a._modelResponses.push(a._lastTurnResponse),a._context.usage.add(a._lastTurnResponse.usage),a._noActiveAgentRun=!1,o?.trackServerItems(a._lastTurnResponse);const m=gr(a._lastTurnResponse,a._currentAgent,f.tools,f.handoffs);a._lastProcessedResponse=m;const g=await _r(a._currentAgent,a._originalInput,a._generatedItems,a._lastTurnResponse,a._lastProcessedResponse,this,a);a._toolUseTracker.addToolUse(a._currentAgent,a._lastProcessedResponse.toolsUsed),a._originalInput=g.originalInput,a._generatedItems=g.generatedItems,g.nextStep.type==="next_step_run_again"&&(a._currentTurnPersistedItemCount=0),a._currentStep=g.nextStep,p&&await p}if(a._currentStep&&a._currentStep.type==="next_step_final_output")return await this.#s(a,a._currentStep.output),this.emit("agent_end",a._context,a._currentAgent,a._currentStep.output),a._currentAgent.emit("agent_end",a._context,a._currentStep.output),new Ln(a);if(a._currentStep&&a._currentStep.type==="next_step_handoff")a._currentAgent=a._currentStep.newAgent,a._currentAgentSpan&&(a._currentAgentSpan.end(),_t(),a._currentAgentSpan=void 0),a._noActiveAgentRun=!0,a._currentStep={type:"next_step_run_again"};else{if(a._currentStep&&a._currentStep.type==="next_step_interruption")return new Ln(a);R.debug("Running next loop")}}}catch(l){throw a._currentAgentSpan&&a._currentAgentSpan.setError({message:"Error in agent run",data:{error:String(l)}}),l}finally{if(a._currentStep?.type!=="next_step_interruption")try{await Js({runContext:a._context})}catch(l){R.warn(`Failed to dispose computers after run: ${l}`)}a._currentAgentSpan&&(a._currentStep?.type!=="next_step_interruption"&&a._currentAgentSpan.end(),_t())}})}async#o(e,n,s,r,i){const a=!!n.conversationId||!!n.previousResponseId,o=a?new Jr({conversationId:n.conversationId,previousResponseId:n.previousResponseId}):void 0;let u=!1,l=!1;const d=async()=>{l||!r||(await r(),l=!0)};o&&s&&o.primeFromState({originalInput:e.state._originalInput,generatedItems:e.state._generatedItems,modelResponses:e.state._modelResponses});let p=!1;try{for(;;){const h=e.state._currentAgent;if(e.state._currentStep=e.state._currentStep??{type:"next_step_run_again"},e.state._currentStep.type==="next_step_interruption"){if(R.debug("Continuing from interruption"),!e.state._lastTurnResponse||!e.state._lastProcessedResponse)throw new J("No model response found in previous state",e.state);const f=await yr(e.state._currentAgent,e.state._originalInput,e.state._generatedItems,e.state._lastTurnResponse,e.state._lastProcessedResponse,this,e.state);if(Tr(e,f),e.state._toolUseTracker.addToolUse(e.state._currentAgent,e.state._lastProcessedResponse.toolsUsed),e.state._originalInput=f.originalInput,e.state._generatedItems=f.generatedItems,f.nextStep.type==="next_step_interruption"){e.state._currentStep=f.nextStep;return}if(f.nextStep.type==="next_step_run_again"){p=!0,e.state._currentStep=void 0;continue}p=!1,e.state._currentStep=f.nextStep}if(e.state._currentStep.type==="next_step_run_again"){const f=await Gr(e.state),m=s&&p;if(p=!1,m||(e.state._currentTurn++,e.state._currentTurnPersistedItemCount=0),e.state._currentTurn>e.state._maxTurns)throw e.state._currentAgentSpan?.setError({message:"Max turns exceeded",data:{max_turns:e.state._maxTurns}}),new Is(`Max turns (${e.state._maxTurns}) exceeded`,e.state);R.debug(`Running agent ${h.name} (turn ${e.state._currentTurn})`);let g,_;if(e.state._currentTurn===1&&!m){const F=this.#t(e.state);F.blocking.length>0&&await this.#a(e.state,F.blocking),F.parallel.length>0&&(_=this.#a(e.state,F.parallel).catch(G=>(g=G,[])))}const w=o?o.prepareInput(e.input,e.newItems):rt(e.input,e.newItems);e.state._noActiveAgentRun&&(h.emit("agent_start",e.state._context,h,w),this.emit("agent_start",e.state._context,h,w));let b;const C=await this.#u(e.state,n,f,w,o,i);if(g)throw g;u=!0,await d();for await(const F of C.model.getStreamedResponse({systemInstructions:C.modelInput.instructions,prompt:C.prompt,...C.explictlyModelSet?{overridePromptModel:!0}:{},input:C.modelInput.input,previousResponseId:C.previousResponseId,conversationId:C.conversationId,modelSettings:C.modelSettings,tools:C.serializedTools,toolsExplicitlyProvided:C.toolsExplicitlyProvided,handoffs:C.serializedHandoffs,outputType:Rs(h.outputType),tracing:qr(this.config.tracingDisabled,this.config.traceIncludeSensitiveData),signal:n.signal})){if(g)throw g;if(F.type==="response_done"){const L=dr.parse(F);b={usage:new gt(L.response.usage),output:L.response.output,responseId:L.response.id},e.state._context.usage.add(b.usage)}if(e.cancelled)return;e._addItem(new ju(F))}if(_&&(await _,g))throw g;if(e.state._noActiveAgentRun=!1,!b)throw new te("Model did not produce a final response!",e.state);e.state._lastTurnResponse=b,o?.trackServerItems(b),e.state._modelResponses.push(e.state._lastTurnResponse);const k=gr(e.state._lastTurnResponse,h,C.tools,C.handoffs);e.state._lastProcessedResponse=k;const x=new Set(k.newItems);x.size>0&&ec(e,k.newItems);const D=await _r(h,e.state._originalInput,e.state._generatedItems,e.state._lastTurnResponse,e.state._lastProcessedResponse,this,e.state);Tr(e,D,{skipItems:x}),e.state._toolUseTracker.addToolUse(h,k.toolsUsed),e.state._originalInput=D.originalInput,e.state._generatedItems=D.generatedItems,D.nextStep.type==="next_step_run_again"&&(e.state._currentTurnPersistedItemCount=0),e.state._currentStep=D.nextStep}if(e.state._currentStep.type==="next_step_final_output"){await this.#s(e.state,e.state._currentStep.output),await d(),a||await Cr(n.session,e),this.emit("agent_end",e.state._context,h,e.state._currentStep.output),h.emit("agent_end",e.state._context,e.state._currentStep.output);return}else if(e.state._currentStep.type==="next_step_interruption"){await d(),a||await Cr(n.session,e);return}else e.state._currentStep.type==="next_step_handoff"?(e.state._currentAgent=e.state._currentStep?.newAgent,e.state._currentAgentSpan&&(e.state._currentAgentSpan.end(),_t()),e.state._currentAgentSpan=void 0,e._addItem(new Uu(e.state._currentAgent)),e.state._noActiveAgentRun=!0,e.state._currentStep={type:"next_step_run_again"}):R.debug("Running next loop")}}catch(h){throw u&&!l&&await d(),e.state._currentAgentSpan&&e.state._currentAgentSpan.setError({message:"Error in agent run",data:{error:String(h)}}),h}finally{if(e.state._currentStep?.type!=="next_step_interruption")try{await Js({runContext:e.state._context})}catch(h){R.warn(`Failed to dispose computers after run: ${h}`)}e.state._currentAgentSpan&&(e.state._currentStep?.type!=="next_step_interruption"&&e.state._currentAgentSpan.end(),_t())}}async#i(e,n,s,r,i){return s=s??{},zn(async()=>{const a=n instanceof Ae,o=a?n:new Ae(s.context instanceof nt?s.context:new nt(s.context),n,e,s.maxTurns??Zr),u=new Wr({signal:s.signal,state:o});u.maxTurns=s.maxTurns??o._maxTurns;const l=this.#o(u,s,a,r,i).then(()=>{u._done()},d=>{u._raiseError(d)});return u._setStreamLoopPromise(l),u})}async#a(e,n){const s=n??this.#e(e);if(s.length>0){const r={agent:e._currentAgent,input:e._originalInput,context:e._context};try{const i=await Promise.all(s.map(async a=>fr(async o=>{const u=await a.run(r);return o.spanData.triggered=u.output.tripwireTriggered,u},{data:{name:a.name}},e._currentAgentSpan)));e._inputGuardrailResults.push(...i);for(const a of i)if(a.output.tripwireTriggered)throw e._currentAgentSpan&&e._currentAgentSpan.setError({message:"Guardrail tripwire triggered",data:{guardrail:a.guardrail.name}}),new Ts(`Input guardrail triggered: ${JSON.stringify(a.output.outputInfo)}`,a,e);return i}catch(i){throw i instanceof Ts?i:(e._currentTurn--,new Ss(`Input guardrail failed to complete: ${i}`,i,e))}}return[]}async#s(e,n){const s=this.outputGuardrailDefs.concat(e._currentAgent.outputGuardrails.map(kn));if(s.length>0){const r=e._currentAgent.processFinalOutput(n),i=rt([],e._generatedItems),a={agent:e._currentAgent,agentOutput:r,context:e._context,details:{modelResponse:e._lastTurnResponse,output:i}};try{const o=await Promise.all(s.map(async u=>fr(async l=>{const d=await u.run(a);return l.spanData.triggered=d.output.tripwireTriggered,d},{data:{name:u.name}},e._currentAgentSpan)));for(const u of o)if(u.output.tripwireTriggered)throw e._currentAgentSpan&&e._currentAgentSpan.setError({message:"Guardrail tripwire triggered",data:{guardrail:u.guardrail.name}}),new hn(`Output guardrail triggered: ${JSON.stringify(u.output.outputInfo)}`,u,e)}catch(o){throw o instanceof hn?o:new Ss(`Output guardrail failed to complete: ${o}`,o,e)}}}async#u(e,n,s,r,i,a){const{model:o,explictlyModelSet:u}=await this.#r(e._currentAgent);let l={...this.config.modelSettings,...e._currentAgent.modelSettings};l=Ic(u,e._currentAgent.modelSettings,o,l),l=qu(e._currentAgent,e._toolUseTracker,l);const d=await e._currentAgent.getSystemPrompt(e._context),p=await e._currentAgent.getPrompt(e._context),{modelInput:h,sourceItems:f,persistedItems:m,filterApplied:g}=await wc(e._currentAgent,n.callModelInputFilter,e._context,r,d);i?.markInputAsSent(f),a?.(f,g?m:void 0);const _=i?.previousResponseId??n.previousResponseId,w=i?.conversationId??n.conversationId;return{...s,model:o,explictlyModelSet:u,modelSettings:l,modelInput:h,prompt:p,previousResponseId:_,conversationId:w}}}function rt(t,e){const n=e.filter(s=>s.type!=="tool_approval_item").map(s=>s.rawItem);return[...Un(t),...n]}const Zr=10;function bc(t,e){return typeof t=="string"&&t!==ce.DEFAULT_MODEL_PLACEHOLDER||t?t:e??t??ce.DEFAULT_MODEL_PLACEHOLDER}function qr(t,e){return t?!1:e?!0:"enabled_without_data"}async function wc(t,e,n,s,r){const i=(f,m)=>f.map(g=>{const _=structuredClone(g);return m&&_&&typeof _=="object"&&m.set(_,g),_}),a=new WeakMap,o=Sc(s),u=[];for(const f of s)f&&typeof f=="object"&&u.push(f);const l=f=>{if(!f||typeof f!="object")return;const m=u.findIndex(g=>g===f);m!==-1&&u.splice(m,1)},d=()=>{const f=u.shift();return f&&Vr(o,f),f},h={input:i(s,a),instructions:r};if(!e)return{modelInput:h,sourceItems:[...s],persistedItems:[],filterApplied:!1};try{const f=await e({modelData:h,agent:t,context:n.context});if(!f||!Array.isArray(f.input))throw new J("callModelInputFilter must return a ModelInputData object with an input array.");const m=f.input.map(_=>{if(!_||typeof _!="object")return;const w=a.get(_);if(w)return l(w),Vr(o,w),w;const b=Ge(_),C=Tc(o,b);if(C)return l(C),C;const k=d();if(k)return k}),g=i(f.input);return{modelInput:{input:g,instructions:typeof f.instructions>"u"?r:f.instructions},sourceItems:m,persistedItems:g.map(_=>structuredClone(_)),filterApplied:!0}}catch(f){throw Ce({message:"Error in callModelInputFilter",data:{error:String(f)}}),f}}class Jr{conversationId;previousResponseId;sentInitialInput=!1;sentItems=new WeakSet;serverItems=new WeakSet;remainingInitialInput=null;constructor({conversationId:e,previousResponseId:n}){this.conversationId=e??void 0,this.previousResponseId=n??void 0}primeFromState({originalInput:e,generatedItems:n,modelResponses:s}){if(this.sentInitialInput)return;for(const i of Un(e))i&&typeof i=="object"&&this.sentItems.add(i);this.sentInitialInput=!0,this.remainingInitialInput=null;const r=s[s.length-1];for(const i of s)for(const a of i.output)a&&typeof a=="object"&&this.serverItems.add(a);!this.conversationId&&r?.responseId&&(this.previousResponseId=r.responseId);for(const i of n){const a=i.rawItem;!a||typeof a!="object"||this.serverItems.has(a)&&this.sentItems.add(a)}}trackServerItems(e){if(e){for(const n of e.output)n&&typeof n=="object"&&this.serverItems.add(n);!this.conversationId&&e.responseId&&(this.previousResponseId=e.responseId)}}prepareInput(e,n){const s=[];if(this.sentInitialInput)this.remainingInitialInput&&this.remainingInitialInput.length>0&&s.push(...this.remainingInitialInput);else{const r=Un(e);s.push(...r),this.remainingInitialInput=r.filter(i=>!!i&&typeof i=="object"),this.sentInitialInput=!0}for(const r of n){if(r.type==="tool_approval_item")continue;const i=r.rawItem;!i||typeof i!="object"||this.sentItems.has(i)||this.serverItems.has(i)||s.push(i)}return s}markInputAsSent(e){if(!e.length)return;const n=new Set;for(const s of e)!s||typeof s!="object"||n.has(s)||(n.add(s),this.sentItems.add(s));!this.remainingInitialInput||this.remainingInitialInput.length===0||(this.remainingInitialInput=this.remainingInitialInput.filter(s=>!n.has(s)),this.remainingInitialInput.length===0&&(this.remainingInitialInput=null))}}function Ic(t,e,n,s){if(Hs()&&t&&(typeof n!="string"||!Ut(n))&&(e.providerData?.reasoning||e.providerData?.text?.verbosity||e.providerData?.reasoning_effort)){const r={...s};return delete r.providerData?.reasoning,delete r.providerData?.text?.verbosity,delete r.providerData?.reasoning_effort,r.reasoning&&(delete r.reasoning.effort,delete r.reasoning.summary),r.text&&delete r.text.verbosity,r}return s}async function Gr(t){const e=await t._currentAgent.getEnabledHandoffs(t._context),n=await t._currentAgent.getAllTools(t._context),s=n.filter(r=>r.type==="computer");if(s.length>0&&await Promise.all(s.map(async r=>{await qs({tool:r,runContext:t._context})})),t._currentAgentSpan)t._currentAgentSpan.spanData.tools=n.map(r=>r.name);else{const r=e.map(i=>i.agentName);t._currentAgentSpan=Eu({data:{name:t._currentAgent.name,handoffs:r,tools:n.map(i=>i.name),output_type:t._currentAgent.outputSchemaName}}),t._currentAgentSpan.start(),Bn(t._currentAgentSpan)}return{handoffs:e,tools:n,serializedHandoffs:e.map(r=>Ou(r)),serializedTools:n.map(r=>Cu(r)),toolsExplicitlyProvided:t._currentAgent.hasExplicitToolConfig()}}function Ge(t){return JSON.stringify(t,xc)}function Sc(t){const e=new Map;for(const n of t){const s=Ge(n),r=e.get(s);r?r.push(n):e.set(s,[n])}return e}function Tc(t,e){const n=t.get(e);if(!n||n.length===0)return;const[s]=n;return n.shift(),n.length===0&&t.delete(e),s}function Vr(t,e){const n=Ge(e),s=t.get(n);if(!s||s.length===0)return;const r=s.findIndex(i=>i===e);r!==-1&&(s.splice(r,1),s.length===0&&t.delete(n))}function xc(t,e){if(e instanceof ArrayBuffer)return{__type:"ArrayBuffer",data:ie(new Uint8Array(e))};if(dt(e)){const n=e;return{__type:n.constructor.name,data:ie(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}}if(vn(e)){const n=e;return{__type:"Buffer",data:ie(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}}return Ft(e)?{__type:"Buffer",data:ie(Uint8Array.from(e.data))}:e}function Un(t){return typeof t=="string"?[{type:"message",role:"user",content:t}]:[...t]}class Hr{state;constructor(e){this.state=e}get history(){return rt(this.input,this.newItems)}get output(){return rt([],this.newItems)}get input(){return this.state._originalInput}get newItems(){return this.state._generatedItems}get rawResponses(){return this.state._modelResponses}get lastResponseId(){const e=this.rawResponses;return e&&e.length>0?e[e.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 this.state._currentStep?.type==="next_step_interruption"?this.state._currentStep.data.interruptions:[]}get finalOutput(){if(this.state._currentStep?.type==="next_step_final_output")return this.state._currentAgent.processFinalOutput(this.state._currentStep.output);R.warn("Accessed finalOutput before agent run is completed.")}}class Ln extends Hr{constructor(e){super(e)}}class Wr extends Hr{get currentAgent(){return this.lastAgent}currentTurn=0;maxTurns;#e=null;#t;#r;#n;#o;#i;#a;#s=!1;#u;constructor(e={}){if(super(e.state),this.#t=e.signal,this.#n=new Co({start:n=>{this.#r=n},cancel:()=>{this.#s=!0}}),this.#o=new Promise((n,s)=>{this.#i=n,this.#a=s}),this.#t){const n=()=>{if(this.#s)return;this.#s=!0;const s=this.#r;if(this.#r=void 0,this.#n.locked){if(s)try{s.close()}catch(r){R.debug(`Failed to close readable stream on abort: ${r}`)}}else this.#n.cancel(this.#t?.reason).catch(r=>{R.debug(`Failed to cancel readable stream on abort: ${r}`)});this.#i?.()};this.#t.aborted?n():this.#t.addEventListener("abort",n,{once:!0})}}_addItem(e){this.cancelled||this.#r?.enqueue(e)}_done(){!this.cancelled&&this.#r&&(this.#r.close(),this.#r=void 0,this.#i?.())}_raiseError(e){!this.cancelled&&this.#r&&(this.#r.error(e),this.#r=void 0),this.#e=e,this.#a?.(e),this.#o.catch(n=>{R.debug(`Resulted in an error: ${n}`)})}get cancelled(){return this.#s}toStream(){return this.#n}get completed(){return this.#o}get error(){return this.#e}toTextStream(e={}){const n=this.#n.pipeThrough(new Oo({transform(s,r){if(s.type==="raw_model_stream_event"&&s.data.type==="output_text_delta"){const i=lr.parse(s.data);r.enqueue(i.delta)}}}));return e.compatibleWithNodeStreams?Ao.fromWeb(n):n}[Symbol.asyncIterator](){return this.#n[Symbol.asyncIterator]()}_setStreamLoopPromise(e){this.#u=e}_getStreamLoopPromise(){return this.#u}}let Kr;function _e(){return Kr??=new Eo,Kr}function it(){const t=_e().getStore();return t?.trace?t.trace:null}function yt(){const t=_e().getStore();return t?.span?t.span:null}function Yr(t){return async()=>{const e=it();if(!e)throw new Error("No trace found");await e.start();const n=await t(e);if(n instanceof Wr){const s=n._getStreamLoopPromise();if(s)return s.finally(()=>e.end()),n}return await e.end(),n}}async function kc(t,e,n={}){const s=typeof t=="string"?ve().createTrace({...n,name:t}):t;return _e().run({trace:s},Yr(e))}async function Ac(t,e={}){if(it())return await t();const s=ve().createTrace(e);return _e().run({trace:s},Yr(t))}function Bn(t){const e=_e().getStore();if(!e)throw new Error("No existing trace found");e.span&&(e.span.previousSpan=e.previousSpan,e.previousSpan=e.span),t.previousSpan=e.span??e.previousSpan,e.span=t,_e().enterWith(e)}function _t(){const t=_e().getStore();t&&(t.span=t.previousSpan,t.previousSpan=t.previousSpan?.previousSpan,_e().enterWith(t))}function Ce(t){const e=yt();e&&e.setError(t)}function Cc(t){return{trace:t.trace?.clone(),span:t.span?.clone(),previousSpan:t.previousSpan?.clone()}}function zn(t){const e=_e().getStore();if(!e)throw new Error("No existing trace found");const n=Cc(e);return _e().run(n,t)}class Oc{async export(e){if(js.disabled){R.debug("Tracing is disabled. Skipping export");return}for(const n of e)n.type==="trace"?console.log(`[Exporter] Export trace traceId=${n.traceId} name=${n.name}${n.groupId?` groupId=${n.groupId}`:""}`):console.log(`[Exporter] Export span: ${JSON.stringify(n)}`)}}class Ec{#e;#t;#r;#n;#o;#i=[];#a;#s=null;#u=!1;#l=null;constructor(e,{maxQueueSize:n=1e3,maxBatchSize:s=100,scheduleDelay:r=5e3,exportTriggerRatio:i=.8}={}){this.#e=n,this.#t=s,this.#r=r,this.#n=n*i,this.#o=e,this.#a=No,R.debug("Automatic trace export loop is not supported in this environment. You need to manually call `getGlobalTraceProvider().forceFlush()` to export traces.")}start(){this.#l=new AbortController,this.#p()}async#c(e){if(this.#i.length+1>this.#e){R.error("Dropping trace because buffer is full");return}this.#i.push(e),this.#i.length>this.#n&&await this.#d()}#p(){this.#s=this.#a.setTimeout(async()=>{await this.#d(),this.#p()},this.#r),typeof this.#s.unref=="function"&&this.#s.unref()}async#d(e=!1){if(this.#i.length!==0){if(R.debug(`Exporting batches. Force: ${e}. Buffer size: ${this.#i.length}`),e||this.#i.length<this.#t){const n=[...this.#i];this.#i=[],this.#u=!0,await this.#o.export(n),this.#u=!1}else if(this.#i.length>0){const n=this.#i.splice(0,this.#t);this.#u=!0,await this.#o.export(n),this.#u=!1}}}async onTraceStart(e){await this.#c(e)}async onTraceEnd(e){}async onSpanStart(e){}async onSpanEnd(e){await this.#c(e)}async shutdown(e){for(e&&this.#a.setTimeout(()=>{this.#l?.abort()},e),R.debug("Shutting down gracefully");this.#i.length>0;){if(R.debug(`Waiting for buffer to empty. Items left: ${this.#i.length}`),this.#u||await this.#d(!0),this.#l?.signal.aborted){R.debug("Timeout reached, force flushing"),await this.#d(!0);break}await new Promise(n=>this.#a.setTimeout(n,500))}R.debug("Buffer empty. Exiting"),this.#a&&this.#s&&this.#a.clearTimeout(this.#s)}async forceFlush(){this.#i.length>0&&await this.#d(!0)}}class Rc{#e=[];start(){for(const e of this.#e)e.start&&e.start()}addTraceProcessor(e){this.#e.push(e)}setProcessors(e){R.debug("Shutting down old processors");for(const n of this.#e)n.shutdown();this.#e=e}async onTraceStart(e){for(const n of this.#e)await n.onTraceStart(e)}async onTraceEnd(e){for(const n of this.#e)await n.onTraceEnd(e)}async onSpanStart(e){for(const n of this.#e)await n.onSpanStart(e)}async onSpanEnd(e){for(const n of this.#e)await n.onSpanEnd(e)}async shutdown(e){for(const n of this.#e)await n.shutdown(e)}async forceFlush(){for(const e of this.#e)await e.forceFlush()}}let Zn=null,qn=null;function Nc(){return Zn||(Zn=new Oc),Zn}function Xr(){return qn||(qn=new Ec(Nc())),qn}function Qr(){return new Date().toISOString()}function ei(){return`trace_${Vs().replace(/-/g,"")}`}function Dc(){return`span_${Vs().replace(/-/g,"").slice(0,24)}`}function Pc(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("_")))}class vt{type="trace.span";#e;#t;#r;#n;#o;#i;#a;#s;#u;constructor(e,n){this.#t=e.traceId,this.#r=e.spanId??Dc(),this.#e=e.data,this.#o=n,this.#n=e.parentId??null,this.#s=e.error??null,this.#i=e.startedAt??null,this.#a=e.endedAt??null}get traceId(){return this.#t}get spanData(){return this.#e}get spanId(){return this.#r}get parentId(){return this.#n}get previousSpan(){return this.#u}set previousSpan(e){this.#u=e}start(){if(this.#i){R.warn("Span already started");return}this.#i=Qr(),this.#o.onSpanStart(this)}end(){if(this.#a){R.debug("Span already finished",this.spanData);return}this.#a=Qr(),this.#o.onSpanEnd(this)}setError(e){this.#s=e}get error(){return this.#s}get startedAt(){return this.#i}get endedAt(){return this.#a}clone(){const e=new vt({traceId:this.traceId,spanId:this.spanId,parentId:this.parentId??void 0,data:this.spanData,startedAt:this.#i??void 0,endedAt:this.#a??void 0,error:this.#s??void 0},this.#o);return e.previousSpan=this.previousSpan?.clone(),e}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:Pc(this.spanData),error:this.error}}}class De extends vt{constructor(e,n){super({traceId:"no-op",spanId:"no-op",data:e},n)}start(){}end(){}setError(){}toJSON(){return null}}class bt{type="trace";traceId;name;groupId=null;metadata;#e;#t;constructor(e,n){this.traceId=e.traceId??ei(),this.name=e.name??"Agent workflow",this.groupId=e.groupId??null,this.metadata=e.metadata??{},this.#e=n??Xr(),this.#t=e.started??!1}async start(){this.#t||(this.#t=!0,await this.#e.onTraceStart(this))}async end(){this.#t&&(this.#t=!1,await this.#e.onTraceEnd(this))}clone(){return new bt({traceId:this.traceId,name:this.name,groupId:this.groupId??void 0,metadata:this.metadata,started:this.#t})}toJSON(){return{object:this.type,id:this.traceId,workflow_name:this.name,group_id:this.groupId,metadata:this.metadata}}}class Jn extends bt{constructor(){super({})}async start(){}async end(){}toJSON(){return null}}class Mc{#e;#t;constructor(){this.#e=new Rc,this.#t=js.disabled,this.#r()}registerProcessor(e){this.#e.addTraceProcessor(e)}setProcessors(e){this.#e.setProcessors(e)}getCurrentTrace(){return it()}getCurrentSpan(){return yt()}setDisabled(e){this.#t=e}startExportLoop(){this.#e.start()}createTrace(e){if(this.#t)return R.debug("Tracing is disabled, Not creating trace %o",e),new Jn;const n=e.traceId??ei(),s=e.name??"Agent workflow";return R.debug("Creating trace %s with name %s",n,s),new bt({...e,name:s,traceId:n},this.#e)}createSpan(e,n){if(this.#t||e.disabled)return R.debug("Tracing is disabled, Not creating span %o",e),new De(e.data,this.#e);let s,r;if(n){if(n instanceof bt){if(n instanceof Jn)return R.debug("Parent trace is no-op, returning NoopSpan"),new De(e.data,this.#e);r=n.traceId}else if(n instanceof vt){if(n instanceof De)return R.debug("Parent span is no-op, returning NoopSpan"),new De(e.data,this.#e);s=n.spanId,r=n.traceId}}else{const i=it(),a=yt();if(!i)return R.error("No active trace. Make sure to start a trace with `withTrace()` first. Returning NoopSpan."),new De(e.data,this.#e);if(a instanceof De||i instanceof Jn)return R.debug(`Parent ${a} or ${i} is no-op, returning NoopSpan`),new De(e.data,this.#e);r=i.traceId,a?(R.debug("Using parent span %s",a.spanId),s=a.spanId):R.debug("No parent span, using current trace %s",i.traceId)}return r?(R.debug(`Creating span ${JSON.stringify(e.data)} with id ${e.spanId??r}`),new vt({...e,traceId:r,parentId:s},this.#e)):(R.error("No traceId found. Make sure to start a trace with `withTrace()` first. Returning NoopSpan."),new De(e.data,this.#e))}async shutdown(e){try{R.debug("Shutting down tracing provider"),await this.#e.shutdown(e)}catch(n){R.error("Error shutting down tracing provider %o",n)}}#r(){if(typeof process<"u"&&typeof process.on=="function"){const e=async()=>{const n=setTimeout(()=>{console.warn("Cleanup timeout, forcing exit"),process.exit(1)},5e3);try{await this.shutdown()}finally{clearTimeout(n)}};process.on("beforeExit",e),process.on("SIGINT",async()=>{await e(),ti("SIGINT")||process.exit(130)}),process.on("SIGTERM",async()=>{await e(),ti("SIGTERM")||process.exit(0)}),process.on("unhandledRejection",async(n,s)=>{R.error("Unhandled rejection",n,s),await e(),Fc("unhandledRejection")||process.exit(1)})}}async forceFlush(){await this.#e.forceFlush()}}function ti(t){return process.listeners(t).length>1}function Fc(t){return process.listeners(t).length>1}let Gn;function ve(){return Gn||(Gn=new Mc),Gn}function jc(t){ve().registerProcessor(t)}jc(Xr());function $c(t){const e=atob(t),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.charCodeAt(r);return s.buffer}function Uc(t){const e=String.fromCharCode(...new Uint8Array(t));return btoa(e)}function Lc(t){if(typeof t>"u"||t===null||typeof t!="object"||!("type"in t)||typeof t.type!="string"||!t.type||t.type!=="message"||!("content"in t)||!Array.isArray(t.content)||t.content.length<1)return;const e=t.content[t.content.length-1];if(!(!("type"in e)||typeof e.type!="string")){if(e.type==="output_text")return typeof e.text=="string"?e.text:void 0;if(e.type==="output_audio")return typeof e.transcript=="string"?e.transcript:void 0}}function Bc(t,e){const n=t.filter(i=>!e.some(a=>a.itemId===i.itemId)),s=e.filter(i=>!t.some(a=>a.itemId===i.itemId)),r=e.filter(i=>t.some(a=>a.itemId===i.itemId&&JSON.stringify(a)!==JSON.stringify(i)));return{removals:n,additions:s,updates:r}}function zc(){return typeof window>"u"?!1:typeof window.RTCPeerConnection<"u"}function ni(t){return t.role==="system"?t:t.role==="assistant"?{...t,content:t.content.map(e=>e.type==="output_audio"?{...e,audio:null}:e)}:t.role==="user"?{...t,content:t.content.map(e=>e.type==="input_audio"?{...e,audio:null}:e)}:t}function Zc(t,e){if(t.role!=="assistant"||e.role!=="assistant")return e;const n=e.content.map((s,r)=>{if(s.type!=="output_audio"||!(typeof s.transcript!="string"||s.transcript.length===0))return s;const a=t.content[r];return a&&a.type==="output_audio"&&typeof a.transcript=="string"&&a.transcript.length>0?{...s,transcript:a.transcript}:s});return{...e,content:n}}function si(t,e,n){if(e.type==="conversation.item.input_audio_transcription.completed")return t.map(i=>{if(i.itemId===e.item_id&&i.type==="message"&&"role"in i&&i.role==="user"){const a=i.content.map(o=>o.type==="input_audio"?{...o,transcript:e.transcript}:o);return{...i,content:a,status:"completed"}}return i});const s=!n&&e.type==="message"?ni(e):e,r=t.findIndex(i=>i.itemId===e.itemId);if(r!==-1){const i=t[r],a=s.type==="message"&&i.type==="message"?Zc(i,s):s;return t.map((o,u)=>u===r?a:!n&&o.type==="message"?ni(o):o)}else if(e.previousItemId){const i=t.findIndex(a=>a.itemId===e.previousItemId);return i!==-1?[...t.slice(0,i+1),s,...t.slice(i+1)]:[...t,s]}else return[...t,s]}const ri={"User-Agent":`Agents/JavaScript ${Me.version}`,"X-OpenAI-Agents-SDK":`openai-agents-sdk.${Me.version}`},qc=`openai-agents-sdk.${Me.version}`;function Jc(t,e){const{name:n,arguments:s,...r}=e;return new ee({type:"hosted_tool_call",name:n,arguments:JSON.stringify(s),status:"in_progress",providerData:{...r}},t)}function ii(t){if(t.rawItem.type!=="function_call"&&t.rawItem.type!=="hosted_tool_call")throw new Error("Invalid approval item type for Realtime MCP approval request");const{name:e,arguments:n,providerData:s}=t.rawItem,{itemId:r,serverLabel:i,...a}=s??{};if(!r||!i)throw new Error("Invalid approval item for Realtime MCP approval request");return{type:"mcp_approval_request",itemId:r,serverLabel:i,...a,name:e,arguments:n?JSON.parse(n):{},approved:null}}class Gc extends ce{voice;constructor(e){super(e),this.voice=e.voice}}function Vc(t){return{debounceTextLength:t.debounceTextLength??100}}function Hc({policyHint:t,...e}){const n=kn(e),s=t??n.name;return{...n,policyHint:s,run:async r=>{const i=await n.run(r);return{...i,guardrail:{...i.guardrail,policyHint:s}}}}}function Wc(t){return`
|
|
8
8
|
⚠️ Your last answer was blocked.
|
|
9
|
-
Failed Guardrail Reason: ${
|
|
10
|
-
Failure Details: ${JSON.stringify(
|
|
9
|
+
Failed Guardrail Reason: ${t.guardrail.policyHint}.
|
|
10
|
+
Failure Details: ${JSON.stringify(t.output.outputInfo??{})}.
|
|
11
11
|
Please 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.
|
|
12
|
-
`.trim()}function Et(n,e){return n in e&&typeof e[n]<"u"}function ep(n){return Et("modalities",n)||Et("inputAudioFormat",n)||Et("outputAudioFormat",n)||Et("inputAudioTranscription",n)||Et("turnDetection",n)||Et("inputAudioNoiseReduction",n)||Et("speed",n)}function tp(n){var e,t,s,r,i,o,a,u;if(!ep(n)){const l=(e=n.audio)!=null&&e.input?{format:Ds(n.audio.input.format),noiseReduction:n.audio.input.noiseReduction??null,transcription:n.audio.input.transcription,turnDetection:n.audio.input.turnDetection}:void 0,p=((s=(t=n.audio)==null?void 0:t.output)==null?void 0:s.voice)??n.voice,d=(r=n.audio)!=null&&r.output||typeof p<"u"?{format:Ds((o=(i=n.audio)==null?void 0:i.output)==null?void 0:o.format),voice:p,speed:(u=(a=n.audio)==null?void 0:a.output)==null?void 0:u.speed}:void 0;return{model:n.model,instructions:n.instructions,toolChoice:n.toolChoice,tools:n.tools,tracing:n.tracing,providerData:n.providerData,prompt:n.prompt,outputModalities:n.outputModalities,audio:l||d?{input:l,output:d}:void 0}}return{model:n.model,instructions:n.instructions,toolChoice:n.toolChoice,tools:n.tools,tracing:n.tracing,providerData:n.providerData,prompt:n.prompt,outputModalities:n.modalities,audio:{input:{format:Ds(n.inputAudioFormat),noiseReduction:n.inputAudioNoiseReduction??null,transcription:n.inputAudioTranscription,turnDetection:n.turnDetection},output:{format:Ds(n.outputAudioFormat),voice:n.voice,speed:n.speed}}}}function Ds(n){if(!n)return;if(typeof n=="object")return n;const e=String(n);return e==="pcm16"?{type:"audio/pcm",rate:24e3}:e==="g711_ulaw"?{type:"audio/pcmu"}:e==="g711_alaw"?{type:"audio/pcma"}:{type:"audio/pcm",rate:24e3}}w({itemId:f()});const so=ve("role",[w({itemId:f(),previousItemId:f().nullable().optional(),type:I("message"),role:I("system"),content:J(w({type:I("input_text"),text:f()}))}),w({itemId:f(),previousItemId:f().nullable().optional(),type:I("message"),role:I("user"),status:pe(["in_progress","completed"]),content:J(w({type:I("input_text"),text:f()}).or(w({type:I("input_audio"),audio:f().nullable().optional(),transcript:f().nullable()})))}),w({itemId:f(),previousItemId:f().nullable().optional(),type:I("message"),role:I("assistant"),status:pe(["in_progress","completed","incomplete"]),content:J(w({type:I("output_text"),text:f()}).or(w({type:I("output_audio"),audio:f().nullable().optional(),transcript:f().nullable().optional()})))})]),ro=w({itemId:f(),previousItemId:f().nullable().optional(),type:I("function_call"),status:pe(["in_progress","completed","incomplete"]),arguments:f(),name:f(),output:f().nullable()}),io=w({itemId:f(),previousItemId:f().nullable().optional(),type:pe(["mcp_call","mcp_tool_call"]),status:pe(["in_progress","completed","incomplete"]),arguments:f(),name:f(),output:f().nullable()}),np=w({itemId:f(),type:I("mcp_approval_request"),serverLabel:f(),name:f(),arguments:se(f(),H()),approved:St().optional().nullable()}),Ne=Fi("openai-agents:realtime"),ao=w({id:f().optional().nullable(),conversation_id:f().optional().nullable(),max_output_tokens:E().or(I("inf")).optional().nullable(),metadata:se(f(),H()).optional().nullable(),output_modalities:J(f()).optional().nullable(),object:I("realtime.response").optional().nullable(),output:J(H()).optional().nullable(),audio:w({output:w({format:H().optional().nullable(),voice:f().optional().nullable()}).optional().nullable()}).optional().nullable(),status:pe(["completed","incomplete","failed","cancelled","in_progress"]).optional().nullable(),status_details:se(f(),H()).optional().nullable(),usage:w({input_tokens:E().optional(),input_token_details:se(f(),H()).optional().nullable(),output_tokens:E().optional(),output_token_details:se(f(),H()).optional().nullable()}).optional().nullable()}),sp=w({id:f().optional(),audio:f().nullable().optional(),text:f().nullable().optional(),transcript:f().nullable().optional(),type:Ye([I("input_text"),I("input_audio"),I("item_reference"),I("output_text"),I("output_audio")])}),Qt=w({id:f().optional(),arguments:f().optional(),call_id:f().optional(),content:J(sp).optional(),name:f().optional(),output:f().nullable().optional(),role:pe(["user","assistant","system"]).optional(),status:pe(["completed","incomplete","in_progress"]).optional(),type:pe(["message","function_call","function_call_output","mcp_list_tools","mcp_tool_call","mcp_call","mcp_approval_request","mcp_approval_response"]).optional(),approval_request_id:f().nullable().optional(),approve:St().nullable().optional(),reason:f().nullable().optional(),server_label:f().optional(),error:H().nullable().optional(),tools:J(w({name:f(),description:f(),input_schema:se(H()).optional()}).passthrough()).optional()}).passthrough(),rp=w({type:I("conversation.created"),event_id:f(),conversation:w({id:f().optional(),object:I("realtime.conversation").optional()})}),ip=w({type:I("conversation.item.added"),event_id:f(),item:Qt,previous_item_id:f().nullable().optional()}),ap=w({type:I("conversation.item.done"),event_id:f(),item:Qt,previous_item_id:f().nullable().optional()}),op=w({type:I("conversation.item.deleted"),event_id:f(),item_id:f()}),up=w({type:I("conversation.item.input_audio_transcription.completed"),event_id:f(),item_id:f(),content_index:E(),transcript:f(),logprobs:J(H()).nullable().optional(),usage:w({type:I("tokens"),total_tokens:E(),input_tokens:E(),input_token_details:w({text_tokens:E(),audio_tokens:E()}),output_tokens:E()}).optional()}),cp=w({type:I("conversation.item.input_audio_transcription.delta"),event_id:f(),item_id:f(),content_index:E().optional(),delta:f().optional(),logprobs:J(H()).nullable().optional()}),lp=w({type:I("conversation.item.input_audio_transcription.failed"),event_id:f(),item_id:f(),content_index:E(),error:w({code:f().optional(),message:f().optional(),param:f().optional(),type:f().optional()})}),dp=w({type:I("conversation.item.retrieved"),event_id:f(),item:Qt}),pp=w({type:I("conversation.item.truncated"),event_id:f(),item_id:f(),audio_end_ms:E(),content_index:E()}),fp=w({type:I("conversation.item.create"),item:Qt,event_id:f().optional(),previous_item_id:f().nullable().optional()}),hp=w({type:I("conversation.item.delete"),item_id:f(),event_id:f().optional()}),mp=w({type:I("conversation.item.retrieve"),item_id:f(),event_id:f().optional()}),gp=w({type:I("conversation.item.truncate"),item_id:f(),audio_end_ms:E(),content_index:E(),event_id:f().optional()}),yp=w({type:I("error"),event_id:f().optional(),error:H().optional()}),_p=w({type:I("input_audio_buffer.cleared"),event_id:f()}),vp=w({type:I("input_audio_buffer.append"),audio:f(),event_id:f().optional()}),bp=w({type:I("input_audio_buffer.clear"),event_id:f().optional()}),wp=w({type:I("input_audio_buffer.commit"),event_id:f().optional()}),Ip=w({type:I("input_audio_buffer.committed"),event_id:f(),item_id:f(),previous_item_id:f().nullable().optional()}),Sp=w({type:I("input_audio_buffer.speech_started"),event_id:f(),item_id:f(),audio_start_ms:E()}),Tp=w({type:I("input_audio_buffer.speech_stopped"),event_id:f(),item_id:f(),audio_end_ms:E()}),xp=w({type:I("output_audio_buffer.started"),event_id:f()}).passthrough(),kp=w({type:I("output_audio_buffer.stopped"),event_id:f()}).passthrough(),Ap=w({type:I("output_audio_buffer.cleared"),event_id:f()}),Cp=w({type:I("rate_limits.updated"),event_id:f(),rate_limits:J(w({limit:E().optional(),name:pe(["requests","tokens"]).optional(),remaining:E().optional(),reset_seconds:E().optional()}))}),Op=w({type:I("response.output_audio.delta"),event_id:f(),item_id:f(),content_index:E(),delta:f(),output_index:E(),response_id:f()}),Ep=w({type:I("response.output_audio.done"),event_id:f(),item_id:f(),content_index:E(),output_index:E(),response_id:f()}),Rp=w({type:I("response.output_audio_transcript.delta"),event_id:f(),item_id:f(),content_index:E(),delta:f(),output_index:E(),response_id:f()}),Np=w({type:I("response.output_audio_transcript.done"),event_id:f(),item_id:f(),content_index:E(),transcript:f(),output_index:E(),response_id:f()}),Pp=w({type:I("response.content_part.added"),event_id:f(),item_id:f(),content_index:E(),output_index:E(),response_id:f(),part:w({audio:f().optional(),text:f().optional(),transcript:f().optional(),type:pe(["text","audio"]).optional()})}),Dp=w({type:I("response.content_part.done"),event_id:f(),item_id:f(),content_index:E(),output_index:E(),response_id:f(),part:w({audio:f().optional(),text:f().optional(),transcript:f().optional(),type:pe(["text","audio"]).optional()})}),Mp=w({type:I("response.created"),event_id:f(),response:ao}),oo=w({type:I("response.done"),event_id:f(),response:ao}),Fp=w({type:I("response.function_call_arguments.delta"),event_id:f(),item_id:f(),call_id:f(),delta:f(),output_index:E(),response_id:f()}),$p=w({type:I("response.function_call_arguments.done"),event_id:f(),item_id:f(),call_id:f(),arguments:f(),output_index:E(),response_id:f()}),jp=w({type:I("response.output_item.added"),event_id:f(),item:Qt,output_index:E(),response_id:f()}),Up=w({type:I("response.output_item.done"),event_id:f(),item:Qt,output_index:E(),response_id:f()}),Lp=w({type:I("response.output_text.delta"),event_id:f(),item_id:f(),content_index:E(),delta:f(),output_index:E(),response_id:f()}),zp=w({type:I("response.output_text.done"),event_id:f(),item_id:f(),content_index:E(),text:f(),output_index:E(),response_id:f()}),Bp=w({type:I("session.created"),event_id:f(),session:H()}),Zp=w({type:I("session.updated"),event_id:f(),session:H()}),qp=w({type:I("response.cancel"),event_id:f().optional(),response_id:f().optional()}),Jp=w({type:I("response.create"),event_id:f().optional(),response:H().optional()}),Gp=w({type:I("session.update"),event_id:f().optional(),session:H()}),Vp=w({type:I("mcp_list_tools.in_progress"),event_id:f().optional(),item_id:f().optional()}),Hp=w({type:I("mcp_list_tools.completed"),event_id:f().optional(),item_id:f().optional()}),Wp=w({type:I("response.mcp_call_arguments.delta"),event_id:f(),response_id:f(),item_id:f(),output_index:E(),delta:f(),obfuscation:f()}),Kp=w({type:I("response.mcp_call_arguments.done"),event_id:f(),response_id:f(),item_id:f(),output_index:E(),arguments:f()}),Yp=w({type:I("response.mcp_call.in_progress"),event_id:f(),output_index:E(),item_id:f()}),Xp=w({type:I("response.mcp_call.completed"),event_id:f(),output_index:E(),item_id:f()}),Qp=w({type:I("mcp_list_tools.failed"),event_id:f().optional(),item_id:f().optional()}),ef=w({type:f(),event_id:f().optional().nullable()}).passthrough(),tf=ve("type",[rp,ip,ap,op,up,cp,lp,dp,pp,yp,_p,Ip,Sp,Tp,xp,kp,Ap,Cp,Op,Ep,Rp,Np,Pp,Dp,Mp,oo,Fp,$p,jp,Up,Lp,zp,Bp,Zp,Vp,Hp,Qp,Wp,Kp,Yp,Xp]);ve("type",[fp,hp,mp,gp,vp,bp,wp,qp,Jp,Gp]);function Er(n){const e=JSON.parse(n.data.toString()),t=tf.safeParse(e);if(!t.success){const s=ef.safeParse(e);return s.success?{data:s.data,isGeneric:!0}:{data:null,isGeneric:!0}}return{data:t.data,isGeneric:!1}}const nf="gpt-realtime",Je={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}}},Dr=class Dr extends or{constructor(t={}){super();R(this,$t);R(this,Bn);R(this,xe,null);R(this,Zn,null);S(this,"eventEmitter",new ws);k(this,$t,t.model??nf),k(this,Bn,t.apiKey)}get currentModel(){return c(this,$t)}set currentModel(t){k(this,$t,t)}_afterAudioDoneEvent(){}get _rawSessionConfig(){return c(this,Zn)??null}async _getApiKey(t){const s=t.apiKey??c(this,Bn);return typeof s=="function"?await s():s}_onMessage(t){var i,o,a,u,l,p;const{data:s,isGeneric:r}=Er(t);if(s!==null&&(this.emit("*",s),!r)){if(s.type==="error"?this.emit("error",{type:"error",error:s}):this.emit(s.type,s),s.type==="response.created"){this.emit("turn_started",{type:"response_started",providerData:{...s}});return}if(s.type==="session.updated"&&k(this,Zn,s.session),s.type==="response.done"){const d=oo.safeParse(s);if(!d.success){Ne.error("Error parsing response done event",d.error);return}const m=((i=d.data.response.usage)==null?void 0:i.input_tokens)??0,g=((o=d.data.response.usage)==null?void 0:o.output_tokens)??0,_=m+g,T=new kn({inputTokens:m,inputTokensDetails:((a=d.data.response.usage)==null?void 0:a.input_token_details)??{},outputTokens:g,outputTokensDetails:((u=d.data.response.usage)==null?void 0:u.output_token_details)??{},totalTokens:_});this.emit("usage_update",T),this.emit("turn_done",{type:"response_done",response:{id:d.data.response.id??"",output:d.data.response.output??[],usage:{inputTokens:m,inputTokensDetails:((l=d.data.response.usage)==null?void 0:l.input_token_details)??{},outputTokens:g,outputTokensDetails:((p=d.data.response.usage)==null?void 0:p.output_token_details)??{},totalTokens:_}}});return}if(s.type==="response.output_audio.done"){this.emit("audio_done"),this._afterAudioDoneEvent();return}if(s.type==="conversation.item.deleted"){this.emit("item_deleted",{itemId:s.item_id});return}if(s.type==="conversation.item.input_audio_transcription.completed"||s.type==="conversation.item.truncated"){this.sendEvent({type:"conversation.item.retrieve",item_id:s.item_id});return}if(s.type==="conversation.item.input_audio_transcription.delta"||s.type==="response.output_text.delta"||s.type==="response.output_audio_transcript.delta"||s.type==="response.function_call_arguments.delta"){s.type==="response.output_audio_transcript.delta"&&this.emit("audio_transcript_delta",{type:"transcript_delta",delta:s.delta,itemId:s.item_id,responseId:s.response_id});return}if(s.type==="conversation.item.added"||s.type==="conversation.item.done"||s.type==="conversation.item.retrieved"){if(s.item.type==="mcp_list_tools"&&s.type==="conversation.item.done"){const d=s.item.server_label??"",m=s.item.tools??[];try{this.emit("mcp_tools_listed",{serverLabel:d,tools:m})}catch(g){Ne.error("Error emitting mcp_tools_listed",g,s.item)}return}if(s.item.type==="message"){const d=s.type==="conversation.item.added"||s.type==="conversation.item.done"?s.previous_item_id:null,m=so.parse({itemId:s.item.id,previousItemId:d,type:s.item.type,role:s.item.role,content:s.item.content,status:s.item.status});this.emit("item_update",m);return}if(s.item.type==="mcp_approval_request"&&s.type==="conversation.item.done"){const d=s.item,m=np.parse({itemId:d.id,type:d.type,serverLabel:d.server_label,name:d.name,arguments:JSON.parse(d.arguments||"{}"),approved:d.approved});this.emit("item_update",m),this.emit("mcp_approval_request",m);return}if(s.item.type==="mcp_tool_call"||s.item.type==="mcp_call"){const d=s.type==="conversation.item.done"?"completed":"in_progress",m=io.parse({itemId:s.item.id,type:s.item.type,status:d,arguments:s.item.arguments,name:s.item.name,output:s.item.output});this.emit("item_update",m),s.type==="conversation.item.done"&&this.emit("mcp_tool_call_completed",m);return}}if(s.type==="response.mcp_call.in_progress"){const d=s;this.sendEvent({type:"conversation.item.retrieve",item_id:d.item_id});return}if(s.type==="mcp_list_tools.in_progress"){const d=s;d.item_id&&this.sendEvent({type:"conversation.item.retrieve",item_id:d.item_id});return}if(s.type==="response.output_item.done"||s.type==="response.output_item.added"){const d=s.item;if(d.type==="function_call"&&d.status==="completed"){const m=ro.parse({itemId:d.id,type:d.type,status:"in_progress",arguments:d.arguments,name:d.name,output:null});this.emit("item_update",m),this.emit("function_call",{id:d.id,type:"function_call",callId:d.call_id??"",arguments:d.arguments??"",name:d.name??""});return}if(d.type==="mcp_tool_call"||d.type==="mcp_call"){const m=io.parse({itemId:d.id,type:d.type,status:s.type==="response.output_item.done"?"completed":"in_progress",arguments:d.arguments,name:d.name,output:d.output});this.emit("item_update",m);return}if(d.type==="message"){const m=so.parse({itemId:s.item.id,type:s.item.type,role:s.item.role,content:s.item.content,status:s.type==="response.output_item.done"?d.status??"completed":d.status??"in_progress"});this.emit("item_update",m);return}}}}_onError(t){this.emit("error",{type:"error",error:t})}_onOpen(){this.emit("connected")}_onClose(){this.emit("disconnected")}sendMessage(t,s,{triggerResponse:r=!0}={}){const i=typeof t=="string"?[{type:"input_text",text:t}]:t.content.map(o=>o.type==="input_image"?{type:"input_image",image_url:o.image,...o.providerData??{}}:o);this.sendEvent({type:"conversation.item.create",item:{type:"message",role:"user",content:i},...s}),r&&this.sendEvent({type:"response.create"})}addImage(t,{triggerResponse:s=!0}={}){this.sendMessage({type:"message",role:"user",content:[{type:"input_image",image:t}]},{},{triggerResponse:s})}_getMergedSessionConfig(t){var i,o,a,u,l,p,d,m,g,_,T,y,h,v,b,N,x,A,D,U,G,L,fe,Y,ce,Me,Ve,Qn;const s=tp(t),r={type:"realtime",instructions:s.instructions,model:s.model??c(this,$t),output_modalities:s.outputModalities??Je.outputModalities,audio:{input:{format:((o=(i=s.audio)==null?void 0:i.input)==null?void 0:o.format)??((u=(a=Je.audio)==null?void 0:a.input)==null?void 0:u.format),noise_reduction:((p=(l=s.audio)==null?void 0:l.input)==null?void 0:p.noiseReduction)??((m=(d=Je.audio)==null?void 0:d.input)==null?void 0:m.noiseReduction),transcription:((_=(g=s.audio)==null?void 0:g.input)==null?void 0:_.transcription)??((y=(T=Je.audio)==null?void 0:T.input)==null?void 0:y.transcription),turn_detection:Dr.buildTurnDetectionConfig((v=(h=s.audio)==null?void 0:h.input)==null?void 0:v.turnDetection)??((N=(b=Je.audio)==null?void 0:b.input)==null?void 0:N.turnDetection)},output:{format:((A=(x=s.audio)==null?void 0:x.output)==null?void 0:A.format)??((U=(D=Je.audio)==null?void 0:D.output)==null?void 0:U.format),voice:((L=(G=s.audio)==null?void 0:G.output)==null?void 0:L.voice)??((Y=(fe=Je.audio)==null?void 0:fe.output)==null?void 0:Y.voice),speed:((Me=(ce=s.audio)==null?void 0:ce.output)==null?void 0:Me.speed)??((Qn=(Ve=Je.audio)==null?void 0:Ve.output)==null?void 0:Qn.speed)}},tool_choice:s.toolChoice??Je.toolChoice,...s.providerData??{}};return s.prompt&&(r.prompt={id:s.prompt.promptId,version:s.prompt.version,variables:s.prompt.variables}),s.tools&&s.tools.length>0&&(r.tools=s.tools.map($s=>({...$s,strict:void 0}))),r}buildSessionPayload(t){return this._getMergedSessionConfig(t)}static buildTurnDetectionConfig(t){if(typeof t>"u")return;const{type:s,createResponse:r,create_response:i,eagerness:o,interruptResponse:a,interrupt_response:u,prefixPaddingMs:l,prefix_padding_ms:p,silenceDurationMs:d,silence_duration_ms:m,threshold:g,idleTimeoutMs:_,idle_timeout_ms:T,...y}=t,h={type:s,create_response:r||i,eagerness:o,interrupt_response:a||u,prefix_padding_ms:l||p,silence_duration_ms:d||m,idle_timeout_ms:_||T,threshold:g,...y};return Object.keys(h).forEach(v=>{h[v]===void 0&&delete h[v]}),Object.keys(h).length>0?h:void 0}set _tracingConfig(t){k(this,xe,t)}_updateTracingConfig(t){var s,r,i;if(typeof c(this,xe)>"u"&&k(this,xe,null),t==="auto"){this.sendEvent({type:"session.update",session:{type:"realtime",tracing:"auto"}});return}if(c(this,xe)!==null&&typeof c(this,xe)!="string"&&typeof t!="string"){Ne.warn("Tracing config is already set, skipping setting it again. This likely happens when you already set a tracing config on session creation.");return}if(t===null){Ne.debug("Disabling tracing for this session. It cannot be turned on for this session from this point on."),this.sendEvent({type:"session.update",session:{type:"realtime",tracing:null}});return}if(c(this,xe)===null||typeof c(this,xe)=="string"){this.sendEvent({type:"session.update",session:{type:"realtime",tracing:t}});return}if((t==null?void 0:t.group_id)!==((s=c(this,xe))==null?void 0:s.group_id)||(t==null?void 0:t.metadata)!==((r=c(this,xe))==null?void 0:r.metadata)||(t==null?void 0:t.workflow_name)!==((i=c(this,xe))==null?void 0:i.workflow_name)){Ne.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(c(this,xe)),JSON.stringify(t));return}this.sendEvent({type:"session.update",session:{type:"realtime",tracing:t}})}updateSessionConfig(t){const s=this.buildSessionPayload(t);this.sendEvent({type:"session.update",session:s})}sendFunctionCallOutput(t,s,r=!0){this.sendEvent({type:"conversation.item.create",item:{type:"function_call_output",output:s,call_id:t.callId}});try{const i=ro.parse({itemId:t.id,previousItemId:t.previousItemId,type:"function_call",status:"completed",arguments:t.arguments,name:t.name,output:s});this.emit("item_update",i)}catch(i){Ne.error("Error parsing tool call item",i,t)}r&&this.sendEvent({type:"response.create"})}sendAudio(t,{commit:s=!1}={}){this.sendEvent({type:"input_audio_buffer.append",audio:Zd(t)}),s&&this.sendEvent({type:"input_audio_buffer.commit"})}resetHistory(t,s){const{removals:r,additions:i,updates:o}=Jd(t,s),a=new Set(r.map(l=>l.itemId));for(const l of o)a.add(l.itemId);if(a.size>0)for(const l of a)this.sendEvent({type:"conversation.item.delete",item_id:l});const u=[...i,...o];for(const l of u)if(l.type==="message"){const p={type:"message",role:l.role,content:l.content,id:l.itemId};l.role!=="system"&&l.status&&(p.status=l.status),this.sendEvent({type:"conversation.item.create",item:p})}else l.type==="function_call"&&Ne.warn("Function calls cannot be manually added or updated at the moment. Ignoring.")}sendMcpResponse(t,s){this.sendEvent({type:"conversation.item.create",previous_item_id:t.itemId,item:{type:"mcp_approval_response",approval_request_id:t.itemId,approve:s}})}};$t=new WeakMap,Bn=new WeakMap,xe=new WeakMap,Zn=new WeakMap;let Ms=Dr;class sf extends Ms{constructor(t={}){if(typeof RTCPeerConnection>"u")throw new Error("WebRTC is not supported in this environment");super(t);S(this,"options");R(this,qn);R(this,ie,{status:"disconnected",peerConnection:void 0,dataChannel:void 0,callId:void 0});R(this,Jn);R(this,yt,!1);R(this,Gn,!1);this.options=t,k(this,qn,t.baseUrl??"https://api.openai.com/v1/realtime/calls"),k(this,Jn,t.useInsecureApiKey??!1)}get callId(){return c(this,ie).callId}get status(){return c(this,ie).status}get connectionState(){return c(this,ie)}get muted(){return c(this,Gn)}async connect(t){if(c(this,ie).status==="connected")return;c(this,ie).status==="connecting"&&Ne.warn("Realtime connection already in progress. Please await original promise");const s=t.model??this.currentModel;this.currentModel=s;const r=t.url??c(this,qn),i=await this._getApiKey(t),o=typeof i=="string"&&i.startsWith("ek_");if(!c(this,Jn)&&!o)throw new re("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(a,u)=>{var l,p;try{const d={...t.initialSessionConfig||{},model:this.currentModel},m=new URL(r);let g=new RTCPeerConnection;const _=g.createDataChannel("oai-events");let T;const y=A=>{A.onconnectionstatechange=()=>{switch(A.connectionState){case"disconnected":case"failed":case"closed":this.close();break}}};y(g),k(this,ie,{status:"connecting",peerConnection:g,dataChannel:_,callId:T}),this.emit("connection_change",c(this,ie).status),_.addEventListener("open",()=>{k(this,ie,{status:"connected",peerConnection:g,dataChannel:_,callId:T}),this.updateSessionConfig(d),this.emit("connection_change",c(this,ie).status),this._onOpen(),a()}),_.addEventListener("error",A=>{this.close(),this._onError(A),u(A)}),_.addEventListener("message",A=>{this._onMessage(A);const{data:D,isGeneric:U}=Er(A);if(!(!D||U)&&(D.type==="response.created"?k(this,yt,!0):D.type==="response.done"&&k(this,yt,!1),D.type==="session.created")){this._tracingConfig=D.session.tracing;const G=typeof d.tracing>"u"?"auto":d.tracing;this._updateTracingConfig(G)}});const h=this.options.audioElement??document.createElement("audio");h.autoplay=!0,g.ontrack=A=>{h.srcObject=A.streams[0]};const v=this.options.mediaStream??await navigator.mediaDevices.getUserMedia({audio:!0});if(g.addTrack(v.getAudioTracks()[0]),this.options.changePeerConnection){const A=g;g=await this.options.changePeerConnection(g),A!==g&&(A.onconnectionstatechange=null),y(g),k(this,ie,{...c(this,ie),peerConnection:g})}const b=await g.createOffer();if(await g.setLocalDescription(b),!b.sdp)throw new Error("Failed to create offer");const N=await fetch(m,{method:"POST",body:b.sdp,headers:{"Content-Type":"application/sdp",Authorization:`Bearer ${i}`,"X-OpenAI-Agents-SDK":to["X-OpenAI-Agents-SDK"]}});T=(p=(l=N.headers)==null?void 0:l.get("Location"))==null?void 0:p.split("/").pop(),k(this,ie,{...c(this,ie),callId:T});const x={type:"answer",sdp:await N.text()};await g.setRemoteDescription(x)}catch(d){this.close(),this._onError(d),u(d)}})}sendEvent(t){if(!c(this,ie).dataChannel||c(this,ie).dataChannel.readyState!=="open")throw new Error("WebRTC data channel is not connected. Make sure you call `connect()` before sending events.");c(this,ie).dataChannel.send(JSON.stringify(t))}mute(t){k(this,Gn,t),c(this,ie).peerConnection&&c(this,ie).peerConnection.getSenders().forEach(r=>{r.track&&(r.track.enabled=!t)})}_afterAudioDoneEvent(){k(this,yt,!1)}close(){if(c(this,ie).dataChannel&&c(this,ie).dataChannel.close(),c(this,ie).peerConnection){const t=c(this,ie).peerConnection;t.onconnectionstatechange=null,t.getSenders().forEach(s=>{var r;(r=s.track)==null||r.stop()}),t.close()}c(this,ie).status!=="disconnected"&&(k(this,ie,{status:"disconnected",peerConnection:void 0,dataChannel:void 0,callId:void 0}),this.emit("connection_change",c(this,ie).status),this._onClose())}interrupt(){c(this,yt)&&(this.sendEvent({type:"response.cancel"}),k(this,yt,!1)),this.sendEvent({type:"output_audio_buffer.clear"})}}qn=new WeakMap,ie=new WeakMap,Jn=new WeakMap,yt=new WeakMap,Gn=new WeakMap;const rf=globalThis.WebSocket;class af extends Ms{constructor(t={}){super(t);R(this,Bt);R(this,_t);R(this,jt);R(this,Ut);R(this,ye,{status:"disconnected",websocket:void 0});R(this,Vn);R(this,at);R(this,Lt);S(this,"_firstAudioTimestamp");S(this,"_audioLengthMs",0);R(this,zt,!1);R(this,ln);R(this,Hn);k(this,jt,t.url),k(this,Ut,t.url),k(this,Vn,t.useInsecureApiKey??!1),k(this,ln,t.createWebSocket),k(this,Hn,t.skipOpenEventListeners??!1)}getCommonRequestHeaders(){return to}get status(){return c(this,ye).status}get connectionState(){return c(this,ye)}get muted(){return null}get currentItemId(){return c(this,at)}_onAudio(t){this.emit("audio",t)}_afterAudioDoneEvent(){z(this,Bt,Zr).call(this)}async connect(t){const s=t.model??this.currentModel;this.currentModel=s,k(this,_t,await this._getApiKey(t));const r=t.callId;let i;t.url?(i=t.url,k(this,Ut,t.url)):r?i=`wss://api.openai.com/v1/realtime?call_id=${r}`:c(this,Ut)?i=c(this,Ut):i=`wss://api.openai.com/v1/realtime?model=${this.currentModel}`,k(this,jt,i);const o={...t.initialSessionConfig||{},model:this.currentModel};await new Promise((a,u)=>{z(this,Bt,bo).call(this,a,u,o).catch(u)}),await this.updateSessionConfig(o)}sendEvent(t){if(!c(this,ye).websocket)throw new Error("WebSocket is not connected. Make sure you call `connect()` before sending events.");c(this,ye).websocket.send(JSON.stringify(t))}close(){var t;(t=c(this,ye).websocket)==null||t.close(),k(this,at,void 0),this._firstAudioTimestamp=void 0,this._audioLengthMs=0,k(this,Lt,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,s={}){c(this,ye).status==="connected"&&super.sendAudio(t,s)}_cancelResponse(){c(this,zt)&&(this.sendEvent({type:"response.cancel"}),k(this,zt,!1))}_interrupt(t,s=!0){if(t<0)return;s&&this._cancelResponse();const r=this._audioLengthMs??Number.POSITIVE_INFINITY,i=Math.max(0,Math.floor(Math.min(t,r)));this.emit("audio_interrupted"),this.sendEvent({type:"conversation.item.truncate",item_id:c(this,at),content_index:c(this,Lt),audio_end_ms:i})}interrupt(t=!0){if(!c(this,at)||typeof this._firstAudioTimestamp!="number")return;const s=Date.now()-this._firstAudioTimestamp;s>=0&&this._interrupt(s,t),z(this,Bt,Zr).call(this)}}_t=new WeakMap,jt=new WeakMap,Ut=new WeakMap,ye=new WeakMap,Vn=new WeakMap,at=new WeakMap,Lt=new WeakMap,zt=new WeakMap,ln=new WeakMap,Hn=new WeakMap,Bt=new WeakSet,Zr=function(){k(this,at,void 0),this._firstAudioTimestamp=void 0,this._audioLengthMs=0,k(this,Lt,void 0)},bo=async function(t,s,r){if(c(this,ye).websocket){t();return}if(!c(this,_t))throw new re("API key is not set. Please call `connect()` with an API key first.");if(!c(this,_t).startsWith("ek_")&&!c(this,Vn))throw new re("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 i=null;if(c(this,ln))i=await c(this,ln).call(this,{url:c(this,jt),apiKey:c(this,_t)});else{const a=["realtime","openai-insecure-api-key."+c(this,_t),Hd];i=new rf(c(this,jt),a)}k(this,ye,{status:"connecting",websocket:i}),this.emit("connection_change",c(this,ye).status);const o=()=>{k(this,ye,{status:"connected",websocket:i}),this.emit("connection_change",c(this,ye).status),this._onOpen(),t()};c(this,Hn)===!0?o():i.addEventListener("open",o),i.addEventListener("error",a=>{this._onError(a),k(this,ye,{status:"disconnected",websocket:void 0}),this.emit("connection_change",c(this,ye).status),s(a)}),i.addEventListener("message",a=>{var p,d,m,g,_,T,y;this._onMessage(a);const{data:u,isGeneric:l}=Er(a);if(!(!u||l)){if(u.type==="response.output_audio.delta"){k(this,Lt,u.content_index),k(this,at,u.item_id),this._firstAudioTimestamp===void 0&&(this._firstAudioTimestamp=Date.now(),this._audioLengthMs=0);const h=Bd(u.delta),v=(m=(d=(p=this._rawSessionConfig)==null?void 0:p.audio)==null?void 0:d.output)==null?void 0:m.format;if(v&&typeof v=="object"){const N=v.type;if(N==="audio/pcmu"||N==="audio/pcma")this._audioLengthMs+=h.byteLength/8;else if(N==="audio/pcm"){const x=v.rate??24e3;this._audioLengthMs+=h.byteLength/2/x*1e3}else this._audioLengthMs+=h.byteLength/24/2}else typeof v=="string"?v.startsWith("g711_")?this._audioLengthMs+=h.byteLength/8:this._audioLengthMs+=h.byteLength/24/2:this._audioLengthMs+=h.byteLength/24/2;const b={type:"audio",data:h,responseId:u.response_id};this._onAudio(b)}else if(u.type==="input_audio_buffer.speech_started"){const h=((y=(T=(_=(g=this._rawSessionConfig)==null?void 0:g.audio)==null?void 0:_.input)==null?void 0:T.turn_detection)==null?void 0:y.interrupt_response)??!1;this.interrupt(!h)}else if(u.type==="response.created")k(this,zt,!0);else if(u.type==="response.done")k(this,zt,!1);else if(u.type==="session.created"){this._tracingConfig=u.session.tracing;const h=typeof r.tracing>"u"?"auto":r.tracing;this._updateTracingConfig(h)}}}),i.addEventListener("close",()=>{k(this,ye,{status:"disconnected",websocket:void 0}),this.emit("connection_change",c(this,ye).status),this._onClose()})};const of=Symbol("backgroundResult");function uf(n){return typeof n=="object"&&n!==null&&of in n}function cf(n){return n.type==="function"||n.type==="hosted_tool"&&n.name==="hosted_mcp"}function lf(n){if(n.type==="function")return n;if(n.type==="hosted_tool"&&n.name==="hosted_mcp"){const e=n.providerData.server_url&&n.providerData.server_url.length>0?n.providerData.server_url:void 0;return{type:"mcp",server_label:n.providerData.server_label,server_url:e,headers:n.providerData.headers,allowed_tools:n.providerData.allowed_tools,require_approval:n.providerData.require_approval}}throw new re(`Invalid tool type: ${n}`)}function df(){return JSON.parse(JSON.stringify(Je))}const Mr=class Mr extends ws{constructor(t,s={}){super();R(this,ae);S(this,"initialAgent");S(this,"options");R(this,W);R(this,Z);R(this,dn);R(this,q);R(this,pn,[]);R(this,fn);R(this,Wn,{});R(this,ue,[]);R(this,hn);R(this,mn,{});R(this,Ge,!1);R(this,Kn,new Map);R(this,Zt,[]);R(this,Yn,df());R(this,Xn,!0);this.initialAgent=t,this.options=s,typeof s.transport>"u"&&Gd()||s.transport==="webrtc"?k(this,W,new sf):s.transport==="websocket"||typeof s.transport>"u"?k(this,W,new af):k(this,W,s.transport),k(this,Z,t),k(this,q,new Wt({...s.context??{},history:c(this,ue)})),k(this,pn,(s.outputGuardrails??[]).map(Xd)),k(this,fn,Yd(s.outputGuardrailSettings??{})),k(this,hn,s.historyStoreAudio??!1),k(this,Xn,s.automaticallyTriggerResponseForMcpToolCalls??!0)}get transport(){return c(this,W)}get currentAgent(){return c(this,Z)}get usage(){return c(this,q).usage}get context(){return c(this,q)}get muted(){return c(this,W).muted}get history(){return c(this,ue)}get availableMcpTools(){return c(this,Zt)}async getInitialSessionConfig(t={}){return await z(this,ae,ts).call(this,this.initialAgent),z(this,ae,ns).call(this,{...this.options.config??{},...t??{}})}static async computeInitialSessionConfig(t,s={},r={}){const i=new Mr(t,s);try{return await i.getInitialSessionConfig(r)}finally{i.close()}}async updateAgent(t){return c(this,Z).emit("agent_handoff",c(this,q),t),this.emit("agent_handoff",c(this,q),c(this,Z),t),await z(this,ae,ts).call(this,t),await c(this,W).updateSessionConfig(await z(this,ae,ns).call(this)),t}async connect(t){await z(this,ae,ts).call(this,this.initialAgent),z(this,ae,So).call(this),await c(this,W).connect({apiKey:t.apiKey??this.options.apiKey,model:this.options.model,url:t.url,callId:t.callId,initialSessionConfig:await z(this,ae,ns).call(this,this.options.config)}),k(this,ue,[]),this.emit("history_updated",c(this,ue))}updateHistory(t){let s;typeof t=="function"?s=t(c(this,ue)):s=t,c(this,W).resetHistory(c(this,ue),s)}sendMessage(t,s={}){c(this,W).sendMessage(t,s)}addImage(t,{triggerResponse:s=!0}={}){c(this,W).addImage(t,{triggerResponse:s})}mute(t){c(this,W).mute(t)}close(){k(this,mn,{}),c(this,W).close()}sendAudio(t,s={}){c(this,W).sendAudio(t,s)}interrupt(){c(this,W).interrupt()}async approve(t,s={alwaysApprove:!1}){c(this,q).approveTool(t,s);const r=t.toolName??t.rawItem.name,i=c(this,Z).tools.find(o=>o.name===r);if(i&&i.type==="function"&&t.rawItem.type==="function_call")await z(this,ae,js).call(this,t.rawItem,i);else if(t.rawItem.type==="hosted_tool_call"){s.alwaysApprove&&Ne.warn("Always approving MCP tools is not supported. Use the allowed tools configuration instead.");const o=no(t);c(this,W).sendMcpResponse(o,!0)}else throw new Se(`Tool ${r??"unknown"} not found`)}async reject(t,s={alwaysReject:!1}){c(this,q).rejectTool(t,s);const r=t.toolName??t.rawItem.name,i=c(this,Z).tools.find(o=>o.name===r);if(i&&i.type==="function"&&t.rawItem.type==="function_call")await z(this,ae,js).call(this,t.rawItem,i);else if(t.rawItem.type==="hosted_tool_call"){s.alwaysReject&&Ne.warn("Always rejecting MCP tools is not supported. Use the allowed tools configuration instead.");const o=no(t);c(this,W).sendMcpResponse(o,!1)}else throw new Se(`Tool ${r??"unknown"} not found`)}};W=new WeakMap,Z=new WeakMap,dn=new WeakMap,q=new WeakMap,pn=new WeakMap,fn=new WeakMap,Wn=new WeakMap,ue=new WeakMap,hn=new WeakMap,mn=new WeakMap,Ge=new WeakMap,Kn=new WeakMap,Zt=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,ae=new WeakSet,ts=async function(t){k(this,Z,t);const s=await c(this,Z).getEnabledHandoffs(c(this,q)),r=s.map(u=>u.getHandoffAsFunctionTool()),i=(await c(this,Z).getAllTools(c(this,q))).filter(cf).map(lf),o=typeof c(this,Z).tools<"u"||typeof c(this,Z).mcpServers<"u",a=s.length>0;k(this,dn,o||a?[...i,...r]:void 0),z(this,ae,Jr).call(this)},ns=async function(t={}){const s=t??{},r=this.options.config??{},i=await c(this,Z).getSystemPrompt(c(this,q)),o=g=>{var T;const _=g.audio;return(T=_==null?void 0:_.output)==null?void 0:T.voice},a=this.options.tracingDisabled?null:this.options.workflowName?{workflow_name:this.options.workflowName}:"auto";a!==null&&a!=="auto"?(this.options.groupId&&(a.group_id=this.options.groupId),this.options.traceMetadata&&(a.metadata=this.options.traceMetadata)):(this.options.groupId||this.options.traceMetadata)&&Ne.warn("In order to set traceMetadata or a groupId you need to specify a workflowName.");const u=o(s)??o(r),l=s.voice??r.voice,p=typeof u<"u"?u:typeof l<"u"?l:c(this,Z).voice,m={...{...c(this,Yn)??{},...r,...s},instructions:i,voice:p,model:this.options.model,tools:c(this,dn),tracing:a,prompt:typeof c(this,Z).prompt=="function"?await c(this,Z).prompt(c(this,q),c(this,Z)):c(this,Z).prompt};return k(this,Yn,m),m},wo=async function(t,s){const r=await s.onInvokeHandoff(c(this,q),t.arguments);c(this,Z).emit("agent_handoff",c(this,q),r),this.emit("agent_handoff",c(this,q),c(this,Z),r),await z(this,ae,ts).call(this,r),await c(this,W).updateSessionConfig(await z(this,ae,ns).call(this));const i=Vi(r);return c(this,W).sendFunctionCallOutput(t,i,!0),r},js=async function(t,s){c(this,q).context.history=JSON.parse(JSON.stringify(c(this,ue)));let r=t.arguments;if(s.parameters&&(kt(s.parameters)?r=s.parameters.parse(r):r=JSON.parse(r)),await s.needsApproval(c(this,q),r,t.callId)){const u=this.context.isToolApproved({toolName:s.name,callId:t.callId});if(u===!1){this.emit("agent_tool_start",c(this,q),c(this,Z),s,{toolCall:t}),c(this,Z).emit("agent_tool_start",c(this,q),s,{toolCall:t});const l="Tool execution was not approved.";c(this,W).sendFunctionCallOutput(t,l,!0),this.emit("agent_tool_end",c(this,q),c(this,Z),s,l,{toolCall:t}),c(this,Z).emit("agent_tool_end",c(this,q),s,l,{toolCall:t});return}else if(typeof u>"u"){this.emit("tool_approval_requested",c(this,q),c(this,Z),{type:"function_approval",tool:s,approvalItem:new Ie(t,c(this,Z))});return}}this.emit("agent_tool_start",c(this,q),c(this,Z),s,{toolCall:t}),c(this,Z).emit("agent_tool_start",c(this,q),s,{toolCall:t}),c(this,q).context.history=JSON.parse(JSON.stringify(c(this,ue)));const o=await s.invoke(c(this,q),t.arguments,{toolCall:t});let a;uf(o)?(a=lt(o.content),c(this,W).sendFunctionCallOutput(t,a,!1)):(a=lt(o),c(this,W).sendFunctionCallOutput(t,a,!0)),this.emit("agent_tool_end",c(this,q),c(this,Z),s,a,{toolCall:t}),c(this,Z).emit("agent_tool_end",c(this,q),s,a,{toolCall:t})},Io=async function(t){const s=await c(this,Z).getEnabledHandoffs(c(this,q)),r=new Map(s.map(u=>[u.toolName,u])),i=await c(this,Z).getAllTools(c(this,q)),o=new Map(i.map(u=>[u.name,u])),a=r.get(t.name);if(a)await z(this,ae,wo).call(this,t,a);else{const u=o.get(t.name);if(u&&u.type==="function")await z(this,ae,js).call(this,t,u);else throw new Se(`Tool ${t.name} not found`)}},qr=async function(t,s,r){if(c(this,pn).length===0)return;const i={agent:c(this,Z),agentOutput:t,context:c(this,q)},a=(await Promise.all(c(this,pn).map(u=>u.run(i)))).find(u=>u.output.tripwireTriggered);if(a){if(c(this,mn)[s])return;c(this,mn)[s]=!0;const u=new Ys(`Output guardrail triggered: ${JSON.stringify(a.output.outputInfo)}`,a);this.emit("guardrail_tripped",c(this,q),c(this,Z),u,{itemId:r}),this.interrupt();const l=Qd(a);this.sendMessage(l);return}},So=function(){c(this,W).on("*",r=>{if(this.emit("transport_event",r),r.type==="conversation.item.input_audio_transcription.completed")try{const i=r;k(this,ue,eo(c(this,ue),i,c(this,hn))),c(this,q).context.history=c(this,ue),this.emit("history_updated",c(this,ue))}catch(i){this.emit("error",{type:"error",error:i})}}),c(this,W).on("mcp_tools_listed",({serverLabel:r,tools:i})=>{try{c(this,Kn).set(r,i??[]),z(this,ae,Jr).call(this)}catch(o){this.emit("error",{type:"error",error:o})}}),c(this,W).on("audio",r=>{c(this,Ge)||(k(this,Ge,!0),this.emit("audio_start",c(this,q),c(this,Z))),this.emit("audio",r)}),c(this,W).on("turn_started",()=>{k(this,Ge,!1),this.emit("agent_start",c(this,q),c(this,Z)),c(this,Z).emit("agent_start",c(this,q),c(this,Z))}),c(this,W).on("turn_done",r=>{const i=r.response.output[r.response.output.length-1],o=qd(i)??"",a=(i==null?void 0:i.id)??"";this.emit("agent_end",c(this,q),c(this,Z),o),c(this,Z).emit("agent_end",c(this,q),o),z(this,ae,qr).call(this,o,r.response.id,a)}),c(this,W).on("audio_done",()=>{c(this,Ge)&&k(this,Ge,!1),this.emit("audio_stopped",c(this,q),c(this,Z))});let t=0,s;c(this,W).on("audio_transcript_delta",r=>{try{const i=r.delta,o=r.itemId,a=r.responseId;s!==o&&(s=o,t=0);const l=(c(this,Wn)[o]??"")+i;if(c(this,Wn)[o]=l,c(this,fn).debounceTextLength<0)return;const p=Math.floor(l.length/c(this,fn).debounceTextLength);p>t&&(t=p,z(this,ae,qr).call(this,l,a,o))}catch(i){this.emit("error",{type:"error",error:i})}}),c(this,W).on("item_update",r=>{try{const i=!c(this,ue).some(o=>o.itemId===r.itemId);if(k(this,ue,eo(c(this,ue),r,c(this,hn))),c(this,q).context.history=c(this,ue),i){const o=c(this,ue).find(a=>a.itemId===r.itemId);o&&this.emit("history_added",o)}this.emit("history_updated",c(this,ue))}catch(i){this.emit("error",{type:"error",error:i})}}),c(this,W).on("item_deleted",r=>{try{k(this,ue,c(this,ue).filter(i=>i.itemId!==r.itemId)),c(this,q).context.history=c(this,ue),this.emit("history_updated",c(this,ue))}catch(i){this.emit("error",{type:"error",error:i})}}),c(this,W).on("function_call",async r=>{try{await z(this,ae,Io).call(this,r)}catch(i){Ne.error("Error handling function call",i),this.emit("error",{type:"error",error:i})}}),c(this,W).on("usage_update",r=>{c(this,q).usage.add(r)}),c(this,W).on("audio_interrupted",()=>{c(this,Ge)&&k(this,Ge,!1),this.emit("audio_interrupted",c(this,q),c(this,Z))}),c(this,W).on("error",r=>{this.emit("error",r)}),c(this,W).on("mcp_tool_call_completed",r=>{this.emit("mcp_tool_call_completed",c(this,q),c(this,Z),r),c(this,Xn)&&c(this,W).sendEvent({type:"response.create"})}),c(this,W).on("mcp_approval_request",r=>{this.emit("tool_approval_requested",c(this,q),c(this,Z),{type:"mcp_approval_request",approvalItem:Wd(c(this,Z),r)})})},Jr=function(){var u;const t=(u=c(this,dn))==null?void 0:u.filter(l=>l.type==="mcp"),s=l=>{const p=l.allowed_tools;if(p){if(Array.isArray(p))return p;if(p&&Array.isArray(p.tool_names))return p.tool_names}},r=new Map;for(const l of t){const p=c(this,Kn).get(l.server_label)??[],d=s(l);for(const m of p)d&&!d.includes(m.name)||r.has(m.name)||r.set(m.name,m)}const i=Array.from(r.values()),o=c(this,Zt);(o.length!==i.length||JSON.stringify(o.map(l=>l.name).sort())!==JSON.stringify(i.map(l=>l.name).sort()))&&(k(this,Zt,i),this.emit("mcp_tools_changed",c(this,Zt)))};let Rr=Mr;class pf{constructor(){this._listeners={}}on(e,t){return this._listeners[e]||(this._listeners[e]=new Set),this._listeners[e].add(t),this}off(e,t){const s=this._listeners[e];return s&&(s.delete(t),s.size===0&&delete this._listeners[e]),this}emit(e,...t){const s=this._listeners[e];if(!s||s.size===0)return!1;for(const r of Array.from(s))try{r(...t)}catch(i){console.error(`BabelbeezClient listener for event "${e}" threw:`,i)}return!0}}const Rt={DEBUG:0,INFO:1,WARN:2,ERROR:3},uo=!0,ff=Rt.INFO;function $(n,e,...t){const s=Rt[n]??Rt.INFO;if(!(s<ff))switch(s){case Rt.DEBUG:console.debug(`[${n}] ${e}`,...t);break;case Rt.INFO:console.info(`[${n}] ${e}`,...t);break;case Rt.WARN:console.warn(`[${n}] ${e}`,...t);break;case Rt.ERROR:{const r=t.find(o=>o instanceof Error),i=e+(r&&r.message?`: ${r.message}`:"");console.error(`[${n}] ${i}`)}break;default:console.log(`[${n}] ${e}`,...t)}}function co(n,e){if(!e)return n;n||(n={});for(const t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;const s=e[t],r=n[t];typeof s=="number"?n[t]=(typeof r=="number"?r:0)+s:typeof s=="object"&&s!==null&&!Array.isArray(s)&&((typeof r!="object"||r===null||Array.isArray(r))&&(n[t]={}),co(n[t],s))}return n}const hf=15e3,mf=2e3,gf="https://www.babelbeez.com/initialize-chat";class yf extends pf{constructor(e){if(super(),!e||!e.publicChatbotId)throw new Error("BabelbeezClient: publicChatbotId is required.");this.publicChatbotId=e.publicChatbotId;const t=e.proxyInitializeUrl||gf;this.proxyInitializeUrl=t,this.apiBaseUrl=e.apiBaseUrl||new URL(t).origin,this.agent=null,this.session=null,this.currentSystemSettings=null,this.currentChatbotSettings=null,this.currentSessionId=null,this.currentRagSearchUrl=null,this.sessionStartTime=null,this.accumulatedUsage=null,this.hasEndConversationBeenHandled=!1,this.isTerminating=!1,this.isUserSpeaking=!1,this.isAssistantSpeaking=!1,this.isHandoffFormOpen=!1,this.inactivityStage=0,this.inactivityStage1TimeoutId=null,this.inactivityStage2TimeoutId=null,this.shouldScheduleStage2OnNextAssistantSilence=!1,this.pendingGoodbyeResolve=null,this.handoffPromiseResolve=null,this.currentHandoffSummaryText=null,this.heartbeatIntervalId=null,this.heartbeatFrequencySeconds=null,this._lastInitData=null,this._lastAssistantMessageId=null,this._lastAssistantTranscript="",this._currentAssistantTranscript="",this._currentUserTranscript=""}async connect(){if(this.session){$("WARN","BabelbeezClient.connect() called while session already active; ignoring.");return}$("INFO","BabelbeezClient.connect: initializing via proxy and connecting RealtimeSession.");const e=await this._initializeSessionViaProxy();this._lastInitData=e;const{openai_token:t,system_settings:s,chatbot_config:r,session_id:i,heartbeat_frequency_seconds:o}=e;this.currentSystemSettings=s,this.currentChatbotSettings=r,this.currentSessionId=i,this.heartbeatFrequencySeconds=o,this.currentRagSearchUrl=`${this.apiBaseUrl}/api/perform-rag-search`,$("DEBUG","BabelbeezClient: using RAG search URL",this.currentRagSearchUrl),this._resetAccumulatedUsage(),this._resetInactivityState(),this.isUserSpeaking=!1,this.isAssistantSpeaking=!1,this.isTerminating=!1,this.hasEndConversationBeenHandled=!1;try{this.emit("buttonState","loading"),this.agent=this._createVoiceAgent(),this.session=this._createVoiceSession(s,r),await this.session.connect({apiKey:t}),this._attachTransportListeners(),this.sessionStartTime=Date.now(),this.emit("buttonState","active"),this.emit("session:start",{chatbotId:this.publicChatbotId,config:this.currentChatbotSettings}),this._startHeartbeat(),this._resetInactivityState(),$("INFO","BabelbeezClient: Realtime session connected."),setTimeout(()=>{var u;const a=(u=this.currentChatbotSettings)==null?void 0:u.greetingInstructions;if(a)try{this.session&&this.session.transport&&this.session.transport.sendEvent({type:"response.create",response:{conversation:"none",output_modalities:["audio"],instructions:a,tools:[],input:[{type:"message",role:"user",content:[{type:"input_text",text:"The caller has just connected. Greet them now."}]}],metadata:{source:"greeting"}}})}catch(l){$("WARN","BabelbeezClient: failed to trigger greeting response (post-connect).",l)}},0)}catch(a){let u=`Connect Session failed: ${(a==null?void 0:a.message)||"Unknown error"}`,l="connection_error",p="CONNECTION_FAILED";throw a&&(a.name==="NotAllowedError"||a.name==="PermissionDeniedError")?(u="Microphone access denied. Please allow microphone access in your browser settings.",l="microphone_permission_denied",p="MIC_DENIED"):a&&a.name==="NotFoundError"&&(u="No microphone found. Please ensure a microphone is connected and enabled.",l="microphone_not_found",p="MIC_NOT_FOUND"),$("ERROR",u,a),this.emit("buttonState","error"),this.emit("error",{code:p,message:u,severity:"error",fatal:!0}),await this._finalizeSession(l),a}}async disconnect(e="client_disconnect"){if($("INFO",`BabelbeezClient.disconnect called. Reason: ${e}`),e==="user_button_click"){try{this.session&&(await this.session.interrupt(),$("INFO","Session interrupted by user_button_click before goodbye."))}catch(t){$("WARN","Error interrupting session during user_button_click; proceeding with goodbye anyway.",t)}await this._playGoodbyeThenFinalize(e);return}await this._finalizeSession(e)}initializeAudio(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return;const t=this._audioCtx||new e;this._audioCtx=t,t.state==="suspended"&&t.resume().catch(()=>{});try{const s=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,s),r.connect(t.destination);const i=t.createOscillator();i.type="sine",i.frequency.setValueAtTime(440,s),i.connect(r),i.start(s),i.stop(s+.02),i.onended=()=>{try{i.disconnect(),r.disconnect()}catch{}}}catch{}}catch(e){$("WARN","BabelbeezClient.initializeAudio failed",e)}}async sendUserText(e){if(!this.session||this.isTerminating){$("WARN","Cannot send text message; session is not active or is terminating.");return}const t=(e??"").trim();if(!t){$("DEBUG","sendUserText called with empty/whitespace text; ignoring.");return}if(this.isAssistantSpeaking)try{await this.session.interrupt()}catch(s){$("WARN","Failed to interrupt assistant before sending user text.",s)}this._resetInactivityState();try{await this.session.sendMessage(t),this.emit("transcript",{role:"user",text:t,isFinal:!0})}catch(s){$("ERROR","Failed to send user text message",s)}}async handleHandoffSubmit(e){if(!this.isHandoffFormOpen){$("WARN","handleHandoffSubmit called but no handoff form is open.");return}const{email:t,consent:s}=e||{},r=this.currentHandoffSummaryText||"Summary not available.";try{const i=`${this.apiBaseUrl}/handoff/request`,o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.currentSessionId,email:t,consent:s,summary:r})});if(o.ok)$("INFO","Handoff request submitted successfully.");else{let a=`HTTP ${o.status}`;try{const u=await o.json();u&&u.detail&&(a=u.detail)}catch{}$("ERROR",`Failed to submit handoff request: ${a}`),this.emit("error",{code:"HANDOFF_FAILED",message:"Failed to submit handoff request. Please try again later.",severity:"error",fatal:!1})}}catch(i){$("ERROR","Network or unexpected error submitting handoff request.",i),this.emit("error",{code:"HANDOFF_FAILED",message:"Network error submitting handoff request. Please try again later.",severity:"error",fatal:!1})}finally{this.isHandoffFormOpen=!1,this._resetInactivityState(),this.isTerminating||this._setSessionMuted(!1,"handoff_form"),this.emit("handoff:hide",{outcome:"email_submitted"}),this.handoffPromiseResolve&&(this.handoffPromiseResolve("email_submitted"),this.handoffPromiseResolve=null)}try{this.session&&await this.session.sendMessage("The user has submitted their contact details. Confirm that their request was received and that a team member will follow up. See if there's anything else you can help them with in the meantime.")}catch(i){$("WARN","Failed to send post-handoff confirmation message.",i)}}async handleHandoffCancel(e={}){const{viaWhatsapp:t}=e;if(!this.isHandoffFormOpen){$("WARN","handleHandoffCancel called but no handoff form is open.");return}this.isHandoffFormOpen=!1,this._resetInactivityState(),this.isTerminating||this._setSessionMuted(!1,"handoff_form");const s=t?"whatsapp_submitted":"cancelled";if(this.emit("handoff:hide",{outcome:s}),this.handoffPromiseResolve&&(this.handoffPromiseResolve(s),this.handoffPromiseResolve=null),t){await this._playGoodbyeThenFinalize("handoff_whatsapp");return}try{this.session&&await this.session.sendMessage("The user changed their mind and no longer wishes to fill out the form right now. See if there's anything else you can help them with.")}catch(r){$("WARN","Failed to send handoff cancellation message.",r)}}async _initializeSessionViaProxy(){$("INFO","BabelbeezClient: Initializing session via proxy /initialize-chat...");const e=typeof navigator<"u"&&(navigator.language||navigator.userLanguage)||null,t=await fetch(this.proxyInitializeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({public_chatbot_id:this.publicChatbotId,browser_language:e})});if(!t.ok){let r=`HTTP error ${t.status}: ${t.statusText}`;try{const i=await t.json();i&&i.detail&&(r=i.detail)}catch{}throw $("ERROR","BabelbeezClient: /initialize-chat failed",r),new Error(r)}const s=await t.json();if(!s.session_id||!s.openai_token||!s.system_settings||!s.chatbot_config||s.heartbeat_frequency_seconds===void 0)throw $("ERROR","BabelbeezClient: Invalid response structure from /initialize-chat.",s?{...s,openai_token:"***"}:null),new Error("Incomplete session details received from server.");return $("INFO","BabelbeezClient: Session initialized via proxy.",{session_id:s.session_id,heartbeat_frequency_seconds:s.heartbeat_frequency_seconds}),s}_resetAccumulatedUsage(){this.accumulatedUsage={total_tokens:0,input_tokens:0,output_tokens:0,input_token_details:{cached_tokens:0,text_tokens:0,audio_tokens:0,cached_tokens_details:{text_tokens:0,audio_tokens:0}},output_token_details:{text_tokens:0,audio_tokens:0}},$("DEBUG","BabelbeezClient: accumulated token usage reset.")}_setSessionMuted(e,t=""){try{this.session&&this.session.transport&&typeof this.session.transport.mute=="function"&&(this.session.transport.mute(e),$("DEBUG",`Session ${e?"muted":"unmuted"}${t?` (${t})`:""}.`))}catch{}}_clearInactivityTimers(){this.inactivityStage1TimeoutId&&(clearTimeout(this.inactivityStage1TimeoutId),this.inactivityStage1TimeoutId=null),this.inactivityStage2TimeoutId&&(clearTimeout(this.inactivityStage2TimeoutId),this.inactivityStage2TimeoutId=null)}_resetInactivityState(){this.inactivityStage=0,this.shouldScheduleStage2OnNextAssistantSilence=!1,this._clearInactivityTimers()}async _sendInactivityEnquiry(){var t,s;const e=(((t=this.currentChatbotSettings)==null?void 0:t.inactivityTimeoutMs)||0)/1e3;$("INFO",`User inactive for ${e}s. Sending enquiry.`),this.shouldScheduleStage2OnNextAssistantSilence=!0;try{(s=this.currentSystemSettings)!=null&&s.inactivityInstructions&&this.session&&await this.session.sendMessage(this.currentSystemSettings.inactivityInstructions)}catch(r){$("ERROR","Failed to send inactivity enquiry; ending session.",r),await this._finalizeSession("inactivity_enquiry_failed")}}async _playGoodbyeThenFinalize(e){var o,a;if(this.isTerminating){await this._finalizeSession(e);return}this._clearInactivityTimers();const t=(a=(o=this.currentSystemSettings)==null?void 0:o.goodbyeInstructions)==null?void 0:a.trim();if(!this.session||!t){$("INFO","No goodbyeInstructions configured or no active session; finalizing immediately."),await this._finalizeSession(e);return}$("INFO","Playing goodbye message before finalizing session.");const s=new Promise(u=>{this.pendingGoodbyeResolve=u});try{this._setSessionMuted(!0,"goodbye"),await this.session.sendMessage(t)}catch(u){$("WARN","Failed to send goodbye message; finalizing immediately.",u),this.pendingGoodbyeResolve=null,this._setSessionMuted(!1,"goodbye"),await this._finalizeSession(e);return}const r=15e3,i=new Promise(u=>setTimeout(u,r));await Promise.race([s,i]),this.pendingGoodbyeResolve=null,this._setSessionMuted(!1,"goodbye"),await this._finalizeSession(e)}_createVoiceAgent(){var u,l,p,d;const e=(u=this.currentSystemSettings)!=null&&u.system_prompt?`${this.currentSystemSettings.system_prompt}
|
|
12
|
+
`.trim()}function Ve(t,e){return t in e&&typeof e[t]<"u"}function Kc(t){return Ve("modalities",t)||Ve("inputAudioFormat",t)||Ve("outputAudioFormat",t)||Ve("inputAudioTranscription",t)||Ve("turnDetection",t)||Ve("inputAudioNoiseReduction",t)||Ve("speed",t)}function Yc(t){if(!Kc(t)){const e=t.audio?.input?{format:Yt(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,s=t.audio?.output||typeof n<"u"?{format:Yt(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||s?{input:e,output:s}: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:Yt(t.inputAudioFormat),noiseReduction:t.inputAudioNoiseReduction??null,transcription:t.inputAudioTranscription,turnDetection:t.turnDetection},output:{format:Yt(t.outputAudioFormat),voice:t.voice,speed:t.speed}}}}function Yt(t){if(!t)return;if(typeof t=="object")return t;const e=String(t);return e==="pcm16"?{type:"audio/pcm",rate:24e3}:e==="g711_ulaw"?{type:"audio/pcmu"}:e==="g711_alaw"?{type:"audio/pcma"}:{type:"audio/pcm",rate:24e3}}y({itemId:c()});const ai=X("role",[y({itemId:c(),previousItemId:c().nullable().optional(),type:v("message"),role:v("system"),content:M(y({type:v("input_text"),text:c()}))}),y({itemId:c(),previousItemId:c().nullable().optional(),type:v("message"),role:v("user"),status:H(["in_progress","completed"]),content:M(y({type:v("input_text"),text:c()}).or(y({type:v("input_audio"),audio:c().nullable().optional(),transcript:c().nullable()})))}),y({itemId:c(),previousItemId:c().nullable().optional(),type:v("message"),role:v("assistant"),status:H(["in_progress","completed","incomplete"]),content:M(y({type:v("output_text"),text:c()}).or(y({type:v("output_audio"),audio:c().nullable().optional(),transcript:c().nullable().optional()})))})]),oi=y({itemId:c(),previousItemId:c().nullable().optional(),type:v("function_call"),status:H(["in_progress","completed","incomplete"]),arguments:c(),name:c(),output:c().nullable()}),ui=y({itemId:c(),previousItemId:c().nullable().optional(),type:H(["mcp_call","mcp_tool_call"]),status:H(["in_progress","completed","incomplete"]),arguments:c(),name:c(),output:c().nullable()}),Xc=y({itemId:c(),type:v("mcp_approval_request"),serverLabel:c(),name:c(),arguments:q(c(),$()),approved:Le().optional().nullable()}),ae=Us("openai-agents:realtime"),ci=y({id:c().optional().nullable(),conversation_id:c().optional().nullable(),max_output_tokens:T().or(v("inf")).optional().nullable(),metadata:q(c(),$()).optional().nullable(),output_modalities:M(c()).optional().nullable(),object:v("realtime.response").optional().nullable(),output:M($()).optional().nullable(),audio:y({output:y({format:$().optional().nullable(),voice:c().optional().nullable()}).optional().nullable()}).optional().nullable(),status:H(["completed","incomplete","failed","cancelled","in_progress"]).optional().nullable(),status_details:q(c(),$()).optional().nullable(),usage:y({input_tokens:T().optional(),input_token_details:q(c(),$()).optional().nullable(),output_tokens:T().optional(),output_token_details:q(c(),$()).optional().nullable()}).optional().nullable()}),Qc=y({id:c().optional(),audio:c().nullable().optional(),text:c().nullable().optional(),transcript:c().nullable().optional(),type:Te([v("input_text"),v("input_audio"),v("item_reference"),v("output_text"),v("output_audio")])}),at=y({id:c().optional(),arguments:c().optional(),call_id:c().optional(),content:M(Qc).optional(),name:c().optional(),output:c().nullable().optional(),role:H(["user","assistant","system"]).optional(),status:H(["completed","incomplete","in_progress"]).optional(),type:H(["message","function_call","function_call_output","mcp_list_tools","mcp_tool_call","mcp_call","mcp_approval_request","mcp_approval_response"]).optional(),approval_request_id:c().nullable().optional(),approve:Le().nullable().optional(),reason:c().nullable().optional(),server_label:c().optional(),error:$().nullable().optional(),tools:M(y({name:c(),description:c(),input_schema:q($()).optional()}).passthrough()).optional()}).passthrough(),el=y({type:v("conversation.created"),event_id:c(),conversation:y({id:c().optional(),object:v("realtime.conversation").optional()})}),tl=y({type:v("conversation.item.added"),event_id:c(),item:at,previous_item_id:c().nullable().optional()}),nl=y({type:v("conversation.item.done"),event_id:c(),item:at,previous_item_id:c().nullable().optional()}),sl=y({type:v("conversation.item.deleted"),event_id:c(),item_id:c()}),rl=y({type:v("conversation.item.input_audio_transcription.completed"),event_id:c(),item_id:c(),content_index:T(),transcript:c(),logprobs:M($()).nullable().optional(),usage:y({type:v("tokens"),total_tokens:T(),input_tokens:T(),input_token_details:y({text_tokens:T(),audio_tokens:T()}),output_tokens:T()}).optional()}),il=y({type:v("conversation.item.input_audio_transcription.delta"),event_id:c(),item_id:c(),content_index:T().optional(),delta:c().optional(),logprobs:M($()).nullable().optional()}),al=y({type:v("conversation.item.input_audio_transcription.failed"),event_id:c(),item_id:c(),content_index:T(),error:y({code:c().optional(),message:c().optional(),param:c().optional(),type:c().optional()})}),ol=y({type:v("conversation.item.retrieved"),event_id:c(),item:at}),ul=y({type:v("conversation.item.truncated"),event_id:c(),item_id:c(),audio_end_ms:T(),content_index:T()}),cl=y({type:v("conversation.item.create"),item:at,event_id:c().optional(),previous_item_id:c().nullable().optional()}),ll=y({type:v("conversation.item.delete"),item_id:c(),event_id:c().optional()}),dl=y({type:v("conversation.item.retrieve"),item_id:c(),event_id:c().optional()}),pl=y({type:v("conversation.item.truncate"),item_id:c(),audio_end_ms:T(),content_index:T(),event_id:c().optional()}),fl=y({type:v("error"),event_id:c().optional(),error:$().optional()}),hl=y({type:v("input_audio_buffer.cleared"),event_id:c()}),ml=y({type:v("input_audio_buffer.append"),audio:c(),event_id:c().optional()}),gl=y({type:v("input_audio_buffer.clear"),event_id:c().optional()}),yl=y({type:v("input_audio_buffer.commit"),event_id:c().optional()}),_l=y({type:v("input_audio_buffer.committed"),event_id:c(),item_id:c(),previous_item_id:c().nullable().optional()}),vl=y({type:v("input_audio_buffer.speech_started"),event_id:c(),item_id:c(),audio_start_ms:T()}),bl=y({type:v("input_audio_buffer.speech_stopped"),event_id:c(),item_id:c(),audio_end_ms:T()}),wl=y({type:v("output_audio_buffer.started"),event_id:c()}).passthrough(),Il=y({type:v("output_audio_buffer.stopped"),event_id:c()}).passthrough(),Sl=y({type:v("output_audio_buffer.cleared"),event_id:c()}),Tl=y({type:v("rate_limits.updated"),event_id:c(),rate_limits:M(y({limit:T().optional(),name:H(["requests","tokens"]).optional(),remaining:T().optional(),reset_seconds:T().optional()}))}),xl=y({type:v("response.output_audio.delta"),event_id:c(),item_id:c(),content_index:T(),delta:c(),output_index:T(),response_id:c()}),kl=y({type:v("response.output_audio.done"),event_id:c(),item_id:c(),content_index:T(),output_index:T(),response_id:c()}),Al=y({type:v("response.output_audio_transcript.delta"),event_id:c(),item_id:c(),content_index:T(),delta:c(),output_index:T(),response_id:c()}),Cl=y({type:v("response.output_audio_transcript.done"),event_id:c(),item_id:c(),content_index:T(),transcript:c(),output_index:T(),response_id:c()}),Ol=y({type:v("response.content_part.added"),event_id:c(),item_id:c(),content_index:T(),output_index:T(),response_id:c(),part:y({audio:c().optional(),text:c().optional(),transcript:c().optional(),type:H(["text","audio"]).optional()})}),El=y({type:v("response.content_part.done"),event_id:c(),item_id:c(),content_index:T(),output_index:T(),response_id:c(),part:y({audio:c().optional(),text:c().optional(),transcript:c().optional(),type:H(["text","audio"]).optional()})}),Rl=y({type:v("response.created"),event_id:c(),response:ci}),li=y({type:v("response.done"),event_id:c(),response:ci}),Nl=y({type:v("response.function_call_arguments.delta"),event_id:c(),item_id:c(),call_id:c(),delta:c(),output_index:T(),response_id:c()}),Dl=y({type:v("response.function_call_arguments.done"),event_id:c(),item_id:c(),call_id:c(),arguments:c(),output_index:T(),response_id:c()}),Pl=y({type:v("response.output_item.added"),event_id:c(),item:at,output_index:T(),response_id:c()}),Ml=y({type:v("response.output_item.done"),event_id:c(),item:at,output_index:T(),response_id:c()}),Fl=y({type:v("response.output_text.delta"),event_id:c(),item_id:c(),content_index:T(),delta:c(),output_index:T(),response_id:c()}),jl=y({type:v("response.output_text.done"),event_id:c(),item_id:c(),content_index:T(),text:c(),output_index:T(),response_id:c()}),$l=y({type:v("session.created"),event_id:c(),session:$()}),Ul=y({type:v("session.updated"),event_id:c(),session:$()}),Ll=y({type:v("response.cancel"),event_id:c().optional(),response_id:c().optional()}),Bl=y({type:v("response.create"),event_id:c().optional(),response:$().optional()}),zl=y({type:v("session.update"),event_id:c().optional(),session:$()}),Zl=y({type:v("mcp_list_tools.in_progress"),event_id:c().optional(),item_id:c().optional()}),ql=y({type:v("mcp_list_tools.completed"),event_id:c().optional(),item_id:c().optional()}),Jl=y({type:v("response.mcp_call_arguments.delta"),event_id:c(),response_id:c(),item_id:c(),output_index:T(),delta:c(),obfuscation:c()}),Gl=y({type:v("response.mcp_call_arguments.done"),event_id:c(),response_id:c(),item_id:c(),output_index:T(),arguments:c()}),Vl=y({type:v("response.mcp_call.in_progress"),event_id:c(),output_index:T(),item_id:c()}),Hl=y({type:v("response.mcp_call.completed"),event_id:c(),output_index:T(),item_id:c()}),Wl=y({type:v("mcp_list_tools.failed"),event_id:c().optional(),item_id:c().optional()}),Kl=y({type:c(),event_id:c().optional().nullable()}).passthrough(),Yl=X("type",[el,tl,nl,sl,rl,il,al,ol,ul,fl,hl,_l,vl,bl,wl,Il,Sl,Tl,xl,kl,Al,Cl,Ol,El,Rl,li,Nl,Dl,Pl,Ml,Fl,jl,$l,Ul,Zl,ql,Wl,Jl,Gl,Vl,Hl]);X("type",[cl,ll,dl,pl,ml,gl,yl,Ll,Bl,zl]);function Vn(t){const e=JSON.parse(t.data.toString()),n=Yl.safeParse(e);if(!n.success){const s=Kl.safeParse(e);return s.success?{data:s.data,isGeneric:!0}:{data:null,isGeneric:!0}}return{data:n.data,isGeneric:!1}}const Xl="gpt-realtime",be={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 Xt extends Tn{#e;#t;#r=null;#n=null;eventEmitter=new $t;constructor(e={}){super(),this.#e=e.model??Xl,this.#t=e.apiKey}get currentModel(){return this.#e}set currentModel(e){this.#e=e}_afterAudioDoneEvent(){}get _rawSessionConfig(){return this.#n??null}async _getApiKey(e){const n=e.apiKey??this.#t;return typeof n=="function"?await n():n}_onMessage(e){const{data:n,isGeneric:s}=Vn(e);if(n!==null&&(this.emit("*",n),!s)){if(n.type==="error"?this.emit("error",{type:"error",error:n}):this.emit(n.type,n),n.type==="response.created"){this.emit("turn_started",{type:"response_started",providerData:{...n}});return}if(n.type==="session.updated"&&(this.#n=n.session),n.type==="response.done"){const r=li.safeParse(n);if(!r.success){ae.error("Error parsing response done event",r.error);return}const i=r.data.response.usage?.input_tokens??0,a=r.data.response.usage?.output_tokens??0,o=i+a,u=new gt({inputTokens:i,inputTokensDetails:r.data.response.usage?.input_token_details??{},outputTokens:a,outputTokensDetails:r.data.response.usage?.output_token_details??{},totalTokens:o});this.emit("usage_update",u),this.emit("turn_done",{type:"response_done",response:{id:r.data.response.id??"",output:r.data.response.output??[],usage:{inputTokens:i,inputTokensDetails:r.data.response.usage?.input_token_details??{},outputTokens:a,outputTokensDetails:r.data.response.usage?.output_token_details??{},totalTokens:o}}});return}if(n.type==="response.output_audio.done"){this.emit("audio_done"),this._afterAudioDoneEvent();return}if(n.type==="conversation.item.deleted"){this.emit("item_deleted",{itemId:n.item_id});return}if(n.type==="conversation.item.input_audio_transcription.completed"||n.type==="conversation.item.truncated"){this.sendEvent({type:"conversation.item.retrieve",item_id:n.item_id});return}if(n.type==="conversation.item.input_audio_transcription.delta"||n.type==="response.output_text.delta"||n.type==="response.output_audio_transcript.delta"||n.type==="response.function_call_arguments.delta"){n.type==="response.output_audio_transcript.delta"&&this.emit("audio_transcript_delta",{type:"transcript_delta",delta:n.delta,itemId:n.item_id,responseId:n.response_id});return}if(n.type==="conversation.item.added"||n.type==="conversation.item.done"||n.type==="conversation.item.retrieved"){if(n.item.type==="mcp_list_tools"&&n.type==="conversation.item.done"){const r=n.item.server_label??"",i=n.item.tools??[];try{this.emit("mcp_tools_listed",{serverLabel:r,tools:i})}catch(a){ae.error("Error emitting mcp_tools_listed",a,n.item)}return}if(n.item.type==="message"){const r=n.type==="conversation.item.added"||n.type==="conversation.item.done"?n.previous_item_id:null,i=ai.parse({itemId:n.item.id,previousItemId:r,type:n.item.type,role:n.item.role,content:n.item.content,status:n.item.status});this.emit("item_update",i);return}if(n.item.type==="mcp_approval_request"&&n.type==="conversation.item.done"){const r=n.item,i=Xc.parse({itemId:r.id,type:r.type,serverLabel:r.server_label,name:r.name,arguments:JSON.parse(r.arguments||"{}"),approved:r.approved});this.emit("item_update",i),this.emit("mcp_approval_request",i);return}if(n.item.type==="mcp_tool_call"||n.item.type==="mcp_call"){const r=n.type==="conversation.item.done"?"completed":"in_progress",i=ui.parse({itemId:n.item.id,type:n.item.type,status:r,arguments:n.item.arguments,name:n.item.name,output:n.item.output});this.emit("item_update",i),n.type==="conversation.item.done"&&this.emit("mcp_tool_call_completed",i);return}}if(n.type==="response.mcp_call.in_progress"){const r=n;this.sendEvent({type:"conversation.item.retrieve",item_id:r.item_id});return}if(n.type==="mcp_list_tools.in_progress"){const r=n;r.item_id&&this.sendEvent({type:"conversation.item.retrieve",item_id:r.item_id});return}if(n.type==="response.output_item.done"||n.type==="response.output_item.added"){const r=n.item;if(r.type==="function_call"&&r.status==="completed"){const i=oi.parse({itemId:r.id,type:r.type,status:"in_progress",arguments:r.arguments,name:r.name,output:null});this.emit("item_update",i),this.emit("function_call",{id:r.id,type:"function_call",callId:r.call_id??"",arguments:r.arguments??"",name:r.name??""});return}if(r.type==="mcp_tool_call"||r.type==="mcp_call"){const i=ui.parse({itemId:r.id,type:r.type,status:n.type==="response.output_item.done"?"completed":"in_progress",arguments:r.arguments,name:r.name,output:r.output});this.emit("item_update",i);return}if(r.type==="message"){const i=ai.parse({itemId:n.item.id,type:n.item.type,role:n.item.role,content:n.item.content,status:n.type==="response.output_item.done"?r.status??"completed":r.status??"in_progress"});this.emit("item_update",i);return}}}}_onError(e){this.emit("error",{type:"error",error:e})}_onOpen(){this.emit("connected")}_onClose(){this.emit("disconnected")}sendMessage(e,n,{triggerResponse:s=!0}={}){const r=typeof e=="string"?[{type:"input_text",text:e}]:e.content.map(i=>i.type==="input_image"?{type:"input_image",image_url:i.image,...i.providerData??{}}:i);this.sendEvent({type:"conversation.item.create",item:{type:"message",role:"user",content:r},...n}),s&&this.sendEvent({type:"response.create"})}addImage(e,{triggerResponse:n=!0}={}){this.sendMessage({type:"message",role:"user",content:[{type:"input_image",image:e}]},{},{triggerResponse:n})}_getMergedSessionConfig(e){const n=Yc(e),s={type:"realtime",instructions:n.instructions,model:n.model??this.#e,output_modalities:n.outputModalities??be.outputModalities,audio:{input:{format:n.audio?.input?.format??be.audio?.input?.format,noise_reduction:n.audio?.input?.noiseReduction??be.audio?.input?.noiseReduction,transcription:n.audio?.input?.transcription??be.audio?.input?.transcription,turn_detection:Xt.buildTurnDetectionConfig(n.audio?.input?.turnDetection)??be.audio?.input?.turnDetection},output:{format:n.audio?.output?.format??be.audio?.output?.format,voice:n.audio?.output?.voice??be.audio?.output?.voice,speed:n.audio?.output?.speed??be.audio?.output?.speed}},tool_choice:n.toolChoice??be.toolChoice,...n.providerData??{}};return n.prompt&&(s.prompt={id:n.prompt.promptId,version:n.prompt.version,variables:n.prompt.variables}),n.tools&&n.tools.length>0&&(s.tools=n.tools.map(r=>({...r,strict:void 0}))),s}buildSessionPayload(e){return this._getMergedSessionConfig(e)}static buildTurnDetectionConfig(e){if(typeof e>"u")return;const{type:n,createResponse:s,create_response:r,eagerness:i,interruptResponse:a,interrupt_response:o,prefixPaddingMs:u,prefix_padding_ms:l,silenceDurationMs:d,silence_duration_ms:p,threshold:h,idleTimeoutMs:f,idle_timeout_ms:m,...g}=e,_={type:n,create_response:s||r,eagerness:i,interrupt_response:a||o,prefix_padding_ms:u||l,silence_duration_ms:d||p,idle_timeout_ms:f||m,threshold:h,...g};return Object.keys(_).forEach(w=>{_[w]===void 0&&delete _[w]}),Object.keys(_).length>0?_:void 0}set _tracingConfig(e){this.#r=e}_updateTracingConfig(e){if(typeof this.#r>"u"&&(this.#r=null),e==="auto"){this.sendEvent({type:"session.update",session:{type:"realtime",tracing:"auto"}});return}if(this.#r!==null&&typeof this.#r!="string"&&typeof e!="string"){ae.warn("Tracing config is already set, skipping setting it again. This likely happens when you already set a tracing config on session creation.");return}if(e===null){ae.debug("Disabling tracing for this session. It cannot be turned on for this session from this point on."),this.sendEvent({type:"session.update",session:{type:"realtime",tracing:null}});return}if(this.#r===null||typeof this.#r=="string"){this.sendEvent({type:"session.update",session:{type:"realtime",tracing:e}});return}if(e?.group_id!==this.#r?.group_id||e?.metadata!==this.#r?.metadata||e?.workflow_name!==this.#r?.workflow_name){ae.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.#r),JSON.stringify(e));return}this.sendEvent({type:"session.update",session:{type:"realtime",tracing:e}})}updateSessionConfig(e){const n=this.buildSessionPayload(e);this.sendEvent({type:"session.update",session:n})}sendFunctionCallOutput(e,n,s=!0){this.sendEvent({type:"conversation.item.create",item:{type:"function_call_output",output:n,call_id:e.callId}});try{const r=oi.parse({itemId:e.id,previousItemId:e.previousItemId,type:"function_call",status:"completed",arguments:e.arguments,name:e.name,output:n});this.emit("item_update",r)}catch(r){ae.error("Error parsing tool call item",r,e)}s&&this.sendEvent({type:"response.create"})}sendAudio(e,{commit:n=!1}={}){this.sendEvent({type:"input_audio_buffer.append",audio:Uc(e)}),n&&this.sendEvent({type:"input_audio_buffer.commit"})}resetHistory(e,n){const{removals:s,additions:r,updates:i}=Bc(e,n),a=new Set(s.map(u=>u.itemId));for(const u of i)a.add(u.itemId);if(a.size>0)for(const u of a)this.sendEvent({type:"conversation.item.delete",item_id:u});const o=[...r,...i];for(const u of o)if(u.type==="message"){const l={type:"message",role:u.role,content:u.content,id:u.itemId};u.role!=="system"&&u.status&&(l.status=u.status),this.sendEvent({type:"conversation.item.create",item:l})}else u.type==="function_call"&&ae.warn("Function calls cannot be manually added or updated at the moment. Ignoring.")}sendMcpResponse(e,n){this.sendEvent({type:"conversation.item.create",previous_item_id:e.itemId,item:{type:"mcp_approval_response",approval_request_id:e.itemId,approve:n}})}}class Ql extends Xt{options;#e;#t={status:"disconnected",peerConnection:void 0,dataChannel:void 0,callId:void 0};#r;#n=!1;#o=!1;constructor(e={}){if(typeof RTCPeerConnection>"u")throw new Error("WebRTC is not supported in this environment");super(e),this.options=e,this.#e=e.baseUrl??"https://api.openai.com/v1/realtime/calls",this.#r=e.useInsecureApiKey??!1}get callId(){return this.#t.callId}get status(){return this.#t.status}get connectionState(){return this.#t}get muted(){return this.#o}async connect(e){if(this.#t.status==="connected")return;this.#t.status==="connecting"&&ae.warn("Realtime connection already in progress. Please await original promise");const n=e.model??this.currentModel;this.currentModel=n;const s=e.url??this.#e,r=await this._getApiKey(e),i=typeof r=="string"&&r.startsWith("ek_");if(!this.#r&&!i)throw new J("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(a,o)=>{try{const u={...e.initialSessionConfig||{},model:this.currentModel},l=new URL(s);let d=new RTCPeerConnection;const p=d.createDataChannel("oai-events");let h;const f=C=>{C.onconnectionstatechange=()=>{switch(C.connectionState){case"disconnected":case"failed":case"closed":this.close();break}}};f(d),this.#t={status:"connecting",peerConnection:d,dataChannel:p,callId:h},this.emit("connection_change",this.#t.status),p.addEventListener("open",()=>{this.#t={status:"connected",peerConnection:d,dataChannel:p,callId:h},this.updateSessionConfig(u),this.emit("connection_change",this.#t.status),this._onOpen(),a()}),p.addEventListener("error",C=>{this.close(),this._onError(C),o(C)}),p.addEventListener("message",C=>{this._onMessage(C);const{data:k,isGeneric:x}=Vn(C);if(!(!k||x)&&(k.type==="response.created"?this.#n=!0:k.type==="response.done"&&(this.#n=!1),k.type==="session.created")){this._tracingConfig=k.session.tracing;const D=typeof u.tracing>"u"?"auto":u.tracing;this._updateTracingConfig(D)}});const m=this.options.audioElement??document.createElement("audio");m.autoplay=!0,d.ontrack=C=>{m.srcObject=C.streams[0]};const g=this.options.mediaStream??await navigator.mediaDevices.getUserMedia({audio:!0});if(d.addTrack(g.getAudioTracks()[0]),this.options.changePeerConnection){const C=d;d=await this.options.changePeerConnection(d),C!==d&&(C.onconnectionstatechange=null),f(d),this.#t={...this.#t,peerConnection:d}}const _=await d.createOffer();if(await d.setLocalDescription(_),!_.sdp)throw new Error("Failed to create offer");const w=await fetch(l,{method:"POST",body:_.sdp,headers:{"Content-Type":"application/sdp",Authorization:`Bearer ${r}`,"X-OpenAI-Agents-SDK":ri["X-OpenAI-Agents-SDK"]}});h=w.headers?.get("Location")?.split("/").pop(),this.#t={...this.#t,callId:h};const b={type:"answer",sdp:await w.text()};await d.setRemoteDescription(b)}catch(u){this.close(),this._onError(u),o(u)}})}sendEvent(e){if(!this.#t.dataChannel||this.#t.dataChannel.readyState!=="open")throw new Error("WebRTC data channel is not connected. Make sure you call `connect()` before sending events.");this.#t.dataChannel.send(JSON.stringify(e))}mute(e){this.#o=e,this.#t.peerConnection&&this.#t.peerConnection.getSenders().forEach(s=>{s.track&&(s.track.enabled=!e)})}_afterAudioDoneEvent(){this.#n=!1}close(){if(this.#t.dataChannel&&this.#t.dataChannel.close(),this.#t.peerConnection){const e=this.#t.peerConnection;e.onconnectionstatechange=null,e.getSenders().forEach(n=>{n.track?.stop()}),e.close()}this.#t.status!=="disconnected"&&(this.#t={status:"disconnected",peerConnection:void 0,dataChannel:void 0,callId:void 0},this.emit("connection_change",this.#t.status),this._onClose())}interrupt(){this.#n&&(this.sendEvent({type:"response.cancel"}),this.#n=!1),this.sendEvent({type:"output_audio_buffer.clear"})}}const ed=globalThis.WebSocket;class td extends Xt{#e;#t;#r;#n={status:"disconnected",websocket:void 0};#o;#i;#a;_firstAudioTimestamp;_audioLengthMs=0;#s=!1;#u;#l;#c(){this.#i=void 0,this._firstAudioTimestamp=void 0,this._audioLengthMs=0,this.#a=void 0}constructor(e={}){super(e),this.#t=e.url,this.#r=e.url,this.#o=e.useInsecureApiKey??!1,this.#u=e.createWebSocket,this.#l=e.skipOpenEventListeners??!1}getCommonRequestHeaders(){return ri}get status(){return this.#n.status}get connectionState(){return this.#n}get muted(){return null}get currentItemId(){return this.#i}_onAudio(e){this.emit("audio",e)}_afterAudioDoneEvent(){this.#c()}async#p(e,n,s){if(this.#n.websocket){e();return}if(!this.#e)throw new J("API key is not set. Please call `connect()` with an API key first.");if(!this.#e.startsWith("ek_")&&!this.#o)throw new J("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.#u)r=await this.#u({url:this.#t,apiKey:this.#e});else{const a=["realtime","openai-insecure-api-key."+this.#e,qc];r=new ed(this.#t,a)}this.#n={status:"connecting",websocket:r},this.emit("connection_change",this.#n.status);const i=()=>{this.#n={status:"connected",websocket:r},this.emit("connection_change",this.#n.status),this._onOpen(),e()};this.#l===!0?i():r.addEventListener("open",i),r.addEventListener("error",a=>{this._onError(a),this.#n={status:"disconnected",websocket:void 0},this.emit("connection_change",this.#n.status),n(a)}),r.addEventListener("message",a=>{this._onMessage(a);const{data:o,isGeneric:u}=Vn(a);if(!(!o||u)){if(o.type==="response.output_audio.delta"){this.#a=o.content_index,this.#i=o.item_id,this._firstAudioTimestamp===void 0&&(this._firstAudioTimestamp=Date.now(),this._audioLengthMs=0);const l=$c(o.delta),d=this._rawSessionConfig?.audio?.output?.format;if(d&&typeof d=="object"){const h=d.type;if(h==="audio/pcmu"||h==="audio/pcma")this._audioLengthMs+=l.byteLength/8;else if(h==="audio/pcm"){const f=d.rate??24e3;this._audioLengthMs+=l.byteLength/2/f*1e3}else this._audioLengthMs+=l.byteLength/24/2}else typeof d=="string"?d.startsWith("g711_")?this._audioLengthMs+=l.byteLength/8:this._audioLengthMs+=l.byteLength/24/2:this._audioLengthMs+=l.byteLength/24/2;const p={type:"audio",data:l,responseId:o.response_id};this._onAudio(p)}else if(o.type==="input_audio_buffer.speech_started"){const l=this._rawSessionConfig?.audio?.input?.turn_detection?.interrupt_response??!1;this.interrupt(!l)}else if(o.type==="response.created")this.#s=!0;else if(o.type==="response.done")this.#s=!1;else if(o.type==="session.created"){this._tracingConfig=o.session.tracing;const l=typeof s.tracing>"u"?"auto":s.tracing;this._updateTracingConfig(l)}}}),r.addEventListener("close",()=>{this.#n={status:"disconnected",websocket:void 0},this.emit("connection_change",this.#n.status),this._onClose()})}async connect(e){const n=e.model??this.currentModel;this.currentModel=n,this.#e=await this._getApiKey(e);const s=e.callId;let r;e.url?(r=e.url,this.#r=e.url):s?r=`wss://api.openai.com/v1/realtime?call_id=${s}`:this.#r?r=this.#r:r=`wss://api.openai.com/v1/realtime?model=${this.currentModel}`,this.#t=r;const i={...e.initialSessionConfig||{},model:this.currentModel};await new Promise((a,o)=>{this.#p(a,o,i).catch(o)}),await this.updateSessionConfig(i)}sendEvent(e){if(!this.#n.websocket)throw new Error("WebSocket is not connected. Make sure you call `connect()` before sending events.");this.#n.websocket.send(JSON.stringify(e))}close(){this.#n.websocket?.close(),this.#i=void 0,this._firstAudioTimestamp=void 0,this._audioLengthMs=0,this.#a=void 0}mute(e){throw new Error("Mute is not supported for the WebSocket transport. You have to mute the audio input yourself.")}sendAudio(e,n={}){this.#n.status==="connected"&&super.sendAudio(e,n)}_cancelResponse(){this.#s&&(this.sendEvent({type:"response.cancel"}),this.#s=!1)}_interrupt(e,n=!0){if(e<0)return;n&&this._cancelResponse();const s=this._audioLengthMs??Number.POSITIVE_INFINITY,r=Math.max(0,Math.floor(Math.min(e,s)));this.emit("audio_interrupted"),this.sendEvent({type:"conversation.item.truncate",item_id:this.#i,content_index:this.#a,audio_end_ms:r})}interrupt(e=!0){if(!this.#i||typeof this._firstAudioTimestamp!="number")return;const n=Date.now()-this._firstAudioTimestamp;n>=0&&this._interrupt(n,e),this.#c()}}const nd=Symbol("backgroundResult");function sd(t){return typeof t=="object"&&t!==null&&nd in t}function rd(t){return t.type==="function"||t.type==="hosted_tool"&&t.name==="hosted_mcp"}function id(t){if(t.type==="function")return t;if(t.type==="hosted_tool"&&t.name==="hosted_mcp"){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 J(`Invalid tool type: ${t}`)}function ad(){return JSON.parse(JSON.stringify(be))}class Hn extends $t{initialAgent;options;#e;#t;#r;#n;#o=[];#i;#a={};#s=[];#u;#l={};#c=!1;#p=new Map;#d=[];#g=ad();#y=!0;constructor(e,n={}){super(),this.initialAgent=e,this.options=n,typeof n.transport>"u"&&zc()||n.transport==="webrtc"?this.#e=new Ql:n.transport==="websocket"||typeof n.transport>"u"?this.#e=new td:this.#e=n.transport,this.#t=e,this.#n=new nt({...n.context??{},history:this.#s}),this.#o=(n.outputGuardrails??[]).map(Hc),this.#i=Vc(n.outputGuardrailSettings??{}),this.#u=n.historyStoreAudio??!1,this.#y=n.automaticallyTriggerResponseForMcpToolCalls??!0}get transport(){return this.#e}get currentAgent(){return this.#t}get usage(){return this.#n.usage}get context(){return this.#n}get muted(){return this.#e.muted}get history(){return this.#s}get availableMcpTools(){return this.#d}async#f(e){this.#t=e;const n=await this.#t.getEnabledHandoffs(this.#n),s=n.map(o=>o.getHandoffAsFunctionTool()),r=(await this.#t.getAllTools(this.#n)).filter(rd).map(id),i=typeof this.#t.tools<"u"||typeof this.#t.mcpServers<"u",a=n.length>0;this.#r=i||a?[...r,...s]:void 0,this.#v()}async#h(e={}){const n=e??{},s=this.options.config??{},r=await this.#t.getSystemPrompt(this.#n),i=h=>h.audio?.output?.voice,a=this.options.tracingDisabled?null:this.options.workflowName?{workflow_name:this.options.workflowName}:"auto";a!==null&&a!=="auto"?(this.options.groupId&&(a.group_id=this.options.groupId),this.options.traceMetadata&&(a.metadata=this.options.traceMetadata)):(this.options.groupId||this.options.traceMetadata)&&ae.warn("In order to set traceMetadata or a groupId you need to specify a workflowName.");const o=i(n)??i(s),u=n.voice??s.voice,l=typeof o<"u"?o:typeof u<"u"?u:this.#t.voice,p={...{...this.#g??{},...s,...n},instructions:r,voice:l,model:this.options.model,tools:this.#r,tracing:a,prompt:typeof this.#t.prompt=="function"?await this.#t.prompt(this.#n,this.#t):this.#t.prompt};return this.#g=p,p}async getInitialSessionConfig(e={}){return await this.#f(this.initialAgent),this.#h({...this.options.config??{},...e??{}})}static async computeInitialSessionConfig(e,n={},s={}){const r=new Hn(e,n);try{return await r.getInitialSessionConfig(s)}finally{r.close()}}async updateAgent(e){return this.#t.emit("agent_handoff",this.#n,e),this.emit("agent_handoff",this.#n,this.#t,e),await this.#f(e),await this.#e.updateSessionConfig(await this.#h()),e}async#b(e,n){const s=await n.onInvokeHandoff(this.#n,e.arguments);this.#t.emit("agent_handoff",this.#n,s),this.emit("agent_handoff",this.#n,this.#t,s),await this.#f(s),await this.#e.updateSessionConfig(await this.#h());const r=Ks(s);return this.#e.sendFunctionCallOutput(e,r,!0),s}async#m(e,n){this.#n.context.history=JSON.parse(JSON.stringify(this.#s));let s=e.arguments;if(n.parameters&&(Ze(n.parameters)?s=n.parameters.parse(s):s=JSON.parse(s)),await n.needsApproval(this.#n,s,e.callId)){const o=this.context.isToolApproved({toolName:n.name,callId:e.callId});if(o===!1){this.emit("agent_tool_start",this.#n,this.#t,n,{toolCall:e}),this.#t.emit("agent_tool_start",this.#n,n,{toolCall:e});const u="Tool execution was not approved.";this.#e.sendFunctionCallOutput(e,u,!0),this.emit("agent_tool_end",this.#n,this.#t,n,u,{toolCall:e}),this.#t.emit("agent_tool_end",this.#n,n,u,{toolCall:e});return}else if(typeof o>"u"){this.emit("tool_approval_requested",this.#n,this.#t,{type:"function_approval",tool:n,approvalItem:new ee(e,this.#t)});return}}this.emit("agent_tool_start",this.#n,this.#t,n,{toolCall:e}),this.#t.emit("agent_tool_start",this.#n,n,{toolCall:e}),this.#n.context.history=JSON.parse(JSON.stringify(this.#s));const i=await n.invoke(this.#n,e.arguments,{toolCall:e});let a;sd(i)?(a=Ne(i.content),this.#e.sendFunctionCallOutput(e,a,!1)):(a=Ne(i),this.#e.sendFunctionCallOutput(e,a,!0)),this.emit("agent_tool_end",this.#n,this.#t,n,a,{toolCall:e}),this.#t.emit("agent_tool_end",this.#n,n,a,{toolCall:e})}async#w(e){const n=await this.#t.getEnabledHandoffs(this.#n),s=new Map(n.map(o=>[o.toolName,o])),r=await this.#t.getAllTools(this.#n),i=new Map(r.map(o=>[o.name,o])),a=s.get(e.name);if(a)await this.#b(e,a);else{const o=i.get(e.name);if(o&&o.type==="function")await this.#m(e,o);else throw new te(`Tool ${e.name} not found`)}}async#_(e,n,s){if(this.#o.length===0)return;const r={agent:this.#t,agentOutput:e,context:this.#n},a=(await Promise.all(this.#o.map(o=>o.run(r)))).find(o=>o.output.tripwireTriggered);if(a){if(this.#l[n])return;this.#l[n]=!0;const o=new hn(`Output guardrail triggered: ${JSON.stringify(a.output.outputInfo)}`,a);this.emit("guardrail_tripped",this.#n,this.#t,o,{itemId:s}),this.interrupt();const u=Wc(a);this.sendMessage(u);return}}#I(){this.#e.on("*",s=>{if(this.emit("transport_event",s),s.type==="conversation.item.input_audio_transcription.completed")try{const r=s;this.#s=si(this.#s,r,this.#u),this.#n.context.history=this.#s,this.emit("history_updated",this.#s)}catch(r){this.emit("error",{type:"error",error:r})}}),this.#e.on("mcp_tools_listed",({serverLabel:s,tools:r})=>{try{this.#p.set(s,r??[]),this.#v()}catch(i){this.emit("error",{type:"error",error:i})}}),this.#e.on("audio",s=>{this.#c||(this.#c=!0,this.emit("audio_start",this.#n,this.#t)),this.emit("audio",s)}),this.#e.on("turn_started",()=>{this.#c=!1,this.emit("agent_start",this.#n,this.#t),this.#t.emit("agent_start",this.#n,this.#t)}),this.#e.on("turn_done",s=>{const r=s.response.output[s.response.output.length-1],i=Lc(r)??"",a=r?.id??"";this.emit("agent_end",this.#n,this.#t,i),this.#t.emit("agent_end",this.#n,i),this.#_(i,s.response.id,a)}),this.#e.on("audio_done",()=>{this.#c&&(this.#c=!1),this.emit("audio_stopped",this.#n,this.#t)});let e=0,n;this.#e.on("audio_transcript_delta",s=>{try{const r=s.delta,i=s.itemId,a=s.responseId;n!==i&&(n=i,e=0);const u=(this.#a[i]??"")+r;if(this.#a[i]=u,this.#i.debounceTextLength<0)return;const l=Math.floor(u.length/this.#i.debounceTextLength);l>e&&(e=l,this.#_(u,a,i))}catch(r){this.emit("error",{type:"error",error:r})}}),this.#e.on("item_update",s=>{try{const r=!this.#s.some(i=>i.itemId===s.itemId);if(this.#s=si(this.#s,s,this.#u),this.#n.context.history=this.#s,r){const i=this.#s.find(a=>a.itemId===s.itemId);i&&this.emit("history_added",i)}this.emit("history_updated",this.#s)}catch(r){this.emit("error",{type:"error",error:r})}}),this.#e.on("item_deleted",s=>{try{this.#s=this.#s.filter(r=>r.itemId!==s.itemId),this.#n.context.history=this.#s,this.emit("history_updated",this.#s)}catch(r){this.emit("error",{type:"error",error:r})}}),this.#e.on("function_call",async s=>{try{await this.#w(s)}catch(r){ae.error("Error handling function call",r),this.emit("error",{type:"error",error:r})}}),this.#e.on("usage_update",s=>{this.#n.usage.add(s)}),this.#e.on("audio_interrupted",()=>{this.#c&&(this.#c=!1),this.emit("audio_interrupted",this.#n,this.#t)}),this.#e.on("error",s=>{this.emit("error",s)}),this.#e.on("mcp_tool_call_completed",s=>{this.emit("mcp_tool_call_completed",this.#n,this.#t,s),this.#y&&this.#e.sendEvent({type:"response.create"})}),this.#e.on("mcp_approval_request",s=>{this.emit("tool_approval_requested",this.#n,this.#t,{type:"mcp_approval_request",approvalItem:Jc(this.#t,s)})})}#v(){const e=this.#r?.filter(o=>o.type==="mcp"),n=o=>{const u=o.allowed_tools;if(u){if(Array.isArray(u))return u;if(u&&Array.isArray(u.tool_names))return u.tool_names}},s=new Map;for(const o of e){const u=this.#p.get(o.server_label)??[],l=n(o);for(const d of u)l&&!l.includes(d.name)||s.has(d.name)||s.set(d.name,d)}const r=Array.from(s.values()),i=this.#d;(i.length!==r.length||JSON.stringify(i.map(o=>o.name).sort())!==JSON.stringify(r.map(o=>o.name).sort()))&&(this.#d=r,this.emit("mcp_tools_changed",this.#d))}async connect(e){await this.#f(this.initialAgent),this.#I(),await this.#e.connect({apiKey:e.apiKey??this.options.apiKey,model:this.options.model,url:e.url,callId:e.callId,initialSessionConfig:await this.#h(this.options.config)}),this.#s=[],this.emit("history_updated",this.#s)}updateHistory(e){let n;typeof e=="function"?n=e(this.#s):n=e,this.#e.resetHistory(this.#s,n)}sendMessage(e,n={}){this.#e.sendMessage(e,n)}addImage(e,{triggerResponse:n=!0}={}){this.#e.addImage(e,{triggerResponse:n})}mute(e){this.#e.mute(e)}close(){this.#l={},this.#e.close()}sendAudio(e,n={}){this.#e.sendAudio(e,n)}interrupt(){this.#e.interrupt()}async approve(e,n={alwaysApprove:!1}){this.#n.approveTool(e,n);const s=e.toolName??e.rawItem.name,r=this.#t.tools.find(i=>i.name===s);if(r&&r.type==="function"&&e.rawItem.type==="function_call")await this.#m(e.rawItem,r);else if(e.rawItem.type==="hosted_tool_call"){n.alwaysApprove&&ae.warn("Always approving MCP tools is not supported. Use the allowed tools configuration instead.");const i=ii(e);this.#e.sendMcpResponse(i,!0)}else throw new te(`Tool ${s??"unknown"} not found`)}async reject(e,n={alwaysReject:!1}){this.#n.rejectTool(e,n);const s=e.toolName??e.rawItem.name,r=this.#t.tools.find(i=>i.name===s);if(r&&r.type==="function"&&e.rawItem.type==="function_call")await this.#m(e.rawItem,r);else if(e.rawItem.type==="hosted_tool_call"){n.alwaysReject&&ae.warn("Always rejecting MCP tools is not supported. Use the allowed tools configuration instead.");const i=ii(e);this.#e.sendMcpResponse(i,!1)}else throw new te(`Tool ${s??"unknown"} not found`)}}class od{constructor(){this._listeners={}}on(e,n){return this._listeners[e]||(this._listeners[e]=new Set),this._listeners[e].add(n),this}off(e,n){const s=this._listeners[e];return s&&(s.delete(n),s.size===0&&delete this._listeners[e]),this}emit(e,...n){const s=this._listeners[e];if(!s||s.size===0)return!1;for(const r of Array.from(s))try{r(...n)}catch(i){console.error(`BabelbeezClient listener for event "${e}" threw:`,i)}return!0}}const He={DEBUG:0,INFO:1,WARN:2,ERROR:3},di=!0,ud=He.INFO;function E(t,e,...n){const s=He[t]??He.INFO;if(!(s<ud))switch(s){case He.DEBUG:console.debug(`[${t}] ${e}`,...n);break;case He.INFO:console.info(`[${t}] ${e}`,...n);break;case He.WARN:console.warn(`[${t}] ${e}`,...n);break;case He.ERROR:{const r=n.find(a=>a instanceof Error),i=e+(r&&r.message?`: ${r.message}`:"");console.error(`[${t}] ${i}`)}break;default:console.log(`[${t}] ${e}`,...n)}}function pi(t,e){if(!e)return t;t||(t={});for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const s=e[n],r=t[n];typeof s=="number"?t[n]=(typeof r=="number"?r:0)+s:typeof s=="object"&&s!==null&&!Array.isArray(s)&&((typeof r!="object"||r===null||Array.isArray(r))&&(t[n]={}),pi(t[n],s))}return t}const cd=15e3,ld=2e3,dd="https://www.babelbeez.com/initialize-chat";class pd extends od{constructor(e){if(super(),!e||!e.publicChatbotId)throw new Error("BabelbeezClient: publicChatbotId is required.");this.publicChatbotId=e.publicChatbotId;const n=e.proxyInitializeUrl||dd;this.proxyInitializeUrl=n,this.apiBaseUrl=e.apiBaseUrl||new URL(n).origin,this.agent=null,this.session=null,this.currentSystemSettings=null,this.currentChatbotSettings=null,this.currentSessionId=null,this.currentRagSearchUrl=null,this.sessionStartTime=null,this.accumulatedUsage=null,this.hasEndConversationBeenHandled=!1,this.isTerminating=!1,this.isGoodbyeInProgress=!1,this.isUserSpeaking=!1,this.isAssistantSpeaking=!1,this.isHandoffFormOpen=!1,this.inactivityStage=0,this.inactivityStage1TimeoutId=null,this.inactivityStage2TimeoutId=null,this.shouldScheduleStage2OnNextAssistantSilence=!1,this.pendingGoodbyeResolve=null,this.handoffPromiseResolve=null,this.currentHandoffSummaryText=null,this.heartbeatIntervalId=null,this.heartbeatFrequencySeconds=null,this._lastInitData=null,this._lastAssistantMessageId=null,this._lastAssistantTranscript="",this._currentAssistantTranscript="",this._currentUserTranscript=""}async connect(){if(this.session){E("WARN","BabelbeezClient.connect() called while session already active; ignoring.");return}E("INFO","BabelbeezClient.connect: initializing via proxy and connecting RealtimeSession.");try{const e=await this._initializeSessionViaProxy();this._lastInitData=e;const{openai_token:n,system_settings:s,chatbot_config:r,session_id:i,heartbeat_frequency_seconds:a}=e;this.currentSystemSettings=s,this.currentChatbotSettings=r,this.currentSessionId=i,this.heartbeatFrequencySeconds=a,this.currentRagSearchUrl=`${this.apiBaseUrl}/api/perform-rag-search`,E("DEBUG","BabelbeezClient: using RAG search URL",this.currentRagSearchUrl),this._resetAccumulatedUsage(),this._resetInactivityState(),this.isUserSpeaking=!1,this.isAssistantSpeaking=!1,this.isTerminating=!1,this.isGoodbyeInProgress=!1,this.hasEndConversationBeenHandled=!1,this.pendingGoodbyeResolve=null,this.emit("buttonState","loading"),this.agent=this._createVoiceAgent(),this.session=this._createVoiceSession(s,r),await this.session.connect({apiKey:n}),this._attachTransportListeners(),this.sessionStartTime=Date.now(),this.emit("buttonState","active"),this.emit("session:start",{chatbotId:this.publicChatbotId,config:this.currentChatbotSettings}),this._startHeartbeat(),this._resetInactivityState(),E("INFO","BabelbeezClient: Realtime session connected."),setTimeout(()=>{const o=this.currentChatbotSettings?.greetingInstructions;if(o)try{this.session&&this.session.transport&&this.session.transport.sendEvent({type:"response.create",response:{conversation:"none",output_modalities:["audio"],instructions:o,tools:[],input:[{type:"message",role:"user",content:[{type:"input_text",text:"The caller has just connected. Greet them now."}]}],metadata:{source:"greeting"}}})}catch(u){E("WARN","BabelbeezClient: failed to trigger greeting response (post-connect).",u)}},0)}catch(e){let n=`Connect Session failed: ${e?.message||"Unknown error"}`,s="connection_error",r="CONNECTION_FAILED";throw e&&(e.name==="NotAllowedError"||e.name==="PermissionDeniedError")?(n="Microphone access denied. Please allow microphone access in your browser settings.",s="microphone_permission_denied",r="MIC_DENIED"):e&&e.name==="NotFoundError"&&(n="No microphone found. Please ensure a microphone is connected and enabled.",s="microphone_not_found",r="MIC_NOT_FOUND"),E("ERROR",n,e),this.emit("buttonState","error"),this.emit("error",{code:r,message:n,severity:"error",fatal:!0}),await this._finalizeSession(s),e}}async disconnect(e="client_disconnect"){if(E("INFO",`BabelbeezClient.disconnect called. Reason: ${e}`),e==="user_button_click")return this.hardDisconnect(e);if(e==="ai_end_conversation_tool")return this.gracefulDisconnect(e);await this._finalizeSession(e)}async hardDisconnect(e="client_disconnect"){if(E("INFO",`BabelbeezClient.hardDisconnect called. Reason: ${e}`),this.isTerminating){E("DEBUG","hardDisconnect ignored because termination is already in progress.");return}if(!this.session&&!this.currentSessionId){E("DEBUG","hardDisconnect ignored because there is no active session.");return}if(this._clearInactivityTimers(),this.pendingGoodbyeResolve=null,this.isGoodbyeInProgress=!1,this.session)try{await Promise.resolve(this.session.interrupt())}catch(n){E("WARN","Error interrupting session during hardDisconnect.",n)}await this._finalizeSession(e)}async gracefulDisconnect(e="ai_end_conversation_tool"){if(E("INFO",`BabelbeezClient.gracefulDisconnect called. Reason: ${e}`),this.isTerminating){E("DEBUG","gracefulDisconnect ignored because termination is already in progress.");return}if(!this.session&&!this.currentSessionId){E("DEBUG","gracefulDisconnect ignored because there is no active session.");return}this._clearInactivityTimers(),this.pendingGoodbyeResolve=null,this.isGoodbyeInProgress=!1,this.isTerminating||this.emit("buttonState","finalizing");try{this.session&&await Promise.resolve(this.session.interrupt())}catch(n){E("WARN","Error interrupting session during gracefulDisconnect.",n)}await this._playGoodbyeThenFinalize(e)}initializeAudio(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return;const n=this._audioCtx||new e;this._audioCtx=n,n.state==="suspended"&&n.resume().catch(()=>{});try{const s=n.currentTime,r=n.createGain();r.gain.setValueAtTime(1e-4,s),r.connect(n.destination);const i=n.createOscillator();i.type="sine",i.frequency.setValueAtTime(440,s),i.connect(r),i.start(s),i.stop(s+.02),i.onended=()=>{try{i.disconnect(),r.disconnect()}catch{}}}catch{}}catch(e){E("WARN","BabelbeezClient.initializeAudio failed",e)}}async sendUserText(e){if(!this.session||this.isTerminating){E("WARN","Cannot send text message; session is not active or is terminating.");return}const n=(e??"").trim();if(!n){E("DEBUG","sendUserText called with empty/whitespace text; ignoring.");return}if(this.isAssistantSpeaking)try{await this.session.interrupt()}catch(s){E("WARN","Failed to interrupt assistant before sending user text.",s)}this._resetInactivityState();try{await this.session.sendMessage(n),this.emit("transcript",{role:"user",text:n,isFinal:!0})}catch(s){E("ERROR","Failed to send user text message",s)}}async handleHandoffSubmit(e){if(!this.isHandoffFormOpen){E("WARN","handleHandoffSubmit called but no handoff form is open.");return}const{email:n,consent:s}=e||{},r=this.currentHandoffSummaryText||"Summary not available.";try{const i=`${this.apiBaseUrl}/handoff/request`,a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.currentSessionId,email:n,consent:s,summary:r})});if(a.ok)E("INFO","Handoff request submitted successfully.");else{let o=`HTTP ${a.status}`;try{const u=await a.json();u&&u.detail&&(o=u.detail)}catch{}E("ERROR",`Failed to submit handoff request: ${o}`),this.emit("error",{code:"HANDOFF_FAILED",message:"Failed to submit handoff request. Please try again later.",severity:"error",fatal:!1})}}catch(i){E("ERROR","Network or unexpected error submitting handoff request.",i),this.emit("error",{code:"HANDOFF_FAILED",message:"Network error submitting handoff request. Please try again later.",severity:"error",fatal:!1})}finally{this.isHandoffFormOpen=!1,this._resetInactivityState(),this.isTerminating||this._setSessionMuted(!1,"handoff_form"),this.emit("handoff:hide",{outcome:"email_submitted"}),this.handoffPromiseResolve&&(this.handoffPromiseResolve("email_submitted"),this.handoffPromiseResolve=null)}try{this.session&&await this.session.sendMessage("The user has submitted their contact details. Confirm that their request was received and that a team member will follow up. See if there's anything else you can help them with in the meantime.")}catch(i){E("WARN","Failed to send post-handoff confirmation message.",i)}}async handleHandoffCancel(e={}){const{viaWhatsapp:n}=e;if(!this.isHandoffFormOpen){E("WARN","handleHandoffCancel called but no handoff form is open.");return}this.isHandoffFormOpen=!1,this._resetInactivityState(),this.isTerminating||this._setSessionMuted(!1,"handoff_form");const s=n?"whatsapp_submitted":"cancelled";if(this.emit("handoff:hide",{outcome:s}),this.handoffPromiseResolve&&(this.handoffPromiseResolve(s),this.handoffPromiseResolve=null),n){await this._playGoodbyeThenFinalize("handoff_whatsapp");return}try{this.session&&await this.session.sendMessage("The user changed their mind and no longer wishes to fill out the form right now. See if there's anything else you can help them with.")}catch(r){E("WARN","Failed to send handoff cancellation message.",r)}}async _initializeSessionViaProxy(){E("INFO","BabelbeezClient: Initializing session via proxy /initialize-chat...");const e=typeof navigator<"u"&&(navigator.language||navigator.userLanguage)||null,n=await fetch(this.proxyInitializeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({public_chatbot_id:this.publicChatbotId,browser_language:e})});if(!n.ok){let r=`HTTP error ${n.status}: ${n.statusText}`;try{const i=await n.json();i&&i.detail&&(r=i.detail)}catch{}throw E("ERROR","BabelbeezClient: /initialize-chat failed",r),new Error(r)}const s=await n.json();if(!s.session_id||!s.openai_token||!s.system_settings||!s.chatbot_config||s.heartbeat_frequency_seconds===void 0)throw E("ERROR","BabelbeezClient: Invalid response structure from /initialize-chat.",s?{...s,openai_token:"***"}:null),new Error("Incomplete session details received from server.");return E("INFO","BabelbeezClient: Session initialized via proxy.",{session_id:s.session_id,heartbeat_frequency_seconds:s.heartbeat_frequency_seconds}),s}_resetAccumulatedUsage(){this.accumulatedUsage={total_tokens:0,input_tokens:0,output_tokens:0,input_token_details:{cached_tokens:0,text_tokens:0,audio_tokens:0,cached_tokens_details:{text_tokens:0,audio_tokens:0}},output_token_details:{text_tokens:0,audio_tokens:0}},E("DEBUG","BabelbeezClient: accumulated token usage reset.")}_setSessionMuted(e,n=""){try{this.session&&this.session.transport&&typeof this.session.transport.mute=="function"&&(this.session.transport.mute(e),E("DEBUG",`Session ${e?"muted":"unmuted"}${n?` (${n})`:""}.`))}catch{}}_clearInactivityTimers(){this.inactivityStage1TimeoutId&&(clearTimeout(this.inactivityStage1TimeoutId),this.inactivityStage1TimeoutId=null),this.inactivityStage2TimeoutId&&(clearTimeout(this.inactivityStage2TimeoutId),this.inactivityStage2TimeoutId=null)}_resetInactivityState(){this.inactivityStage=0,this.shouldScheduleStage2OnNextAssistantSilence=!1,this._clearInactivityTimers()}async _sendInactivityEnquiry(){const e=(this.currentChatbotSettings?.inactivityTimeoutMs||0)/1e3;E("INFO",`User inactive for ${e}s. Sending enquiry.`),this.shouldScheduleStage2OnNextAssistantSilence=!0;try{this.currentSystemSettings?.inactivityInstructions&&this.session&&await this.session.sendMessage(this.currentSystemSettings.inactivityInstructions)}catch(n){E("ERROR","Failed to send inactivity enquiry; ending session.",n),await this._finalizeSession("inactivity_enquiry_failed")}}async _playGoodbyeThenFinalize(e){if(this.isTerminating){await this._finalizeSession(e);return}this._clearInactivityTimers();const n=this.currentSystemSettings?.goodbyeInstructions?.trim();if(!this.session||!n){E("INFO","No goodbyeInstructions configured or no active session; finalizing immediately."),await this._finalizeSession(e);return}this.isGoodbyeInProgress=!0,E("INFO","Playing goodbye message before finalizing session.");const s=new Promise(a=>{this.pendingGoodbyeResolve=a});try{this._setSessionMuted(!0,"goodbye"),await this.session.sendMessage(n)}catch(a){E("WARN","Failed to send goodbye message; finalizing immediately.",a),this.pendingGoodbyeResolve=null,this._setSessionMuted(!1,"goodbye"),this.isGoodbyeInProgress=!1,await this._finalizeSession(e);return}const r=15e3,i=new Promise(a=>setTimeout(a,r));await Promise.race([s,i]),this.pendingGoodbyeResolve=null,this._setSessionMuted(!1,"goodbye"),this.isGoodbyeInProgress=!1,await this._finalizeSession(e)}_createVoiceAgent(){const e=this.currentSystemSettings?.system_prompt?`${this.currentSystemSettings.system_prompt}
|
|
13
13
|
|
|
14
|
-
${
|
|
15
|
-
`)}catch(
|
|
14
|
+
${this.currentChatbotSettings?.instructions||""}`.trim():this.currentChatbotSettings?.instructions||"",n=this,s=tt({name:"perform_rag_search",description:this.currentSystemSettings?.rag_search_description||"Searches the knowledge base for relevant context.",parameters:y({query:c()}),async execute({query:u}){if(E("INFO",`Tool perform_rag_search called with query: "${u}"`),n._resetInactivityState(),!n.currentRagSearchUrl||!n.publicChatbotId)return E("ERROR","RAG search URL or publicChatbotId not configured; returning fallback context."),"Knowledge search is temporarily unavailable.";const l=n.isAssistantSpeaking;n.isAssistantSpeaking=!0,n.emit("buttonState","rag-retrieval");try{const d=await fetch(n.currentRagSearchUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:u,public_chatbot_id:n.publicChatbotId})});if(!d.ok){let f=`RAG search failed: ${d.status} ${d.statusText}`;try{const m=await d.json();m&&m.detail&&(f=m.detail)}catch{}return E("ERROR",f),"Knowledge search failed; please answer based on your existing knowledge."}const h=(await d.json()).context||"";return E("INFO",`RAG search succeeded. Context length: ${h.length}`),h||"No additional knowledge was found."}catch(d){return E("ERROR","Network or unexpected error during RAG search.",d),"Knowledge search failed due to a network error."}finally{n.isAssistantSpeaking=l,n.emit("buttonState","active")}}}),r=tt({name:"request_human_handoff",description:"Escalate to a human staff member via contact form. Provide a concise summary_text.",parameters:y({summary_text:c(),announcement:c()}),async execute({summary_text:u,announcement:l}){E("INFO","Tool request_human_handoff called."),n._resetInactivityState();const d=l||"Please fill out the form so that I can connect you to a staff member to follow up";try{n.session&&await n.session.sendMessage(d)}catch(f){E("WARN","Failed to send handoff announcement message.",f)}n.isHandoffFormOpen=!0,n._setSessionMuted(!0,"handoff_form");let p=null;const h=n.currentChatbotSettings?.handoff_whatsapp_number;if(h){const f=String(h).replace(/\D+/g,"");f&&(p=`https://wa.me/${f}?text=${encodeURIComponent(u||"Summary not available.")}`)}return n.currentHandoffSummaryText=u||"Summary not available.",n.emit("handoff:show",{summaryText:n.currentHandoffSummaryText,waLink:p}),await new Promise(f=>{n.handoffPromiseResolve=f}).then(f=>f==="whatsapp_submitted"?"User chose WhatsApp handoff.":f==="email_submitted"?"Handoff request submitted successfully.":"Handoff flow completed or cancelled by the user.")}}),i=tt({name:"end_conversation",description:"End the conversation when the user clearly wants to stop. Call this tool instead of saying goodbye yourself so the client can trigger the configured localized goodbye and then close the session.",parameters:y({}),async execute(){return E("INFO","Tool end_conversation called by AI."),n._resetInactivityState(),n.hasEndConversationBeenHandled?(E("DEBUG","end_conversation already handled; ignoring subsequent call."),"Conversation is already ending."):(n.hasEndConversationBeenHandled=!0,(async()=>await n.gracefulDisconnect("ai_end_conversation_tool"))(),"OK")}}),a=[s,r,i];return new Gc({name:"Assistant",instructions:e,tools:a})}_createVoiceSession(e,n){const s=e?.model;if(!s)throw new Error("Missing systemSettings.model for RealtimeSession.");const r={type:n?.semanticVadEnabled?"semantic_vad":"server_vad",eagerness:n?.eagerness||"medium",createResponse:!0,interruptResponse:!0};return new Hn(this.agent,{model:s,config:{inputAudioFormat:"pcm16",outputAudioFormat:"pcm16",inputAudioTranscription:{model:"gpt-4o-mini-transcribe"},turnDetection:r}})}_attachTransportListeners(){this.session&&(this.session.on("history_updated",e=>{try{const n=Array.isArray(e)?e:this.session.history||[],s=n[n.length-1];if(!s||s.type!=="message"||s.role!=="assistant")return;const r=s.id||null;r&&r!==this._lastAssistantMessageId&&(this._lastAssistantMessageId=r,this._lastAssistantTranscript="");const i=s.content||[],a=[];for(const d of i)if(d&&d.type==="output_audio"&&typeof d.transcript=="string"){const p=d.transcript.trim();p&&a.push(p)}const o=a.join(" ").trim();if(!o)return;const u=this._lastAssistantTranscript||"";let l=o;if(u&&o.startsWith(u)&&(l=o.slice(u.length)),!l)return;this._lastAssistantTranscript=o,this.emit("transcript",{role:"agent",text:l,isFinal:!1})}catch{}}),this.session.transport&&(this.session.transport.on("*",e=>{if(e){if(e.type&&typeof e.type=="string"&&e.type.startsWith("response."),e.type==="response.done"&&e.response?.usage&&(this.accumulatedUsage=pi(this.accumulatedUsage,e.response.usage),E("DEBUG","Accumulated token usage from response.done.",this.accumulatedUsage)),e.type==="input_audio_buffer.speech_started"){this.isUserSpeaking=!0,this._currentUserTranscript="",this._resetInactivityState();return}if(e.type==="conversation.item.input_audio_transcription.delta"){if(this.isUserSpeaking=!0,this._resetInactivityState(),typeof e.delta=="string"&&e.delta){this._currentUserTranscript+=e.delta;const n=this._currentUserTranscript;this.emit("transcript",{role:"user",text:n,isFinal:!1})}return}if(e.type==="input_audio_buffer.speech_stopped"||e.type==="conversation.item.input_audio_transcription.completed"||e.type==="conversation.item.input_audio_transcription.failed"){this.isUserSpeaking=!1,e.type==="conversation.item.input_audio_transcription.completed"&&this._currentUserTranscript&&this.emit("transcript",{role:"user",text:this._currentUserTranscript,isFinal:!0}),this._currentUserTranscript="";return}if(e.type==="output_audio_buffer.started"){this.isAssistantSpeaking=!0,this._clearInactivityTimers(),this._currentAssistantTranscript="",this.isTerminating||this.emit("buttonState","speaking");return}if(e.type==="output_audio_buffer.stopped"||e.type==="output_audio_buffer.cleared"){const n=!!this.pendingGoodbyeResolve;this.isAssistantSpeaking=!1;const s=this._lastAssistantTranscript||this._currentAssistantTranscript||"";if(s&&this.emit("transcript",{role:"agent",text:s,isFinal:!0}),this._lastAssistantTranscript="",this._currentAssistantTranscript="",this.pendingGoodbyeResolve&&(this.pendingGoodbyeResolve(),this.pendingGoodbyeResolve=null),!this.isGoodbyeInProgress&&!n&&!this.isTerminating&&this.emit("buttonState","active"),!this.isTerminating&&this.currentChatbotSettings&&!this.isHandoffFormOpen){const r=this.currentChatbotSettings?.inactivityTimeoutMs||0;if(this.inactivityStage===0&&r>0){this._clearInactivityTimers();const i=r+ld;this.inactivityStage1TimeoutId=setTimeout(()=>{this.inactivityStage=1,E("INFO","[INACTIVITY] Stage 1 threshold reached; sending enquiry."),this._sendInactivityEnquiry()},i)}else this.inactivityStage===1&&this.shouldScheduleStage2OnNextAssistantSilence&&(this._clearInactivityTimers(),this.inactivityStage2TimeoutId=setTimeout(()=>{E("INFO","[INACTIVITY] Stage 2 threshold reached; auto-ending session with goodbye."),this._playGoodbyeThenFinalize("inactivity_timeout")},cd),this.shouldScheduleStage2OnNextAssistantSilence=!1)}return}}}),this.session.transport.on("audio_transcript_delta",e=>{const n=e?.delta,s=n?.delta||n?.transcript;typeof s=="string"&&s&&(E("INFO","Transcript event",{source:"agent_audio_delta",role:"agent",len:s.length}),this._currentAssistantTranscript+=s,this.emit("transcript",{role:"agent",text:s,isFinal:!1}))})))}_buildRawHistoryFromSession(){try{const e=this.session?.history||[],n=[];for(const s of e){if(!s||s.type!=="message"||s.role!=="user"&&s.role!=="assistant")continue;const r=s.role==="user"?"User":"Assistant",i=[],a=s.content||[];for(const u of a)if((u.type==="input_audio"||u.type==="output_audio")&&typeof u.transcript=="string"){const l=u.transcript.trim();l&&i.push(l)}const o=i.join(" ").trim();o&&n.push(`${r}: ${o}`)}return n.join(`
|
|
15
|
+
`)}catch(e){return E("ERROR","Failed to build raw_history from session history.",e),""}}_startHeartbeat(){if(this.heartbeatIntervalId){E("WARN","BabelbeezClient: Heartbeat already running.");return}!this.heartbeatFrequencySeconds&&this._lastInitData&&this._lastInitData.heartbeat_frequency_seconds!=null&&(this.heartbeatFrequencySeconds=this._lastInitData.heartbeat_frequency_seconds);const e=this.heartbeatFrequencySeconds;if(!e||e<=0){E("WARN","BabelbeezClient: Cannot start heartbeat, invalid or missing frequency.",e);return}E("INFO",`BabelbeezClient: Starting heartbeat every ${e} seconds.`);const n=()=>this._sendHeartbeat();this.heartbeatIntervalId=setInterval(n,e*1e3)}_stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null,E("INFO","BabelbeezClient: Heartbeat stopped."))}async _sendHeartbeat(){if(!this.currentSessionId){E("WARN","BabelbeezClient: Cannot send heartbeat, no active session ID."),this._stopHeartbeat();return}try{const e=this.proxyInitializeUrl.replace("/initialize-chat","/heartbeat");E("DEBUG","BabelbeezClient: Sending heartbeat",{session_id:this.currentSessionId,heartbeatUrl:e});const n={session_id:this.currentSessionId};(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok}catch(e){E("ERROR","BabelbeezClient: Error sending heartbeat.",e)}}async _finalizeSession(e){if(this.isTerminating){E("DEBUG",`BabelbeezClient._finalizeSession called while already terminating (reason: ${e}).`);return}this.isTerminating=!0,this.pendingGoodbyeResolve=null,this.isGoodbyeInProgress=!1,this._clearInactivityTimers(),this._stopHeartbeat();const n=this._buildRawHistoryFromSession();if(this.accumulatedUsage){const r=this.accumulatedUsage.input_tokens||0,i=this.accumulatedUsage.output_tokens||0,a=r+i;(!this.accumulatedUsage.total_tokens||this.accumulatedUsage.total_tokens<a)&&(this.accumulatedUsage.total_tokens=a)}E("INFO",`Finalizing session (reason: ${e}). raw_history length=${n.length}`);const s={usage:this.accumulatedUsage,client_reason:e,raw_history:n};this.emit("buttonState","idle"),this.emit("session:end",{reason:e});try{if(this.currentSessionId){const r=this.proxyInitializeUrl.replace("/initialize-chat","/end-chat"),i={session_id:this.currentSessionId,token_usage:s.usage||void 0,raw_history:s.raw_history||void 0,client_reason:s.client_reason||void 0};E("DEBUG","BabelbeezClient: Sending /end-chat beacon",{...i,raw_history:i.raw_history?`[len=${i.raw_history.length}]`:void 0}),await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0})}}catch(r){E("ERROR","BabelbeezClient: Error sending /end-chat beacon.",r)}try{this.session&&(await this.session.close(),E("DEBUG","BabelbeezClient: RealtimeSession closed."))}catch(r){E("WARN","BabelbeezClient: Error closing RealtimeSession.",r)}this.session=null,this.agent=null,this.currentSystemSettings=null,this.currentChatbotSettings=null,this.currentSessionId=null,this.currentRagSearchUrl=null,this.sessionStartTime=null,this._resetInactivityState(),this.isUserSpeaking=!1,this.isAssistantSpeaking=!1,this._resetAccumulatedUsage(),this.hasEndConversationBeenHandled=!1,this.pendingGoodbyeResolve=null,this.isGoodbyeInProgress=!1,this.isTerminating=!1}}Ke.BabelbeezClient=pd,Object.defineProperty(Ke,Symbol.toStringTag,{value:"Module"})}));
|