@babelbeez/sdk 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +208 -0
- package/dist/babelbeez-sdk.d.ts +167 -0
- package/dist/babelbeez-sdk.js +12877 -0
- package/dist/babelbeez-sdk.umd.cjs +15 -0
- package/package.json +22 -0
|
@@ -0,0 +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:w,maximum:v,format:N,patterns:x,contentEncoding:A}=e._zod.bag;if(typeof w=="number"&&(h.minLength=w),typeof v=="number"&&(h.maxLength=v),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:w,maximum:v,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 w=="number"&&(h.minimum=w,typeof D=="number"&&(D>=w?delete h.minimum:delete h.exclusiveMinimum)),typeof A=="number"&&(h.exclusiveMaximum=A),typeof v=="number"&&(h.maximum=v,typeof A=="number"&&(A<=v?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:w,maximum:v}=e._zod.bag;typeof w=="number"&&(h.minItems=w),typeof v=="number"&&(h.maxItems=v),h.type="array",h.items=this.process(r.element,{..._,path:[..._.path,"items"]});break}case"object":{const h=y;h.type="object",h.properties={};const w=r.shape;for(const x in w)h.properties[x]=this.process(w[x],{..._,path:[..._.path,"properties",x]});const v=new Set(Object.keys(w)),N=new Set([...v].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((w,v)=>this.process(w,{..._,path:[..._.path,"anyOf",v]}));break}case"intersection":{const h=y,w=this.process(r.left,{..._,path:[..._.path,"allOf",0]}),v=this.process(r.right,{..._,path:[..._.path,"allOf",1]}),N=A=>"allOf"in A&&Object.keys(A).length===1,x=[...N(w)?w.allOf:[w],...N(v)?v.allOf:[v]];h.allOf=x;break}case"tuple":{const h=y;h.type="array";const w=r.items.map((x,A)=>this.process(x,{..._,path:[..._.path,"prefixItems",A]}));if(this.target==="draft-2020-12"?h.prefixItems=w:h.items=w,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:v,maximum:N}=e._zod.bag;typeof v=="number"&&(h.minItems=v),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,w=ss(r.entries);w.every(v=>typeof v=="number")&&(h.type="number"),w.every(v=>typeof v=="string")&&(h.type="string"),h.enum=w;break}case"literal":{const h=y,w=[];for(const v of r.values)if(v===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(v))}else w.push(v);if(w.length!==0)if(w.length===1){const v=w[0];h.type=v===null?"null":typeof v,h.const=v}else w.every(v=>typeof v=="number")&&(h.type="number"),w.every(v=>typeof v=="string")&&(h.type="string"),w.every(v=>typeof v=="boolean")&&(h.type="string"),w.every(v=>v===null)&&(h.type="null"),h.enum=w;break}case"file":{const h=y,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:N,mime:x}=e._zod.bag;v!==void 0&&(w.minLength=v),N!==void 0&&(w.maxLength=N),x?x.length===1?(w.contentMediaType=x[0],Object.assign(h,w)):h.anyOf=x.map(A=>({...w,contentMediaType:A})):Object.assign(h,w);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,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=w.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 v=`#/${h}/`,N=y[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:v+N}},o=y=>{if(y[1].schema.$ref)return;const h=y[1],{ref:w,defId:v}=i(y);h.def={...h.schema},v&&(h.defId=v);const N=h.schema;for(const x in N)delete N[x];N.$ref=w};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>
|
|
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 v=(d=s.external.registry.get(y[0]))==null?void 0:d.id;if(e!==y[0]&&v){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 w=this.seen.get(y),v=w.def??w.schema,N={...v};if(w.ref===null)return;const x=w.ref;if(w.ref=null,x){a(x,h);const A=this.seen.get(x).schema;A.$ref&&h.target==="draft-7"?(v.allOf=v.allOf??[],v.allOf.push(A)):(Object.assign(v,A),Object.assign(v,N))}w.isParent||this.override({zodSchema:y,jsonSchema:v,path:w.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,b=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[p]==="$"){i+=`($|(?=[\r
|
|
5
|
+
]))`;continue}}if(s.s&&r[p]==="."){i+=a?`${r[p]}\r
|
|
6
|
+
`:`[${r[p]}\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 w=y,v=Number(new Date),N=v-(m||v);w.diff=N,w.prev=m,w.curr=v,m=v,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(w,L),h.splice(x,1),x--}return D}),s.formatArgs.call(w,h),(w.log||s.log).apply(w,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}}b({name:f(),description:f().optional(),inputSchema:b({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,w=y.length>0?y.includes(g.name):!1;if(!h||w){w?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=b({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("*"),w=[...p?[p]:[],...y?Array.from(y):[],...h?Array.from(h):[]];await Promise.allSettled(w.map(v=>Promise.resolve().then(()=>v(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 w=new Sd(a??{}),v=typeof p=="function"||d.size>0,N=v?await w.run(this,T.input,{context:y,...u??{},stream:!0}):await w.run(this,T.input,{context:y,...u??{}}),x={agent:this,toolCall:h==null?void 0:h.toolCall};if(v){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=b({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(b({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(b({id:f().describe("OpenAI file ID")})).or(b({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(b({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=b({data:Ye([f(),li(Uint8Array)]).describe("Base64 image data, or raw bytes that will be base64 encoded automatically."),mediaType:f().optional()}),tl=b({url:f().describe("Publicly accessible URL pointing to the image content")}),nl=b({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=b({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=b({url:f().describe("Publicly accessible URL for the file content"),filename:f().optional()}),al=b({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",[b({type:I("screenshot")}),b({type:I("click"),x:E(),y:E(),button:pe(["left","right","wheel","back","forward"])}),b({type:I("double_click"),x:E(),y:E()}),b({type:I("scroll"),x:E(),y:E(),scroll_x:E(),scroll_y:E()}),b({type:I("type"),text:f()}),b({type:I("wait")}),b({type:I("move"),x:E(),y:E()}),b({type:I("keypress"),keys:J(f())}),b({type:I("drag"),path:J(b({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=b({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",[b({type:I("timeout")}),b({type:I("exit"),exitCode:E().int().nullable()})]),bl=b({stdout:f(),stderr:f(),outcome:vl}).passthrough(),sa=Ee.extend({type:I("shell_call_output"),callId:f(),maxOutputLength:E().optional(),output:J(bl)}),wl=b({type:I("create_file"),path:f(),diff:f()}),Il=b({type:I("update_file"),path:f(),diff:f()}),Sl=b({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=b({inputTokens:E(),outputTokens:E(),totalTokens:E(),inputTokensDetails:se(f(),E()).optional(),outputTokensDetails:se(f(),E()).optional(),endpoint:f().optional()}),Cl=b({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 w;const r=[],i=[],o=[],a=[],u=[],l=[],p=[],d=[],m=new Map(s.map(v=>[v.toolName,v])),g=new Map(t.filter(v=>v.type==="function").map(v=>[v.name,v])),_=t.find(v=>v.type==="computer"),T=t.find(v=>v.type==="shell"),y=t.find(v=>v.type==="apply_patch"),h=new Map(t.filter(v=>{var N;return v.type==="hosted_tool"&&((N=v.providerData)==null?void 0:N.type)==="mcp"}).map(v=>v).map(v=>[v.providerData.server_label,v]));for(const v of n.output){if(v.type==="message")v.role==="assistant"&&r.push(new As(v,e));else if(v.type==="hosted_tool_call"){r.push(new et(v,e));const x=v.name;if(d.push(x),((w=v.providerData)==null?void 0:w.type)==="mcp_approval_request"||v.name==="mcp_approval_request"){const A=v.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(v.type==="reasoning")r.push(new mr(v,e));else if(v.type==="computer_call"){if(r.push(new et(v,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:v,computer:_})}else if(v.type==="shell_call"){if(r.push(new et(v,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:v,shell:T})}else if(v.type==="apply_patch_call"){if(r.push(new et(v,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:v,applyPatch:y})}if(v.type!=="function_call")continue;d.push(v.name);const N=m.get(v.name);if(N)r.push(new gr(v,e)),i.push({toolCall:v,handoff:N});else{const x=g.get(v.name);if(!x)throw nt({message:`Tool ${v.name} not found in agent ${e.name}.`,data:{tool_name:v.name,agent_name:e.name}}),new Se(`Tool ${v.name} not found in agent ${e.name}.`);r.push(new et(v,e)),o.push({toolCall:v,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",[b({type:I("next_step_handoff"),newAgent:H()}),b({type:I("next_step_final_output"),output:f()}),b({type:I("next_step_run_again")}),b({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,w=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),w.add(D),p.push({type:"hosted_mcp_tool_approval",tool:x.mcpTool,runItem:x.requestItem}),T(x.requestItem)}const v=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?w.has(D):!1}return!1}),N=await ga({agent:n,runner:i,state:o,functionResults:p,originalInput:e,newResponse:s,preStepItems:v,newItems:g});return N||new ze(e,s,v,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),w=h.length>0?Ki(h[h.length-1].rawItem):void 0;if(typeof w>"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:w});if(n.outputType!=="text"&&w){const{parser:L}=Qs(n.outputType,"final_output"),[fe]=await le(()=>L(w));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:w})}}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.",w={stdout:"",stderr:h,outcome:{type:"exit",exitCode:null}};o.push(new Le({type:"shell_call_output",callId:l.callId,output:[w]},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 w=wr(h);if(Oa(_,w,h)){Ea(m,w),T.push(h);continue}if(Oa(g,w,h)){Ea(d,w);continue}const v=d.get(w)??0;if(v>0){d.set(w,v-1);continue}const N=m.get(w)??0;if(N>0){m.set(w,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=b({name:f()}),Ra=b({object:I("trace.span"),id:f(),trace_id:f(),parent_id:f().nullable(),started_at:f().nullable(),ended_at:f().nullable(),error:b({message:f(),data:se(f(),H()).optional()}).nullable(),span_data:se(f(),H())}).extend({previous_span:ru(()=>Ra).optional()}),gd=b({inputTokens:E(),outputTokens:E(),totalTokens:E(),inputTokensDetails:se(f(),E()).optional(),outputTokensDetails:se(f(),E()).optional(),endpoint:f().optional()}),Na=b({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=b({usage:Na,output:J(hr),responseId:f().optional(),providerData:se(f(),H()).optional()}),Da=ve("type",[b({type:I("message_output_item"),rawItem:Ss,agent:Be}),b({type:I("tool_call_item"),rawItem:xl.or(Sn),agent:Be}),b({type:I("tool_call_output_item"),rawItem:Ts,agent:Be,output:f()}),b({type:I("reasoning_item"),rawItem:fr,agent:Be}),b({type:I("handoff_call_item"),rawItem:Tn,agent:Be}),b({type:I("handoff_output_item"),rawItem:Ts,sourceAgent:Be,targetAgent:Be}),b({type:I("tool_approval_item"),rawItem:Tn.or(Sn).or(xs).or(ks),agent:Be,toolName:f().optional()})]),yd=b({object:I("trace"),id:f(),workflow_name:f(),group_id:f().nullable(),metadata:se(f(),H())}),_d=b({newItems:J(Da),toolsUsed:J(f()),handoffs:J(b({toolCall:H(),handoff:H()})),functions:J(b({toolCall:H(),tool:H()})),computerActions:J(b({toolCall:H(),computer:H()})),shellActions:J(b({toolCall:H(),shell:H()})).optional(),applyPatchActions:J(b({toolCall:H(),applyPatch:H()})).optional(),mcpApprovalRequests:J(b({requestItem:b({rawItem:b({type:I("hosted_tool_call"),name:f(),arguments:f().optional(),status:f().optional(),output:f().optional(),providerData:se(f(),H()).nullable().optional()})}),mcpTool:b({type:I("hosted_tool"),name:I("hosted_mcp"),providerData:se(f(),H())})})).optional()}),Ma=b({tripwireTriggered:St(),outputInfo:H()}),vd=b({guardrail:b({type:I("input"),name:f()}),output:Ma}),bd=b({guardrail:b({type:I("output"),name:f()}),agentOutput:H(),agent:Be,output:Ma}),Fa=b({$schemaVersion:md,currentTurn:E(),currentAgent:Be,originalInput:f().or(J(kl)),modelResponses:J(Pa),context:b({usage:Na,approvals:se(f(),b({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 w=s;if(!(w instanceof tt)){if(d&&Array.isArray(w)&&!o)throw new re("RunConfig.sessionInputCallback must be provided when using session history with list inputs.");const x=await dd(w,d,o,{includeHistoryInPreparedInput:!p,preserveDroppedNewItems:p});if(p&&d){const A=x.sessionItems;A&&A.length>0?w=A:w=x.preparedInput}else w=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 v;if(d&&!p){let x=!1;v=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,w,l,v,y);const x=await z(this,oe,go).call(this,t,w,l,y);return d&&!p&&await cd(d,h(),x),x};return w instanceof tt&&w._trace?Ed(w._trace,async()=>(w._currentAgentSpan&&Tr(w._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 w=fa(a._lastTurnResponse,a._currentAgent,h.tools,h.handoffs);a._lastProcessedResponse=w;const v=await ma(a._currentAgent,a._originalInput,a._generatedItems,a._lastTurnResponse,a._lastProcessedResponse,this,a);a._toolUseTracker.addToolUse(a._currentAgent,a._lastProcessedResponse.toolsUsed),a._originalInput=v.originalInput,a._generatedItems=v.generatedItems,v.nextStep.type==="next_step_run_again"&&(a._currentTurnPersistedItemCount=0),a._currentStep=v.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 w=await ha(t.state._currentAgent,t.state._originalInput,t.state._generatedItems,t.state._lastTurnResponse,t.state._lastProcessedResponse,this,t.state);if(wa(t,w),t.state._toolUseTracker.addToolUse(t.state._currentAgent,t.state._lastProcessedResponse.toolsUsed),t.state._originalInput=w.originalInput,t.state._generatedItems=w.generatedItems,w.nextStep.type==="next_step_interruption"){t.state._currentStep=w.nextStep;return}if(w.nextStep.type==="next_step_run_again"){m=!0,t.state._currentStep=void 0;continue}m=!1,t.state._currentStep=w.nextStep}if(t.state._currentStep.type==="next_step_run_again"){const w=await Za(t.state),v=r&&m;if(m=!1,v||(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&&!v){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,w,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,w=(o==null?void 0:o.conversationId)??s.conversationId;return{...r,model:u,explictlyModelSet:l,modelSettings:p,modelInput:g,prompt:m,previousResponseId:h,conversationId:w}};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 w=Ot(y),v=Cd(a,w);if(v)return l(v),v;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`
|
|
8
|
+
⚠️ Your last answer was blocked.
|
|
9
|
+
Failed Guardrail Reason: ${n.guardrail.policyHint}.
|
|
10
|
+
Failure Details: ${JSON.stringify(n.output.outputInfo??{})}.
|
|
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}}b({itemId:f()});const so=ve("role",[b({itemId:f(),previousItemId:f().nullable().optional(),type:I("message"),role:I("system"),content:J(b({type:I("input_text"),text:f()}))}),b({itemId:f(),previousItemId:f().nullable().optional(),type:I("message"),role:I("user"),status:pe(["in_progress","completed"]),content:J(b({type:I("input_text"),text:f()}).or(b({type:I("input_audio"),audio:f().nullable().optional(),transcript:f().nullable()})))}),b({itemId:f(),previousItemId:f().nullable().optional(),type:I("message"),role:I("assistant"),status:pe(["in_progress","completed","incomplete"]),content:J(b({type:I("output_text"),text:f()}).or(b({type:I("output_audio"),audio:f().nullable().optional(),transcript:f().nullable().optional()})))})]),ro=b({itemId:f(),previousItemId:f().nullable().optional(),type:I("function_call"),status:pe(["in_progress","completed","incomplete"]),arguments:f(),name:f(),output:f().nullable()}),io=b({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=b({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=b({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:b({output:b({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:b({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=b({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=b({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(b({name:f(),description:f(),input_schema:se(H()).optional()}).passthrough()).optional()}).passthrough(),rp=b({type:I("conversation.created"),event_id:f(),conversation:b({id:f().optional(),object:I("realtime.conversation").optional()})}),ip=b({type:I("conversation.item.added"),event_id:f(),item:Qt,previous_item_id:f().nullable().optional()}),ap=b({type:I("conversation.item.done"),event_id:f(),item:Qt,previous_item_id:f().nullable().optional()}),op=b({type:I("conversation.item.deleted"),event_id:f(),item_id:f()}),up=b({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:b({type:I("tokens"),total_tokens:E(),input_tokens:E(),input_token_details:b({text_tokens:E(),audio_tokens:E()}),output_tokens:E()}).optional()}),cp=b({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=b({type:I("conversation.item.input_audio_transcription.failed"),event_id:f(),item_id:f(),content_index:E(),error:b({code:f().optional(),message:f().optional(),param:f().optional(),type:f().optional()})}),dp=b({type:I("conversation.item.retrieved"),event_id:f(),item:Qt}),pp=b({type:I("conversation.item.truncated"),event_id:f(),item_id:f(),audio_end_ms:E(),content_index:E()}),fp=b({type:I("conversation.item.create"),item:Qt,event_id:f().optional(),previous_item_id:f().nullable().optional()}),hp=b({type:I("conversation.item.delete"),item_id:f(),event_id:f().optional()}),mp=b({type:I("conversation.item.retrieve"),item_id:f(),event_id:f().optional()}),gp=b({type:I("conversation.item.truncate"),item_id:f(),audio_end_ms:E(),content_index:E(),event_id:f().optional()}),yp=b({type:I("error"),event_id:f().optional(),error:H().optional()}),_p=b({type:I("input_audio_buffer.cleared"),event_id:f()}),vp=b({type:I("input_audio_buffer.append"),audio:f(),event_id:f().optional()}),bp=b({type:I("input_audio_buffer.clear"),event_id:f().optional()}),wp=b({type:I("input_audio_buffer.commit"),event_id:f().optional()}),Ip=b({type:I("input_audio_buffer.committed"),event_id:f(),item_id:f(),previous_item_id:f().nullable().optional()}),Sp=b({type:I("input_audio_buffer.speech_started"),event_id:f(),item_id:f(),audio_start_ms:E()}),Tp=b({type:I("input_audio_buffer.speech_stopped"),event_id:f(),item_id:f(),audio_end_ms:E()}),xp=b({type:I("output_audio_buffer.started"),event_id:f()}).passthrough(),kp=b({type:I("output_audio_buffer.stopped"),event_id:f()}).passthrough(),Ap=b({type:I("output_audio_buffer.cleared"),event_id:f()}),Cp=b({type:I("rate_limits.updated"),event_id:f(),rate_limits:J(b({limit:E().optional(),name:pe(["requests","tokens"]).optional(),remaining:E().optional(),reset_seconds:E().optional()}))}),Op=b({type:I("response.output_audio.delta"),event_id:f(),item_id:f(),content_index:E(),delta:f(),output_index:E(),response_id:f()}),Ep=b({type:I("response.output_audio.done"),event_id:f(),item_id:f(),content_index:E(),output_index:E(),response_id:f()}),Rp=b({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=b({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=b({type:I("response.content_part.added"),event_id:f(),item_id:f(),content_index:E(),output_index:E(),response_id:f(),part:b({audio:f().optional(),text:f().optional(),transcript:f().optional(),type:pe(["text","audio"]).optional()})}),Dp=b({type:I("response.content_part.done"),event_id:f(),item_id:f(),content_index:E(),output_index:E(),response_id:f(),part:b({audio:f().optional(),text:f().optional(),transcript:f().optional(),type:pe(["text","audio"]).optional()})}),Mp=b({type:I("response.created"),event_id:f(),response:ao}),oo=b({type:I("response.done"),event_id:f(),response:ao}),Fp=b({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=b({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=b({type:I("response.output_item.added"),event_id:f(),item:Qt,output_index:E(),response_id:f()}),Up=b({type:I("response.output_item.done"),event_id:f(),item:Qt,output_index:E(),response_id:f()}),Lp=b({type:I("response.output_text.delta"),event_id:f(),item_id:f(),content_index:E(),delta:f(),output_index:E(),response_id:f()}),zp=b({type:I("response.output_text.done"),event_id:f(),item_id:f(),content_index:E(),text:f(),output_index:E(),response_id:f()}),Bp=b({type:I("session.created"),event_id:f(),session:H()}),Zp=b({type:I("session.updated"),event_id:f(),session:H()}),qp=b({type:I("response.cancel"),event_id:f().optional(),response_id:f().optional()}),Jp=b({type:I("response.create"),event_id:f().optional(),response:H().optional()}),Gp=b({type:I("session.update"),event_id:f().optional(),session:H()}),Vp=b({type:I("mcp_list_tools.in_progress"),event_id:f().optional(),item_id:f().optional()}),Hp=b({type:I("mcp_list_tools.completed"),event_id:f().optional(),item_id:f().optional()}),Wp=b({type:I("response.mcp_call_arguments.delta"),event_id:f(),response_id:f(),item_id:f(),output_index:E(),delta:f(),obfuscation:f()}),Kp=b({type:I("response.mcp_call_arguments.done"),event_id:f(),response_id:f(),item_id:f(),output_index:E(),arguments:f()}),Yp=b({type:I("response.mcp_call.in_progress"),event_id:f(),output_index:E(),item_id:f()}),Xp=b({type:I("response.mcp_call.completed"),event_id:f(),output_index:E(),item_id:f()}),Qp=b({type:I("mcp_list_tools.failed"),event_id:f().optional(),item_id:f().optional()}),ef=b({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,w,v,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((w=(h=s.audio)==null?void 0:h.input)==null?void 0:w.turnDetection)??((N=(v=Je.audio)==null?void 0:v.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(w=>{h[w]===void 0&&delete h[w]}),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 w=this.options.mediaStream??await navigator.mediaDevices.getUserMedia({audio:!0});if(g.addTrack(w.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 v=await g.createOffer();if(await g.setLocalDescription(v),!v.sdp)throw new Error("Failed to create offer");const N=await fetch(m,{method:"POST",body:v.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),w=(m=(d=(p=this._rawSessionConfig)==null?void 0:p.audio)==null?void 0:d.output)==null?void 0:m.format;if(w&&typeof w=="object"){const N=w.type;if(N==="audio/pcmu"||N==="audio/pcma")this._audioLengthMs+=h.byteLength/8;else if(N==="audio/pcm"){const x=w.rate??24e3;this._audioLengthMs+=h.byteLength/2/x*1e3}else this._audioLengthMs+=h.byteLength/24/2}else typeof w=="string"?w.startsWith("g711_")?this._audioLengthMs+=h.byteLength/8:this._audioLengthMs+=h.byteLength/24/2:this._audioLengthMs+=h.byteLength/24/2;const v={type:"audio",data:h,responseId:u.response_id};this._onAudio(v)}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();const a=r==null?void 0:r.greetingInstructions;if(a)try{this._setSessionMuted(!0,"greeting"),await this.session.sendMessage(a)}catch(u){$("WARN","BabelbeezClient: failed to send greeting instructions.",u)}finally{this.isTerminating||this._setSessionMuted(!1,"greeting")}this._resetInactivityState(),$("INFO","BabelbeezClient: Realtime session connected.")}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 a,u,l,p;const e=(a=this.currentSystemSettings)!=null&&a.system_prompt?`${this.currentSystemSettings.system_prompt}
|
|
13
|
+
|
|
14
|
+
${((u=this.currentChatbotSettings)==null?void 0:u.instructions)||""}`.trim():((l=this.currentChatbotSettings)==null?void 0:l.instructions)||"",t=this,s=Ht({name:"perform_rag_search",description:((p=this.currentSystemSettings)==null?void 0:p.rag_search_description)||"Searches the knowledge base for relevant context.",parameters:b({query:f()}),async execute({query:d}){if($("INFO",`Tool perform_rag_search called with query: "${d}"`),t._resetInactivityState(),!t.currentRagSearchUrl||!t.publicChatbotId)return $("ERROR","RAG search URL or publicChatbotId not configured; returning fallback context."),"Knowledge search is temporarily unavailable.";const m=t.isAssistantSpeaking;t.isAssistantSpeaking=!0,t.emit("buttonState","rag-retrieval");try{const g=await fetch(t.currentRagSearchUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:d,public_chatbot_id:t.publicChatbotId})});if(!g.ok){let y=`RAG search failed: ${g.status} ${g.statusText}`;try{const h=await g.json();h&&h.detail&&(y=h.detail)}catch{}return $("ERROR",y),"Knowledge search failed; please answer based on your existing knowledge."}const T=(await g.json()).context||"";return $("INFO",`RAG search succeeded. Context length: ${T.length}`),T||"No additional knowledge was found."}catch(g){return $("ERROR","Network or unexpected error during RAG search.",g),"Knowledge search failed due to a network error."}finally{t.isAssistantSpeaking=m,t.emit("buttonState","active")}}}),r=Ht({name:"request_human_handoff",description:"Escalate to a human staff member via contact form. Provide a concise summary_text.",parameters:b({summary_text:f(),announcement:f()}),async execute({summary_text:d,announcement:m}){var y;$("INFO","Tool request_human_handoff called."),t._resetInactivityState();const g=m||"Please fill out the form so that I can connect you to a staff member to follow up";try{t.session&&await t.session.sendMessage(g)}catch(h){$("WARN","Failed to send handoff announcement message.",h)}t.isHandoffFormOpen=!0,t._setSessionMuted(!0,"handoff_form");let _=null;const T=(y=t.currentChatbotSettings)==null?void 0:y.handoff_whatsapp_number;if(T){const h=String(T).replace(/\D+/g,"");h&&(_=`https://wa.me/${h}?text=${encodeURIComponent(d||"Summary not available.")}`)}return t.currentHandoffSummaryText=d||"Summary not available.",t.emit("handoff:show",{summaryText:t.currentHandoffSummaryText,waLink:_}),await new Promise(h=>{t.handoffPromiseResolve=h}).then(h=>h==="whatsapp_submitted"?"User chose WhatsApp handoff.":h==="email_submitted"?"Handoff request submitted successfully.":"Handoff flow completed or cancelled by the user.")}}),i=Ht({name:"end_conversation",description:"End the conversation when the user clearly wants to stop. The model should call this tool instead of saying goodbye itself.",parameters:b({}),async execute(){return $("INFO","Tool end_conversation called by AI."),t._resetInactivityState(),t.hasEndConversationBeenHandled?($("DEBUG","end_conversation already handled; ignoring subsequent call."),"Conversation is already ending."):(t.hasEndConversationBeenHandled=!0,(async()=>{try{t.session&&(await t.session.interrupt(),$("INFO","Session interrupted by AI end_conversation before goodbye."))}catch(d){$("WARN","Error interrupting session during AI end_conversation; proceeding anyway.",d)}await t._playGoodbyeThenFinalize("ai_end_conversation_tool")})(),"Conversation ended.")}});return new Kd({name:"Assistant",instructions:e,tools:[s,r,i]})}_createVoiceSession(e,t){const s=e==null?void 0:e.model;if(!s)throw new Error("Missing systemSettings.model for RealtimeSession.");const r={type:t!=null&&t.semanticVadEnabled?"semantic_vad":"server_vad",eagerness:(t==null?void 0:t.eagerness)||"medium",createResponse:!0,interruptResponse:!0};return new Rr(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 t=Array.isArray(e)?e:this.session.history||[],s=t[t.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||[],o=[];for(const p of i)if(p&&p.type==="output_audio"&&typeof p.transcript=="string"){const d=p.transcript.trim();d&&o.push(d)}const a=o.join(" ").trim();if(!a)return;const u=this._lastAssistantTranscript||"";let l=a;if(u&&a.startsWith(u)&&(l=a.slice(u.length)),!l)return;this._lastAssistantTranscript=a,this.emit("transcript",{role:"agent",text:l,isFinal:!1})}catch{}}),this.session.transport&&(this.session.transport.on("*",e=>{var t,s;if(e){if(e.type==="response.done"&&((t=e.response)!=null&&t.usage)&&(this.accumulatedUsage=co(this.accumulatedUsage,e.response.usage),$("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 r=this._currentUserTranscript;this.emit("transcript",{role:"user",text:r,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.emit("buttonState","speaking");return}if(e.type==="output_audio_buffer.stopped"||e.type==="output_audio_buffer.cleared"){this.isAssistantSpeaking=!1;const r=this._lastAssistantTranscript||this._currentAssistantTranscript||"";if(r&&this.emit("transcript",{role:"agent",text:r,isFinal:!0}),this._lastAssistantTranscript="",this._currentAssistantTranscript="",this.emit("buttonState","active"),this.pendingGoodbyeResolve&&(this.pendingGoodbyeResolve(),this.pendingGoodbyeResolve=null),!this.isTerminating&&this.currentChatbotSettings&&!this.isHandoffFormOpen){const i=((s=this.currentChatbotSettings)==null?void 0:s.inactivityTimeoutMs)||0;if(this.inactivityStage===0&&i>0){this._clearInactivityTimers();const o=i+mf;this.inactivityStage1TimeoutId=setTimeout(()=>{this.inactivityStage=1,$("INFO","[INACTIVITY] Stage 1 threshold reached; sending enquiry."),this._sendInactivityEnquiry()},o)}else this.inactivityStage===1&&this.shouldScheduleStage2OnNextAssistantSilence&&(this._clearInactivityTimers(),this.inactivityStage2TimeoutId=setTimeout(()=>{$("INFO","[INACTIVITY] Stage 2 threshold reached; auto-ending session with goodbye."),this._playGoodbyeThenFinalize("inactivity_timeout")},hf),this.shouldScheduleStage2OnNextAssistantSilence=!1)}return}}}),this.session.transport.on("audio_transcript_delta",e=>{const t=e==null?void 0:e.delta,s=(t==null?void 0:t.delta)||(t==null?void 0:t.transcript);typeof s=="string"&&s&&($("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(){var e;try{const t=((e=this.session)==null?void 0:e.history)||[],s=[];for(const r of t){if(!r||r.type!=="message"||r.role!=="user"&&r.role!=="assistant")continue;const i=r.role==="user"?"User":"Assistant",o=[],a=r.content||[];for(const l of a)if((l.type==="input_audio"||l.type==="output_audio")&&typeof l.transcript=="string"){const p=l.transcript.trim();p&&o.push(p)}const u=o.join(" ").trim();u&&s.push(`${i}: ${u}`)}return s.join(`
|
|
15
|
+
`)}catch(t){return $("ERROR","Failed to build raw_history from session history.",t),""}}_startHeartbeat(){if(this.heartbeatIntervalId){$("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){$("WARN","BabelbeezClient: Cannot start heartbeat, invalid or missing frequency.",e);return}$("INFO",`BabelbeezClient: Starting heartbeat every ${e} seconds.`);const t=()=>this._sendHeartbeat();this.heartbeatIntervalId=setInterval(t,e*1e3)}_stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null,$("INFO","BabelbeezClient: Heartbeat stopped."))}async _sendHeartbeat(){if(!this.currentSessionId){$("WARN","BabelbeezClient: Cannot send heartbeat, no active session ID."),this._stopHeartbeat();return}try{const e=this.proxyInitializeUrl.replace("/initialize-chat","/heartbeat");$("DEBUG","BabelbeezClient: Sending heartbeat",{session_id:this.currentSessionId,heartbeatUrl:e}),(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.currentSessionId})})).ok}catch(e){$("ERROR","BabelbeezClient: Error sending heartbeat.",e)}}async _finalizeSession(e){if(this.isTerminating){$("DEBUG",`BabelbeezClient._finalizeSession called while already terminating (reason: ${e}).`);return}this.isTerminating=!0,this._clearInactivityTimers(),this._stopHeartbeat();const t=this._buildRawHistoryFromSession();if(this.accumulatedUsage){const r=this.accumulatedUsage.input_tokens||0,i=this.accumulatedUsage.output_tokens||0,o=r+i;(!this.accumulatedUsage.total_tokens||this.accumulatedUsage.total_tokens<o)&&(this.accumulatedUsage.total_tokens=o)}$("INFO",`Finalizing session (reason: ${e}). raw_history length=${t.length}`);const s={usage:this.accumulatedUsage,client_reason:e,raw_history:t};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};$("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){$("ERROR","BabelbeezClient: Error sending /end-chat beacon.",r)}try{this.session&&(await this.session.close(),$("DEBUG","BabelbeezClient: RealtimeSession closed."))}catch(r){$("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.isTerminating=!1}}ee.BabelbeezClient=yf,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"})});
|