PageSourceSearch

https://app.smartbooks.ai/assets/directive-fL4Pnu6I.js

js smartbooks.ai collected 2026-10-05 12:39:29 UTC 477,005 bytes, 14 lines download raw bytes

1import{a as e,r as t,t as n}from"./rolldown-runtime-DkW27tQK.js";import{t as r}from"./v4-DIgz8zy6.js";import{t as i}from"./random-id-mR65Vk8j.js";function a(e){return typeof e==`function`}function o(e,...t){return a(e)?e(...t):e}var s=class{#e=!0;#t;#n;#r;#i;#a;#o;#s;#c=0;#l=5;#u=!1;#d=!1;#f=null;#p=()=>{this.debugLog(`Connected to event bus`),this.#a=!0,this.#u=!1,this.debugLog(`Emitting queued events`,this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener(`tanstack-connect-success`,this.#p)};#m=()=>{if(this.#c<this.#l){this.#c++,this.dispatchCustomEvent(`tanstack-connect`,{});return}this.#n().removeEventListener(`tanstack-connect`,this.#m),this.#d=!0,this.debugLog(`Max retries reached, giving up on connection`),this.stopConnectLoop()};#h=()=>{this.#u||(this.#u=!0,this.#n().addEventListener(`tanstack-connect-success`,this.#p),this.#m())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:r=300}){this.#t=e,this.#e=n,this.#n=this.getGlobalTarget,this.#r=t,this.debugLog(` Initializing event subscription for plugin`,this.#t),this.#i=[],this.#a=!1,this.#d=!1,this.#o=null,this.#s=r}startConnectLoop(){this.#o!==null||this.#a||(this.debugLog(`Starting connect loop (every ${this.#s}ms)`),this.#o=setInterval(this.#m,this.#s))}stopConnectLoop(){this.#u=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog(`Stopped connect loop`))}debugLog(...e){this.#r&&console.log(`🌴 [tanstack-devtools:${this.#t}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<`u`&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog(`Using global event target`),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<`u`&&window.addEventListener!==void 0)return this.debugLog(`Using window as event target`),window;let e=typeof EventTarget<`u`?new EventTarget:void 0;return e===void 0||e.addEventListener===void 0?(this.debugLog(`No event mechanism available, running in non-web environment`),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog(`Using new EventTarget as fallback`),e)}getPluginId(){return this.#t}dispatchCustomEventShim(e,t){try{let n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog(`Failed to dispatch shim event`)}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog(`Emitting event to client bus`,e),this.dispatchCustomEvent(`tanstack-dispatch-event`,e)}createEventPayload(e,t){return{type:`${this.#t}:${e}`,payload:t,pluginId:this.#t}}emit(e,t){if(!this.#e){this.debugLog(`Event bus client is disabled, not emitting event`,e,t);return}if(this.#f&&(this.debugLog(`Emitting event to internal event target`,e,t),this.#f.dispatchEvent(new CustomEvent(`${this.#t}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog(`Previously failed to connect, not emitting to bus`);return}if(!this.#a){this.debugLog(`Bus not available, will be pushed as soon as connected`),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<`u`&&!this.#u&&(this.#h(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){let r=n?.withEventTarget??!1,i=`${this.#t}:${e}`;if(r&&(this.#f||=new EventTarget,this.#f.addEventListener(i,e=>{t(e.detail)})),!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`,i),()=>{};let a=e=>{this.debugLog(`Received event from bus`,e.detail),t(e.detail)};return this.#n().addEventListener(i,a),this.debugLog(`Registered event to bus`,i
1),()=>{r&&this.#f?.removeEventListener(i,a),this.#n().removeEventListener(i,a)}}onAll(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}onAllPluginEvents(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;this.#t&&n.pluginId!==this.#t||e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}},c=new Map;function l(e,t){c.set(e,t)}function u(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return null}}function d(e){return typeof e.get==`function`?e.get():e.state}function f(e){return{key:e.key,store:{state:u(d(e.store))},options:u(e.options)}}var p=class extends s{constructor(e){super({pluginId:`pacer`,debug:e?.debug,reconnectEveryMs:1e3})}},m=(e,t)=>{let n=t.key;n&&(l(n,t),h.emit(e,f({...t,key:n})))},h=new p,g=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(g||{});function ee({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function te(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var ne=[],re=0,{link:ie,unlink:ae,propagate:oe,checkDirty:se,shallowPropagate:ce}=ee({update(e){return e._update()},notify(e){ne[ue++]=e,e.flags&=~g.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=g.Mutable|g.Dirty,pe(e))}}),le=0,ue=0,de,fe=0;function pe(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=ae(n,e)}function me(){if(!(fe>0)){for(;le<ue;){let e=ne[le];ne[le++]=void 0,e.notify()}le=0,ue=0}}function he(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?g.None:g.Mutable,get(){return de!==void 0&&ie(i,de,re),i._snapshot},subscribe(e){let t=te(e),n={current:!1},r=ge(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=de,o=t?.compare??Object.is;if(n)de=i,++re,i.depsTail=void 0;else if(e===void 0)return!1;
1n&&(i.flags=g.Mutable|g.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{de=a,n&&(i.flags&=~g.RecursedCheck),pe(i)}}};return n?(i.flags=g.Mutable|g.Dirty,i.get=function(){let e=i.flags;if(e&g.Dirty||e&g.Pending&&se(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&ce(e)}}else e&g.Pending&&(i.flags=e&~g.Pending);return de!==void 0&&ie(i,de,re),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(oe(e),ce(e),me())}},i}function ge(e){let t=()=>{let t=de;de=n,++re,n.depsTail=void 0,n.flags=g.Watching|g.RecursedCheck;try{return e()}finally{de=t,n.flags&=~g.RecursedCheck,pe(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:g.Watching|g.RecursedCheck,notify(){let e=this.flags;e&g.Dirty||e&g.Pending&&se(this.deps,this)?t():this.flags=g.Watching},stop(){this.flags=g.None,this.depsTail=void 0,pe(this)}};return t(),n}var _e=class{constructor(e){this.atom=he(e)}setState(e){this.atom.set(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(te(e))}};function ve(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var ye={enabled:!0,leading:!0,trailing:!0,wait:0},be=class{#e;constructor(e,t){this.fn=e,this.store=new _e(ve()),this.setOptions=e=>{this.options={...this.options,...e},this.#n()||this.cancel()},this.maybeExecute=(...e)=>{this.#t({maybeExecuteCount:this.store.state.maybeExecuteCount+1});let t=Date.now(),n=t-this.store.state.lastExecutionTime,r=this.#r();if(this.options.leading&&n>=r)this.#i(...e);else if(this.#t({lastArgs:e}),!this.#e&&this.options.trailing){let e=r-(this.store.state.lastExecutionTime?t-this.store.state.lastExecutionTime:0);this.#t({isPending:!0}),this.#e=setTimeout(()=>{let{lastArgs:e}=this.store.state;e!==void 0&&this.#i(...e)},e)}},this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&this.#i(...this.store.state.lastArgs)},this.cancel=()=>{this.#a(),this.#t({lastArgs:void 0,isPending:!1})},this.reset=()=>{this.#t(ve())},this.key=t.key,this.options={...ye,...t},this.#t(this.options.initialState??{}),this.key&&h.on(`d-Throttler`,e=>{e.payload.key===this.key&&(this.#t(e.payload.store.state),this.setOptions(e.payload.options))})}#t=e=>{this.store.setState(t=>{let n={...t,...e},{isPending:r}=n;return{...n,status:this.#n()?r?`pending`:`idle`:`disabled`}}),m(`Throttler`,this)};#n=()=>!!o(this.options.enabled,this);#r=()=>o(this.options.wait,this);#i=(...e)=>{if(!this.#n())return;this.fn(...e);let t=Date.now(),n=t+this.#r();this.#a(),this.#t({executionCount:this.store.state.executionCount+1,lastExecutionTime:t,nextExecutionTime:n,isPending:!1,lastArgs:void 0}),this.options.onExecute?.(e,this),setTimeout(()=>{this.store.state.isPending||this.#t({nextExecutionTime:void 0})},this.#r())};#a=()=>{this.#e&&=(clearTimeout(this.#e),void 0)}},_;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(_||={});var xe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xe||={});var v=_.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Se=e=>{switch(typeof e){case`undefined`:return v.undefined;case`string`:return v.string;
vendor: 11,938 bytes, line 1
1case`number`:return Number.isNaN(e)?v.nan:v.number;case`boolean`:return v.boolean;case`function`:return v.function;case`bigint`:return v.bigint;case`symbol`:return v.symbol;case`object`:return Array.isArray(e)?v.array:e===null?v.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?v.promise:typeof Map<`u`&&e instanceof Map?v.map:typeof Set<`u`&&e instanceof Set?v.set:typeof Date<`u`&&e instanceof Date?v.date:v.object;default:return v.unknown}},y=_.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`]),Ce=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ce.create=e=>new Ce(e);var we=(e,t)=>{let n;switch(e.code){case y.invalid_type:n=e.received===v.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,_.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:n=`Unrecognized key(s) in object: ${_.joinValues(e.keys,`, `)}`;break;case y.invalid_union:n=`Invalid input`;break;case y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${_.joinValues(e.options)}`;break;case y.invalid_enum_value:n=`Invalid enum value. Expected ${_.joinValues(e.options)}, received '${e.received}'`;break;case y.invalid_arguments:n=`Invalid function arguments`;break;case y.invalid_return_type:n=`Invalid function return type`;break;case y.invalid_date:n=`Invalid date`;break;case y.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:_.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case y.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case y.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case y.custom:n=`Invalid input`;break;case y.invalid_intersection_types:n=`Intersection results could not be merged`;break;case y.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case y.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,_.assertNever(e)}return{message:n}},Te=we;function Ee(){return Te}var De=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function b(e,t){let n=Ee(),r=De({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===we?void 0:we].filter(e=>!!e)});e.common.issues.push(r)}var Oe=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return x;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return x;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},x=Object.freeze({status:`aborted`}),ke=e=>({status:`dirty`,value:e}),Ae=e=>({status:`valid`,value:e}),je=e=>e.status===`aborted`,Me=e=>e.status===`dirty`,Ne=e=>e.status===`valid`,Pe=e=>typeof Promise<`u`&&e instanceof Promise,S;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(S||={});var Fe=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},Ie=(e,t)=>{if(Ne(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Ce(e.common.issues);return this._error=t,this._error}}};function C(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var w=class{get description(){return this._def.description}_getType(e){return Se(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oe,ctx:{common:e.parent.common,data:e.data,parsedType:Se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Pe(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)};return Ie(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Ne(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Ne(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)},r=this._parse({data:e,path:n.path,parent:n});return Ie(n,await(Pe(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:y.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new zt({schema:this,typeName:T.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:e=>this[`~validate`](e)}}optional(){return Bt.create(this,this._def)}nullable(){return Vt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return bt.create(this)}promise(){return Rt.create(this,this._def)}or(e){return Ct.create([this,e],this._def)}and(e){return Dt.create(this,e,this._def)}transform(e){return new zt({...C(this._def),schema:this,typeName:T.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Ht({...C(this._def),innerType:this,defaultValue:t,typeName:T.ZodDefault})}brand(){return new Gt({typeName:T.ZodBranded,type:this,...C(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Ut({...C(this._def),innerType:this,catchValue:t,typeName:T.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Kt.create(this,e)}readonly(){return qt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Le=/^c[^\s-]{8,}
vendor: 18,555 bytes, line 1
1$/i,Re=/^[0-9a-z]+$/,ze=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Be=/^[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,Ve=/^[a-z0-9_-]{21}$/i,He=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ue=/^[-+]?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)?)??$/,We=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ge=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,Ke,qe=/^(?:(?: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])$/,Je=/^(?:(?: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])$/,Ye=/^(([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]))$/,Xe=/^(([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])$/,Ze=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$e=`((\\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])))`,et=RegExp(`^${$e}$`);function tt(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function nt(e){return RegExp(`^${tt(e)}$`)}function rt(e){let t=`${$e}T${tt(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function it(e,t){return!!((t===`v4`||!t)&&qe.test(e)||(t===`v6`||!t)&&Ye.test(e))}function at(e,t){if(!He.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function ot(e,t){return!!((t===`v4`||!t)&&Je.test(e)||(t===`v6`||!t)&&Xe.test(e))}var st=class e extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.string,received:t.parsedType}),x}let t=new Oe,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),b(n,{code:y.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),b(n,{code:y.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?b(n,{code:y.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&b(n,{code:y.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)We.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`email`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Ke||=new RegExp(Ge,`u`),Ke.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`emoji`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Be.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`uuid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ve.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`nanoid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Le.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`cuid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Re.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`cuid2`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ze.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`ulid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),b(n,{validation:`url`,code:y.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`regex`,code:y.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),b(n,{code:y.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),b(n,{code:y.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),b(n,{code:y.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?rt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{code:y.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?et.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{code:y.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?nt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{code:y.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Ue.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`duration`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?it(e.data,r.version)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`ip`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?at(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`jwt`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?ot(e.data,r.version)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`cidr`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Ze.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`base64`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Qe.test(e.data)||(n=this._getOrReturnCtx(e,n),b(n,{validation:`base64url`,code:y.invalid_string,message:r.message}),t.dirty()):_.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:y.invalid_string,...S.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...S.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...S.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...S.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...S.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...S.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...S.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...S.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...S.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...S.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...S.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...S.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...S.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...S.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:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...S.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...S.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...S.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...S.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...S.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...S.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...S.errToObj(t)})}nonempty(e){return this.min(1,S.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...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(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};st.create=e=>new st({checks:[],typeName:T.ZodString,coerce:e?.coerce??!1,...C(e)});function ct(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var lt=class e extends w{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)!==v.number){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.number,received:t.parsedType}),x}let t,n=new Oe;for(let r of this._def.checks)r.kind===`int`?_.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),b(t,{code:y.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),b(t,{code:y.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),b(t,{code:y.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?ct(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),b(t,{code:y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),b(t,{code:y.not_finite,message:r.message}),n.dirty()):_.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,S.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,S.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,S.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,S.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:S.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:S.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:S.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:S.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:S.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:S.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let 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`&&_.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};lt.create=e=>new lt({checks:[],typeName:T.ZodNumber,coerce:e?.coerce||!1,...C(e)});var ut=class e extends w{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)!==v.bigint)return this._getInvalidInput(e);let t,n=new Oe;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),b(t,{code:y.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),b(t,{code:y.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),b(t,{code:y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):_.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.bigint,received:t.parsedType}),x}gte(e,t){return this.setLimit(`min`,e,!0,S.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,S.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,S.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,S.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:S.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:S.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ut.create=e=>new ut({checks:[],typeName:T.ZodBigInt,coerce:e?.coerce??!1,...C(e)});var dt=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.boolean,received:t.parsedType}),x}return Ae(e.data)}};dt.create=e=>new dt({typeName:T.ZodBoolean,coerce:e?.coerce||!1,...C(e)});var ft=class e extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.date,received:t.parsedType}),x}if(Number.isNaN(e.data.getTime()))return b(this._getOrReturnCtx(e),{code:y.invalid_date}),x;let t=new Oe,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),b(n,{code:y.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),b(n,{code:y.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):_.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:S.toString(t)})}
vendor: 20,559 bytes, line 1
1get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ft.create=e=>new ft({checks:[],coerce:e?.coerce||!1,typeName:T.ZodDate,...C(e)});var pt=class extends w{_parse(e){if(this._getType(e)!==v.symbol){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.symbol,received:t.parsedType}),x}return Ae(e.data)}};pt.create=e=>new pt({typeName:T.ZodSymbol,...C(e)});var mt=class extends w{_parse(e){if(this._getType(e)!==v.undefined){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.undefined,received:t.parsedType}),x}return Ae(e.data)}};mt.create=e=>new mt({typeName:T.ZodUndefined,...C(e)});var ht=class extends w{_parse(e){if(this._getType(e)!==v.null){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.null,received:t.parsedType}),x}return Ae(e.data)}};ht.create=e=>new ht({typeName:T.ZodNull,...C(e)});var gt=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}};gt.create=e=>new gt({typeName:T.ZodAny,...C(e)});var _t=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}};_t.create=e=>new _t({typeName:T.ZodUnknown,...C(e)});var vt=class extends w{_parse(e){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.never,received:t.parsedType}),x}};vt.create=e=>new vt({typeName:T.ZodNever,...C(e)});var yt=class extends w{_parse(e){if(this._getType(e)!==v.undefined){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.void,received:t.parsedType}),x}return Ae(e.data)}};yt.create=e=>new yt({typeName:T.ZodVoid,...C(e)});var bt=class e extends w{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==v.array)return b(t,{code:y.invalid_type,expected:v.array,received:t.parsedType}),x;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(b(t,{code:e?y.too_big:y.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(b(t,{code:y.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(b(t,{code:y.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Fe(t,e,t.path,n)))).then(e=>Oe.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Fe(t,e,t.path,n)));return Oe.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:S.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:S.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:S.toString(n)}})}nonempty(e){return this.min(1,e)}};bt.create=(e,t)=>new bt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...C(t)});function xt(e){if(e instanceof St){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Bt.create(xt(r))}return new St({...e._def,shape:()=>t})}return e instanceof bt?new bt({...e._def,type:xt(e.element)}):e instanceof Bt?Bt.create(xt(e.unwrap())):e instanceof Vt?Vt.create(xt(e.unwrap())):e instanceof Ot?Ot.create(e.items.map(e=>xt(e))):e}var St=class e extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=_.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==v.object){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.object,received:t.parsedType}),x}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof vt&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Fe(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof vt){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(b(n,{code:y.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Fe(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Oe.mergeObjectSync(t,e)):Oe.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return S.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:S.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:T.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of _.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of _.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return xt(this)}partial(t){let n={};for(let e of _.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of _.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Bt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ft(_.objectKeys(this.shape))}};St.create=(e,t)=>new St({shape:()=>e,unknownKeys:`strip`,catchall:vt.create(),typeName:T.ZodObject,...C(t)}),St.strictCreate=(e,t)=>new St({shape:()=>e,unknownKeys:`strict`,catchall:vt.create(),typeName:T.ZodObject,...C(t)}),St.lazycreate=(e,t)=>new St({shape:e,unknownKeys:`strip`,catchall:vt.create(),typeName:T.ZodObject,...C(t)});var Ct=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Ce(e.ctx.common.issues));return b(t,{code:y.invalid_union,unionErrors:n}),x}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Ce(e));return b(t,{code:y.invalid_union,unionErrors:i}),x}}get options(){return this._def.options}};Ct.create=(e,t)=>new Ct({options:e,typeName:T.ZodUnion,...C(t)});var wt=e=>e instanceof Nt?wt(e.schema):e instanceof zt?wt(e.innerType()):e instanceof Pt?[e.value]:e instanceof It?e.options:e instanceof Lt?_.objectValues(e.enum):e instanceof Ht?wt(e._def.innerType):e instanceof mt?[void 0]:e instanceof ht?[null]:e instanceof Bt?[void 0,...wt(e.unwrap())]:e instanceof Vt?[null,...wt(e.unwrap())]:e instanceof Gt||e instanceof qt?wt(e.unwrap()):e instanceof Ut?wt(e._def.innerType):[],Tt=class e extends w{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return b(t,{code:y.invalid_type,expected:v.object,received:t.parsedType}),x;let n=this.discriminator,r=t.data[n],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}):(b(t,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),x)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=wt(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...C(r)})}};function Et(e,t){let n=Se(e),r=Se(t);if(e===t)return{valid:!0,data:e};if(n===v.object&&r===v.object){let n=_.objectKeys(t),r=_.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Et(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===v.array&&r===v.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Et(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===v.date&&r===v.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Dt=class extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(je(e)||je(r))return x;let i=Et(e.value,r.value);return i.valid?((Me(e)||Me(r))&&t.dirty(),{status:t.value,value:i.data}):(b(n,{code:y.invalid_intersection_types}),x)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Dt.create=(e,t,n)=>new Dt({left:e,right:t,typeName:T.ZodIntersection,...C(n)});var Ot=class e extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return b(n,{code:y.invalid_type,expected:v.array,received:n.parsedType}),x;if(n.data.length<this._def.items.length)return b(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),x;!this._def.rest&&n.data.length>this._def.items.length&&(b(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Fe(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Oe.mergeArray(t,e)):Oe.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ot.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ot({items:e,typeName:T.ZodTuple,rest:null,...C(t)})};var kt=class e extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return b(n,{code:y.invalid_type,expected:v.object,received:n.parsedType}),x;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Fe(n,e,n.path,e)),value:a._parse(new Fe(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Oe.mergeObjectAsync(t,r):Oe.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof w?new e({keyType:t,valueType:n,typeName:T.ZodRecord,...C(r)}):new e({keyType:st.create(),valueType:t,typeName:T.ZodRecord,...C(n)})}},At=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.map)return b(n,{code:y.invalid_type,expected:v.map,received:n.parsedType}),x;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Fe(n,e,n.path,[a,`key`])),value:i._parse(new Fe(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return x;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return x;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};At.create=(e,t,n)=>new At({valueType:t,keyType:e,typeName:T.ZodMap,...C(n)});var jt=class e extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return b(n,{code:y.invalid_type,expected:v.set,received:n.parsedType}),x;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(b(n,{code:y.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(b(n,{code:y.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return x;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Fe(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:S.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:S.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};jt.create=(e,t)=>new jt({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...C(t)});var Mt=class e extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return b(t,{code:y.invalid_type,expected:v.function,received:t.parsedType}),x;function n(e,n){return De({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ee(),we].filter(e=>!!e),issueData:{code:y.invalid_arguments,argumentsError:n}})}function r(e,n){return De({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ee(),we].filter(e=>!!e),issueData:{code:y.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Rt){let e=this;return Ae(async function(...t){let o=new Ce([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return Ae(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Ce([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Ce([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ot.create(t).rest(_t.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Ot.create([]).rest(_t.create()),returns:n||_t.create(),typeName:T.ZodFunction,...C(r)})}},Nt=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Nt.create=(e,t)=>new Nt({getter:e,typeName:T.ZodLazy,...C(t)});var Pt=class extends w{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return b(t,{received:t.data,code:y.invalid_literal,expected:this._def.value}),x}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Pt.create=(e,t)=>new Pt({value:e,typeName:T.ZodLiteral,...C(t)});function Ft(e,t){return new It({values:e,typeName:T.ZodEnum,...C(t)})}var It=class e extends w{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return b(t,{expected:_.joinValues(n),received:t.parsedType,code:y.invalid_type}),x}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return b(t,{received:t.data,code:y.invalid_enum_value,options:n}),x}return Ae(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};It.create=Ft;var Lt=class extends w{_parse(e){let t=_.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){let e=_.objectValues(t);return b(n,{expected:_.joinValues(e),received:n.parsedType,code:y.invalid_type}),x}if(this._cache||=new Set(_.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=_.objectValues(t);return b(n,{received:n.data,code:y.invalid_enum_value,options:e}),x}return Ae(e.data)}get enum(){return this._def.values}};Lt.create=(e,t)=>new Lt({values:e,typeName:T.ZodNativeEnum,...C(t)});var Rt=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==v.promise&&t.common.async===!1?(b(t,{code:y.invalid_type,expected:v.promise,received:t.parsedType}),x):Ae((t.parsedType===v.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Rt.create=(e,t)=>new Rt({type:e,typeName:T.ZodPromise,...C(t)});var zt=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{b(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return x;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?x:r.status===`dirty`||t.value===`dirty`?ke(r.value):r});{if(t.value===`aborted`)return x;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?x:r.status===`dirty`||t.value===`dirty`?ke(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?x:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?x:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ne(e))return x;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Ne(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):x)}_.assertNever(r)}};
1zt.create=(e,t,n)=>new zt({schema:e,typeName:T.ZodEffects,effect:t,...C(n)}),zt.createWithPreprocess=(e,t,n)=>new zt({schema:t,effect:{type:`preprocess`,transform:e},typeName:T.ZodEffects,...C(n)});var Bt=class extends w{_parse(e){return this._getType(e)===v.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bt.create=(e,t)=>new Bt({innerType:e,typeName:T.ZodOptional,...C(t)});var Vt=class extends w{_parse(e){return this._getType(e)===v.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vt.create=(e,t)=>new Vt({innerType:e,typeName:T.ZodNullable,...C(t)});var Ht=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ht.create=(e,t)=>new Ht({innerType:e,typeName:T.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...C(t)});var Ut=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pe(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Ce(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Ce(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ut.create=(e,t)=>new Ut({innerType:e,typeName:T.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...C(t)});var Wt=class extends w{_parse(e){if(this._getType(e)!==v.nan){let t=this._getOrReturnCtx(e);return b(t,{code:y.invalid_type,expected:v.nan,received:t.parsedType}),x}return{status:`valid`,value:e.data}}};Wt.create=e=>new Wt({typeName:T.ZodNaN,...C(e)});var Gt=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Kt=class e extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?x:e.status===`dirty`?(t.dirty(),ke(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?x:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:T.ZodPipeline})}},qt=class extends w{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Ne(e)&&(e.value=Object.freeze(e.value)),e);return Pe(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};qt.create=(e,t)=>new qt({innerType:e,typeName:T.ZodReadonly,...C(t)}),St.lazycreate;var T;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(T||={});var E=st.create,Jt=lt.create;Wt.create,ut.create;var D=dt.create;ft.create,pt.create,mt.create,ht.create;var Yt=gt.create,Xt=_t.create;vt.create,yt.create;var Zt=bt.create,O=St.create;St.strictCreate;var Qt=Ct.create,$t=Tt.create;Dt.create,Ot.create;var en=kt.create;At.create,jt.create,Mt.create,Nt.create;var k=Pt.create,tn=It.create,nn=Lt.create;Rt.create,zt.create,Bt.create,Vt.create;var rn=zt.createWithPreprocess;Kt.create;var an={string:(e=>st.create({...e,coerce:!0})),number:(e=>lt.create({...e,coerce:!0})),boolean:(e=>dt.create({...e,coerce:!0})),bigint:(e=>ut.create({...e,coerce:!0})),date:(e=>ft.create({...e,coerce:!0}))},on=en(Yt()).optional();function sn(e,t){return t===void 0?e:e===void 0?{...t}:{...e,...t}}var cn=O({name:E(),arguments:E()}),ln=O({id:E(),type:k(`function`),function:cn,encryptedValue:E().optional(),metadata:on}),un=O({id:E(),role:E(),content:E().optional(),name:E().optional(),encryptedValue:E().optional(),subagentRunId:E().optional(),metadata:on}),dn=O({type:k(`text`),text:E()}),fn=$t(`type`,[O({type:k(`data`),value:E(),mimeType:E()}),O({type:k(`url`),value:E(),mimeType:E().optional()}
1)]),pn=O({type:k(`image`),source:fn,metadata:Xt().optional()}),mn=O({type:k(`audio`),source:fn,metadata:Xt().optional()}),hn=O({type:k(`video`),source:fn,metadata:Xt().optional()}),gn=O({type:k(`document`),source:fn,metadata:Xt().optional()}),_n=O({type:k(`binary`),mimeType:E(),id:E().optional(),url:E().optional(),data:E().optional(),filename:E().optional()}),vn=(e,t)=>{!e.id&&!e.url&&!e.data&&t.addIssue({code:y.custom,message:`BinaryInputContent requires at least one of id, url, or data.`,path:[`id`]})};_n.superRefine((e,t)=>{vn(e,t)});var yn=$t(`type`,[dn,pn,mn,hn,gn,_n]).superRefine((e,t)=>{e.type===`binary`&&vn(e,t)}),bn=$t(`role`,[un.extend({role:k(`developer`),content:E()}),un.extend({role:k(`system`),content:E()}),un.extend({role:k(`assistant`),content:E().optional(),toolCalls:Zt(ln).optional()}),un.extend({role:k(`user`),content:Qt([E(),Zt(yn)])}),O({id:E(),content:E(),role:k(`tool`),toolCallId:E(),error:E().optional(),encryptedValue:E().optional(),subagentRunId:E().optional(),metadata:on}),O({id:E(),role:k(`activity`),activityType:E(),content:en(Yt()),subagentRunId:E().optional(),metadata:on}),O({id:E(),role:k(`reasoning`),content:E(),encryptedValue:E().optional(),subagentRunId:E().optional(),metadata:on})]);Qt([k(`developer`),k(`system`),k(`assistant`),k(`user`),k(`tool`),k(`activity`),k(`reasoning`)]);var xn=O({description:E(),value:E()}),Sn=O({name:E(),description:E(),parameters:Yt(),metadata:en(Yt()).optional()}),Cn=O({id:E(),reason:E(),message:E().optional(),toolCallId:E().optional(),responseSchema:en(Yt()).optional(),expiresAt:E().optional(),metadata:en(Yt()).optional(),subagentRunId:E().optional()}),wn=O({interruptId:E(),status:tn([`resolved`,`cancelled`]),payload:Yt().optional(),metadata:on}),Tn=O({threadId:E(),runId:E(),parentRunId:E().optional(),state:Yt().transform(e=>e??void 0),messages:Zt(bn),tools:Zt(Sn),context:Zt(xn),forwardedProps:Yt(),resume:Zt(wn).optional()}),En=Yt(),A=class extends Error{constructor(e){super(e)}},Dn=class extends A{constructor(){super(`Connect not implemented. This method is not supported by the current agent.`)}},On=O({name:E(),description:E().optional()}),kn=O({name:E().optional(),type:E().optional(),description:E().optional(),version:E().optional(),provider:E().optional(),documentationUrl:E().optional(),metadata:en(Xt()).optional()}),An=O({streaming:D().optional(),websocket:D().optional(),httpBinary:D().optional(),pushNotifications:D().optional(),resumable:D().optional()}),jn=O({supported:D().optional(),items:Zt(Sn).optional(),parallelCalls:D().optional(),clientProvided:D().optional()}),Mn=O({structuredOutput:D().optional(),supportedMimeTypes:Zt(E()).optional()}),Nn=O({snapshots:D().optional(),deltas:D().optional(),memory:D().optional(),persistentState:D().optional()}),Pn=O({supported:D().optional(),delegation:D().optional(),handoffs:D().optional(),subAgents:Zt(On).optional()}),Fn=O({supported:D().optional(),streaming:D().optional(),encrypted:D().optional()}),In=O({image:D().optional(),audio:D().optional(),video:D().optional(),pdf:D().optional(),file:D().optional()}),Ln=O({image:D().optional(),audio:D().optional()}),Rn=O({input:In.optional(),output:Ln.optional()}),zn=O({codeExecution:D().optional(),sandboxed:D().optional(),maxIterations:Jt().optional(),maxExecutionTime:Jt().optional()}),Bn=O({supported:D().optional(),approvals:D().optional(),interventions:D().optional(),feedback:D().optional(),interrupts:D().optional(),approveWithEdits:D().optional()});O({identity:kn.optional(),transport:An.optional(),tools:jn.optional(),output:Mn.optional(),state:Nn.optional(),multiAgent:Pn.optional(),reasoning:Fn.optional(),multimodal:Rn.optional(),execution:zn.optional(),humanInTheLoop:Bn.optional(),custom:en(Xt()).optional()});var Vn=Qt([k(`developer`),k(`system`),k(`assistant`),k(`user`)]),j=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`
1STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e.SUBAGENT_STARTED=`SUBAGENT_STARTED`,e.SUBAGENT_FINISHED=`SUBAGENT_FINISHED`,e.SUBAGENT_ERROR=`SUBAGENT_ERROR`,e}({}),M=O({type:nn(j),timestamp:Jt().optional(),rawEvent:Yt().optional(),metadata:on}).passthrough(),Hn=M.extend({type:k(j.TEXT_MESSAGE_START),messageId:E(),role:Vn.default(`assistant`),name:E().optional(),subagentRunId:E().optional()}),Un=M.extend({type:k(j.TEXT_MESSAGE_CONTENT),messageId:E(),delta:E(),subagentRunId:E().optional()}),Wn=M.extend({type:k(j.TEXT_MESSAGE_END),messageId:E(),subagentRunId:E().optional()}),Gn=M.extend({type:k(j.TEXT_MESSAGE_CHUNK),messageId:E().optional(),role:Vn.optional(),delta:E().optional(),name:E().optional(),subagentRunId:E().optional()}),Kn=M.extend({type:k(j.THINKING_TEXT_MESSAGE_START)}),qn=Un.omit({messageId:!0,type:!0,subagentRunId:!0}).extend({type:k(j.THINKING_TEXT_MESSAGE_CONTENT)}),Jn=M.extend({type:k(j.THINKING_TEXT_MESSAGE_END)}),Yn=M.extend({type:k(j.TOOL_CALL_START),toolCallId:E(),toolCallName:E(),parentMessageId:E().nullable().optional().transform(e=>e??void 0),subagentRunId:E().optional()}),Xn=M.extend({type:k(j.TOOL_CALL_ARGS),toolCallId:E(),delta:E(),subagentRunId:E().optional()}),Zn=M.extend({type:k(j.TOOL_CALL_END),toolCallId:E(),subagentRunId:E().optional()}),Qn=M.extend({messageId:E(),type:k(j.TOOL_CALL_RESULT),toolCallId:E(),content:E(),role:k(`tool`).optional(),subagentRunId:E().optional()}),$n=M.extend({type:k(j.TOOL_CALL_CHUNK),toolCallId:E().optional(),toolCallName:E().optional(),parentMessageId:E().nullable().optional().transform(e=>e??void 0),delta:E().optional(),subagentRunId:E().optional()}),er=M.extend({type:k(j.THINKING_START),title:E().optional()}),tr=M.extend({type:k(j.THINKING_END)}),nr=M.extend({type:k(j.STATE_SNAPSHOT),snapshot:En,subagentRunId:E().optional()}),rr=M.extend({type:k(j.STATE_DELTA),delta:Zt(Yt()),subagentRunId:E().optional()}),ir=M.extend({type:k(j.MESSAGES_SNAPSHOT),messages:Zt(bn)}),ar=M.extend({type:k(j.ACTIVITY_SNAPSHOT),messageId:E(),activityType:E(),content:en(Yt()),replace:D().optional().default(!0),subagentRunId:E().optional()}),or=M.extend({type:k(j.ACTIVITY_DELTA),messageId:E(),activityType:E(),patch:Zt(Yt()),subagentRunId:E().optional()}),sr=M.extend({type:k(j.RAW),event:Yt(),source:E().optional(),subagentRunId:E().optional()}),cr=M.extend({type:k(j.CUSTOM),name:E(),value:Yt(),subagentRunId:E().optional()}),lr=M.extend({type:k(j.RUN_STARTED),threadId:E(),runId:E(),parentRunId:E().optional(),input:Tn.optional()}),ur=$t(`type`,[O({type:k(`success`)}).strict(),O({type:k(`interrupt`),interrupts:Zt(Cn).min(1)}).strict()]),dr=O({provider:E().optional(),model:E().optional(),inputTokens:Jt().int().nonnegative().optional(),outputTokens:Jt().int().nonnegative().optional(),totalTokens:Jt().int().nonnegative().optional(),reasoningTokens:Jt().int().nonnegative().optional(),cachedInputTokens:Jt().int().nonnegative().optional()}),fr=M.extend({type:k(j.RUN_FINISHED),threadId:E(),runId:E(),result:Yt().optional(),outcome:ur.nullable().optional().transform(e=>e??void 0),usage:Zt(dr).optional()}),pr=M.extend({type:k(j.RUN_ERROR),message:E(),code:E().optional(),usage:Zt(dr).optional()}),mr=M.extend({type:k(j.STEP_STARTED),stepName:E(),subagentRunId:E().optional()}),hr=M.extend({type:k(j.STEP_FINISHED),stepName:E(),subagentRunId:E().optional()}),gr=Qt([k(`tool-call`),k(`message`)]),_r=M.extend({type:k(j.REASONING_START),messageId:E(),subagentRunId:E().optional()}),vr=M.extend({type:k(j.REASONING_MESSAGE_START),messageId:E(),role:k(`reasoning`),subagentRunId:E().optional()}),yr=M.extend({type:k(j.REASONING_MESSAGE_CONTENT),messageId:E(),delta:E(),subagentRunId:E().optional()}),br=M.extend({type:k(j.REASONING_MESSAGE_END),messageId:E(),subagentRunId:E().optional()}),xr=M.extend({type:k(j.REASONING_MESSAGE_CHUNK),messageId:E().optional(),delta:E().optional(),subagentRunId:E().optional()}),Sr=M.extend({type:k(j.REASONING_END),messageId:E(),subagentRunId:E().optional()}),Cr=M.extend({type:k(j.REASONING_ENCRYPTED_VALUE),subtype:gr,entityId:E(),encryptedValue:E(),subagentRunId:E().optional()}),wr=M.extend({type:k(j.SUBAGENT_STARTED),subagentRunId:E(),name:E(),description:E().optional(),parentSubagentRunId:E().optional(),parentToolCallId:E().optional(),parentMessageId:E().optional()}),Tr=$t(`type`,[O({type:k(`success`)}
1).strict(),O({type:k(`suspended`),interruptIds:Zt(E()).optional()}).strict()]),Er=$t(`type`,[Hn,Un,Wn,Gn,er,tr,Kn,qn,Jn,Yn,Xn,Zn,$n,Qn,nr,rr,ir,ar,or,sr,cr,lr,fr,pr,mr,hr,_r,vr,yr,br,xr,Sr,Cr,wr,M.extend({type:k(j.SUBAGENT_FINISHED),subagentRunId:E(),result:Yt().optional(),outcome:Tr.optional()}),M.extend({type:k(j.SUBAGENT_ERROR),subagentRunId:E(),message:E(),code:E().optional()})]),Dr=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Or=Object.prototype.hasOwnProperty;function kr(e,t){return Or.call(e,t)}function Ar(e){if(Array.isArray(e)){for(var t=Array(e.length),n=0;n<t.length;n++)t[n]=``+n;return t}if(Object.keys)return Object.keys(e);var r=[];for(var i in e)kr(e,i)&&r.push(i);return r}function jr(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Mr(e){for(var t=0,n=e.length,r;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function Nr(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Pr(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Fr(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Fr(e[t]))return!0}else if(typeof e==`object`){for(var r=Ar(e),i=r.length,a=0;a<i;a++)if(Fr(e[r[a]]))return!0}}return!1}function Ir(e,t){var n=[e];for(var r in t){var i=typeof t[r]==`object`?JSON.stringify(t[r],null,2):t[r];i!==void 0&&n.push(r+`: `+i)}return n.join(`
2`)}var Lr=function(e){Dr(t,e);function t(t,n,r,i,a){var o=this.constructor,s=e.call(this,Ir(t,{name:n,index:r,operation:i,tree:a}))||this;return s.name=n,s.index=r,s.operation=i,s.tree=a,Object.setPrototypeOf(s,o.prototype),s.message=Ir(t,{name:n,index:r,operation:i,tree:a}),s}return t}(Error),Rr=t({JsonPatchError:()=>zr,_areEquals:()=>Yr,applyOperation:()=>Wr,applyPatch:()=>Gr,applyReducer:()=>Kr,deepClone:()=>Br,getValueByPointer:()=>Ur,validate:()=>Jr,validator:()=>qr}),zr=Lr,Br=jr,Vr={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){var r=Ur(n,this.path);r&&=jr(r);var i=Wr(n,{op:`remove`,path:this.from}).removed;return Wr(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Ur(n,this.from);return Wr(n,{op:`add`,path:this.path,value:jr(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Yr(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Hr={add:function(e,t,n){return Mr(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:Vr.move,copy:Vr.copy,test:Vr.test,_get:Vr._get};function Ur(e,t){if(t==``)return e;var n={op:`_get`,path:t};return Wr(e,n),n.value}function Wr(e,t,n,r,i,a){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),a===void 0&&(a=0),n&&(typeof n==`function`?n(t,0,e,t.path):qr(t,0)),t.path===``){var o={newDocument:e};if(t.op===`add`)return o.newDocument=t.value,o;if(t.op===`replace`)return o.newDocument=t.value,o.removed=e,o;
vendor: 4,381 bytes, line 2
2if(t.op===`move`||t.op===`copy`)return o.newDocument=Ur(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=Yr(e,t.value),o.test===!1)throw new zr(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o.newDocument=e,o}if(t.op===`remove`)return o.removed=e,o.newDocument=null,o;if(t.op===`_get`)return t.value=e,o;if(n)throw new zr("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);return o}r||(e=jr(e));var s=(t.path||``).split(`/`),c=e,l=1,u=s.length,d=void 0,f=void 0,p=void 0;for(p=typeof n==`function`?n:qr;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=Pr(f)),i&&(f==`__proto__`||f==`prototype`&&l>0&&s[l-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[f]===void 0?d=s.slice(0,l).join(`/`):l==u-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(c)){if(f===`-`)f=c.length;else if(n&&!Mr(f))throw new zr(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else Mr(f)&&(f=~~f);if(l>=u){if(n&&t.op===`add`&&f>c.length)throw new zr(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);var o=Hr[t.op].call(t,c,f,e);if(o.test===!1)throw new zr(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}}else if(l>=u){var o=Vr[t.op].call(t,c,f,e);if(o.test===!1)throw new zr(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}if(c=c[f],n&&l<u&&(!c||typeof c!=`object`))throw new zr(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}function Gr(e,t,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(t))throw new zr(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=jr(e));for(var a=Array(t.length),o=0,s=t.length;o<s;o++)a[o]=Wr(e,t[o],n,!0,i,o),e=a[o].newDocument;return a.newDocument=e,a}function Kr(e,t,n){var r=Wr(e,t);if(r.test===!1)throw new zr(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function qr(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new zr(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!Vr[e.op])throw new zr("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new zr("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new zr('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new zr("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new zr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&Fr(e.value))throw new zr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new zr("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new zr(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=Jr([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new zr(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function Jr(e,t,n){try{if(!Array.isArray(e))throw new zr(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Gr(jr(t),jr(e),n||!0);else{n||=qr;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof zr)return e;throw e}}function Yr(e,t){if(e===t)return!0;
2if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!Yr(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!Yr(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}var Xr=t({compare:()=>si,generate:()=>ai,observe:()=>ii,unobserve:()=>ri}),Zr=new WeakMap,Qr=function(){function e(e){this.observers=new Map,this.obj=e}return e}(),$r=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function ei(e){return Zr.get(e)}function ti(e,t){return e.observers.get(t)}function ni(e,t){e.observers.delete(t.callback)}function ri(e,t){t.unobserve()}function ii(e,t){var n=[],r,i=ei(e);if(!i)i=new Qr(e),Zr.set(e,i);else{var a=ti(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=jr(e),t){r.callback=t,r.next=null;var o=function(){ai(r)},s=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<`u`&&(window.addEventListener(`mouseup`,s),window.addEventListener(`keyup`,s),window.addEventListener(`mousedown`,s),window.addEventListener(`keydown`,s),window.addEventListener(`change`,s))}return r.patches=n,r.object=e,r.unobserve=function(){ai(r),clearTimeout(r.next),ni(i,r),typeof window<`u`&&(window.removeEventListener(`mouseup`,s),window.removeEventListener(`keyup`,s),window.removeEventListener(`mousedown`,s),window.removeEventListener(`keydown`,s),window.removeEventListener(`change`,s))},i.observers.set(t,new $r(t,r)),r}function ai(e,t){t===void 0&&(t=!1);var n=Zr.get(e.object);oi(n.value,e.object,e.patches,``,t),e.patches.length&&Gr(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function oi(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=Ar(t),o=Ar(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(kr(t,l)&&(t[l]!==void 0||u===void 0||Array.isArray(t)!==!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?oi(u,d,n,r+`/`+Nr(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+Nr(l),value:jr(u)}),n.push({op:`replace`,path:r+`/`+Nr(l),value:jr(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+Nr(l),value:jr(u)}),n.push({op:`remove`,path:r+`/`+Nr(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!kr(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+Nr(l),value:jr(t[l])})}}}function si(e,t,n){n===void 0&&(n=!1);var r=[];return oi(e,t,r,``,n),r}var ci=Object.assign({},Rr,Xr,{JsonPatchError:Lr,deepClone:jr,escapePathComponent:Nr,unescapePathComponent:Pr}),li=function(e,t){return li=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},li(e,t)};function ui(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);li(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var di=function(){return di=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},di.apply(this,arguments)};function fi(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function pi(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function mi(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(
vendor: 16,059 bytes, lines 2-4
2o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function hi(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function gi(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function _i(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function vi(e){return this instanceof vi?(this.v=e,this):new vi(e)}function yi(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof vi?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function bi(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof hi==`function`?hi(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function xi(e){return typeof e==`function`}function Si(e){var t=e(function(e){Error.call(e),e.stack=Error().stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Ci=Si(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
3`+t.map(function(e,t){return t+1+`) `+e.toString()}).join(`
4  `):``,this.name=`UnsubscriptionError`,this.errors=t}});function wi(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Ti=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a){if(this._parentage=null,Array.isArray(a))try{for(var o=hi(a),s=o.next();!s.done;s=o.next())s.value.remove(this)}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else a.remove(this)}var c=this.initialTeardown;if(xi(c))try{c()}catch(e){i=e instanceof Ci?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=hi(l),d=u.next();!d.done;d=u.next()){var f=d.value;try{Oi(f)}catch(e){i??=[],e instanceof Ci?i=_i(_i([],gi(i)),gi(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(i)throw new Ci(i)}},e.prototype.add=function(t){if(t&&t!==this){if(this.closed)Oi(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=this._finalizers??[]).push(t)}}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&wi(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&wi(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e}(),Ei=Ti.EMPTY;function Di(e){return e instanceof Ti||e&&`closed`in e&&xi(e.remove)&&xi(e.add)&&xi(e.unsubscribe)}function Oi(e){xi(e)?e():e.unsubscribe()}var ki={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Ai={setTimeout:function(e,t){var n=[...arguments].slice(2),r=Ai.delegate;return r?.setTimeout?r.setTimeout.apply(r,_i([e,t],gi(n))):setTimeout.apply(void 0,_i([e,t],gi(n)))},clearTimeout:function(e){return(Ai.delegate?.clearTimeout||clearTimeout)(e)},delegate:void 0};function ji(e){Ai.setTimeout(function(){var t=ki.onUnhandledError;if(t)t(e);else throw e})}function Mi(){}var Ni=(function(){return Ii(`C`,void 0,void 0)})();function Pi(e){return Ii(`E`,void 0,e)}function Fi(e){return Ii(`N`,e,void 0)}function Ii(e,t,n){return{kind:e,value:t,error:n}}var Li=null;function Ri(e){if(ki.useDeprecatedSynchronousErrorHandling){var t=!Li;if(t&&(Li={errorThrown:!1,error:null}),e(),t){var n=Li,r=n.errorThrown,i=n.error;if(Li=null,r)throw i}}else e()}function zi(e){ki.useDeprecatedSynchronousErrorHandling&&Li&&(Li.errorThrown=!0,Li.error=e)}var Bi=function(e){ui(t,e);function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Di(t)&&t.add(n)):n.destination=Ji,n}return t.create=function(e,t,n){return new Wi(e,t,n)},t.prototype.next=function(e){this.isStopped?qi(Fi(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?qi(Pi(e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?qi(Ni,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Ti),Vi=Function.prototype.bind;function Hi(e,t){return Vi.call(e,t)}var Ui=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){Gi(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Gi(e)}else Gi(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Gi(e)}},e}(),Wi=function(e){ui(t,e);function t(t,n,r){var i=e.call(this)||this,a;if(xi(t)||!t)a={next:t??void 0,error:n??void 0,complete:r??void 0};else{var o;i&&ki.useDeprecatedNextContext?(o=Object.create(t),o.unsubscribe=function(){return i.unsubscribe()},a={next:t.next&&Hi(t.next,o),error:t.error&&Hi(t.error,o),complete:t.complete&&Hi(t.complete,o)}):a=t}return i.destination=new Ui(a),i}return t}(Bi);function Gi(e){ki.useDeprecatedSynchronousErrorHandling?zi(e):ji(e)}function Ki(e){throw e}function qi(e,t){var n=ki.onStoppedNotification;n&&Ai.setTimeout(function(){return n(e,t)})}var Ji={closed:!0,next:Mi,error:Ki,complete:Mi},Yi=(function(){return typeof Symbol==`function`&&Symbol.observable||`@@observable`})();function Xi(e){return e}function Zi(){return Qi([...arguments])}function Qi(e){return e.length===0?Xi:e.length===1?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)}}var $i=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this,i=na(e)?e:new Wi(e,t,n);return Ri(function(){var e=r,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?r._subscribe(i):r._trySubscribe(i))}),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return t=ea(t),new t(function(t,r){var i=new Wi({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){return this.source?.subscribe(e)},e.prototype[Yi]=function(){return this},e.prototype.pipe=function(){return Qi([...arguments])(this)},e.prototype.toPromise=function(e){var t=this;return e=ea(e),new e(function(e,n){var r;t.subscribe(function(e){return r=e},function(e){return n(e)},function(){return e(r)})})},e.create=function(t){return new e(t)},e}();function ea(e){return e??ki.Promise??Promise}function ta(e){return e&&xi(e.next)&&xi(e.error)&&xi(e.complete)}function na(e){return e&&e instanceof Bi||ta(e)&&Di(e)}function ra(e){return xi(e?.lift)}function ia(e){return function(t){if(ra(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw TypeError(`Unable to lift unknown Observable type`)}}function aa(e,t,n,r,i){return new oa(e,t,n,r,i)}var oa=function(e){ui(t,e);function t(t,n,r,i,a,o){var s=e.call(this,t)||this;return s.onFinalize=a,s.shouldUnsubscribe=o,s._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,s._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,s._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,s}return t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)==null||t.call(this))}},t}(Bi),sa=Si(function(e){return function(){e(this),this.name=`ObjectUnsubscribedError`,this.message=`object unsubscribed`}}),ca=function(e){ui(t,e);function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return t.prototype.lift=function(e){var t=new la(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new sa},t.prototype.next=function(e){var t=this;Ri(function(){var n,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||=Array.from(t.observers);try{for(var i=hi(t.currentObservers),a=i.next();!a.done;a=i.next())a.value.next(e)}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}})},t.prototype.error=function(e){var t=this;Ri(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}})},t.prototype.complete=function(){var e=this;Ri(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){return this.observers?.length>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,i=n.isStopped,a=n.observers;return r||i?Ei:(this.currentObservers=null,a.push(e),new Ti(function(){t.currentObservers=null,wi(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,i=t.isStopped;n?e.error(r):i&&e.complete()},t.prototype.asObservable=function(){var e=new $i;return e.source=this,e},t.create=function(e,t){return new la(e,t)},t}($i),la=function(e){ui(t,e);function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return t.prototype.next=function(e){var t,n;(n=(t=this.destination)?.next)==null||n.call(t,e)},t.prototype.error=function(e){var t,n;(n=(t=this.destination)?.error)==null||n.call(t,e)},t.prototype.complete=function(){var e,t;(t=(e=this.destination)?.complete)==null||t.call(e)},t.prototype._subscribe=function(e){return this.source?.subscribe(e)??Ei},t}(ca),ua=function(e){ui(t,e);function t(t){var n=e.call(this)||this;return n._value=t,n}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var n=e.prototype._subscribe.call(this,t);return!n.closed&&t.next(this._value),n},t.prototype.getValue=function(){var e=this,t=e.hasError,n=e.thrownError,r=e._value;if(t)throw n;return this._throwIfClosed(),r},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(ca),da={now:function(){return(da.delegate||Date).now()},delegate:void 0},fa=function(e){ui(t,e);function t(t,n,r){t===void 0&&(t=1/0),n===void 0&&(n=1/0),r===void 0&&(r=da);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return t.prototype.next=function(t){var n=this,r=n.isStopped,i=n._buffer,a=n._infiniteTimeWindow,o=n._timestampProvider,s=n._windowTime;r||(i.push(t),!a&&i.push(o.now()+s)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this,r=n._infiniteTimeWindow,i=n._buffer.slice(),a=0;a<i.length&&!e.closed;a+=r?1:2)e.next(i[a]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,n=e._timestampProvider,r=e._buffer,i=e._infiniteTimeWindow,a=(i?1:2)*t;if(t<1/0&&a<r.length&&r.splice(0,r.length-a),!i){for(var o=n.now(),s=0,c=1;c<r.length&&r[c]<=o;c+=2)s=c;s&&r.splice(0,s+1)}},t}(ca),pa=function(e){ui(t,e);function t(t,n){return e.call(this)||this}return t.prototype.schedule=function(e,t){return t===void 0&&(t=0),this},t}(Ti),ma={setInterval:function(e,t){var n=[...arguments].slice(2),r=ma.delegate;return r?.setInterval?r.setInterval.apply(r,_i([e,t],gi(n))):setInterval.apply(void 0,_i([e,t],gi(n)))},clearInterval:function(e){return(ma.delegate?.clearInterval||clearInterval)(e)},delegate:void 0},ha=function(e){ui(t,e);function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return t.prototype.schedule=function(e,t){if(t===void 0&&(t=0),this.closed)return this;this.state=e;var n=this.id,r=this.scheduler;return n!=null&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=this.id??this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return n===void 0&&(n=0),ma.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(n===void 0&&(n=0),n!=null&&this.delay===n&&this.pending===!1)return t;t!=null&&ma.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return Error(`executing a cancelled action`);this.pending=!1;var n=this._execute(e,t);if(n)return n;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n=!1,r;try{this.work(e)}catch(e){n=!0,r=e||Error(`Scheduled action threw falsy error`)}if(n)return this.unsubscribe(),r},t.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,r=t.scheduler,i=r.actions;
4this.work=this.state=this.scheduler=null,this.pending=!1,wi(i,this),n!=null&&(this.id=this.recycleAsyncId(r,n,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(pa),ga=1,_a,va={};function ya(e){return e in va&&(delete va[e],!0)}var ba={setImmediate:function(e){var t=ga++;return va[t]=!0,_a||=Promise.resolve(),_a.then(function(){return ya(t)&&e()}),t},clearImmediate:function(e){ya(e)}},xa=ba.setImmediate,Sa=ba.clearImmediate,Ca={setImmediate:function(){var e=[...arguments];return(Ca.delegate?.setImmediate||xa).apply(void 0,_i([],gi(e)))},clearImmediate:function(e){return(Ca.delegate?.clearImmediate||Sa)(e)},delegate:void 0},wa=function(e){ui(t,e);function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r}return t.prototype.requestAsyncId=function(t,n,r){return r===void 0&&(r=0),r!==null&&r>0?e.prototype.requestAsyncId.call(this,t,n,r):(t.actions.push(this),t._scheduled||=Ca.setImmediate(t.flush.bind(t,void 0)))},t.prototype.recycleAsyncId=function(t,n,r){if(r===void 0&&(r=0),r==null?this.delay>0:r>0)return e.prototype.recycleAsyncId.call(this,t,n,r);var i=t.actions;n!=null&&i[i.length-1]?.id!==n&&(Ca.clearImmediate(n),t._scheduled===n&&(t._scheduled=void 0))},t}(ha),Ta=function(){function e(t,n){n===void 0&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=da.now,e}(),Ea=function(e){ui(t,e);function t(t,n){n===void 0&&(n=Ta.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(e){var t=this.actions;if(this._active){t.push(e);return}var n;this._active=!0;do if(n=e.execute(e.state,e.delay))break;while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}},t}(Ta),Da=new(function(e){ui(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(e){this._active=!0;var t=this._scheduled;this._scheduled=void 0;var n=this.actions,r;e||=n.shift();do if(r=e.execute(e.state,e.delay))break;while((e=n[0])&&e.id===t&&n.shift());if(this._active=!1,r){for(;(e=n[0])&&e.id===t&&n.shift();)e.unsubscribe();throw r}},t}(Ea))(wa),Oa=new Ea(ha),ka=Oa,Aa=new $i(function(e){return e.complete()});function ja(e){return e&&xi(e.schedule)}function Ma(e){return e[e.length-1]}function Na(e){return xi(Ma(e))?e.pop():void 0}function Pa(e){return ja(Ma(e))?e.pop():void 0}function Fa(e,t){return typeof Ma(e)==`number`?e.pop():t}var Ia=(function(e){return e&&typeof e.length==`number`&&typeof e!=`function`});function La(e){return xi(e?.then)}function Ra(e){return xi(e[Yi])}function za(e){return Symbol.asyncIterator&&xi(e?.[Symbol.asyncIterator])}function Ba(e){return TypeError(`You provided `+(typeof e==`object`&&e?`an invalid object`:`'`+e+`'`)+` where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}function Va(){return typeof Symbol!=`function`||!Symbol.iterator?`@@iterator`:Symbol.iterator}var Ha=Va();function Ua(e){return xi(e?.[Ha])}function Wa(e){return yi(this,arguments,function(){var t,n,r,i;return mi(this,function(a){switch(a.label){case 0:t=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,vi(t.read())];case 3:return n=a.sent(),r=n.value,i=n.done,i?[4,vi(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,vi(r)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Ga(e){return xi(e?.getReader)}function Ka(e){if(e instanceof $i)return e;if(e!=null){if(Ra(e))return qa(e);if(Ia(e))return Ja(e);if(La(e))return Ya(e);if(za(e))return Za(e);if(Ua(e))return Xa(e);if(Ga(e))return Qa(e)}throw Ba(e)}function qa(e){return new $i(function(t){var n=e[Yi]();if(xi(n.subscribe))return n.subscribe(t);throw TypeError(`Provided object does not correctly implement Symbol.observable`)})}function Ja(e){return new $i(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function Ya(e){return new $i(function(t){e.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,ji)})}function Xa(e){return new $i(function(t){var n,r;try{for(var i=hi(e),a=i.next();!a.done;a=i.next()){var o=a.value;if(t.next(o),t.closed)return}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}t.complete()})}function Za(e){return new $i(function(t){$a(e,t).catch(function(e){return t.error(e)})})}function Qa(e){return Za(Wa(e))}function $a(e,t){var n,r,i,a;return pi(this,void 0,void 0,function(){var o,s;return mi(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=bi(e),c.label=1;case 1:return[4,n.next()];case 2:if(r=c.sent(),r.done)return[3,4];if(o=r.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return s=c.sent(),i={error:s},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(a=n.return)?[4,a.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];
4case 10:return[7];case 11:return t.complete(),[2]}})})}function eo(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var a=t.schedule(function(){n(),i?e.add(this.schedule(null,r)):this.unsubscribe()},r);if(e.add(a),!i)return a}function to(e,t){return t===void 0&&(t=0),ia(function(n,r){n.subscribe(aa(r,function(n){return eo(r,e,function(){return r.next(n)},t)},function(){return eo(r,e,function(){return r.complete()},t)},function(n){return eo(r,e,function(){return r.error(n)},t)}))})}function no(e,t){return t===void 0&&(t=0),ia(function(n,r){r.add(e.schedule(function(){return n.subscribe(r)},t))})}function ro(e,t){return Ka(e).pipe(no(t),to(t))}function io(e,t){return Ka(e).pipe(no(t),to(t))}function ao(e,t){return new $i(function(n){var r=0;return t.schedule(function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())})})}function oo(e,t){return new $i(function(n){var r;return eo(n,t,function(){r=e[Ha](),eo(n,t,function(){var e,t,i;try{e=r.next(),t=e.value,i=e.done}catch(e){n.error(e);return}i?n.complete():n.next(t)},0,!0)}),function(){return xi(r?.return)&&r.return()}})}function so(e,t){if(!e)throw Error(`Iterable cannot be null`);return new $i(function(n){eo(n,t,function(){var r=e[Symbol.asyncIterator]();eo(n,t,function(){r.next().then(function(e){e.done?n.complete():n.next(e.value)})},0,!0)})})}function co(e,t){return so(Wa(e),t)}function lo(e,t){if(e!=null){if(Ra(e))return ro(e,t);if(Ia(e))return ao(e,t);if(La(e))return io(e,t);if(za(e))return so(e,t);if(Ua(e))return oo(e,t);if(Ga(e))return co(e,t)}throw Ba(e)}function uo(e,t){return t?lo(e,t):Ka(e)}function N(){var e=[...arguments];return uo(e,Pa(e))}function P(e,t){var n=xi(e)?e:function(){return e},r=function(e){return e.error(n())};return new $i(t?function(e){return t.schedule(r,0,e)}:r)}var fo;(function(e){e.NEXT=`N`,e.ERROR=`E`,e.COMPLETE=`C`})(fo||={});var po=function(){function e(e,t,n){this.kind=e,this.value=t,this.error=n,this.hasValue=e===`N`}return e.prototype.observe=function(e){return mo(this,e)},e.prototype.do=function(e,t,n){var r=this,i=r.kind,a=r.value,o=r.error;return i===`N`?e?.(a):i===`E`?t?.(o):n?.()},e.prototype.accept=function(e,t,n){return xi(e?.next)?this.observe(e):this.do(e,t,n)},e.prototype.toObservable=function(){var e=this,t=e.kind,n=e.value,r=e.error,i=t===`N`?N(n):t===`E`?P(function(){return r}):t===`C`?Aa:0;if(!i)throw TypeError(`Unexpected notification kind `+t);return i},e.createNext=function(t){return new e(`N`,t)},e.createError=function(t){return new e(`E`,void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e(`C`),e}();function mo(e,t){var n,r,i,a=e,o=a.kind,s=a.value,c=a.error;if(typeof o!=`string`)throw TypeError(`Invalid notification, missing "kind"`);o===`N`?(n=t.next)==null||n.call(t,s):o===`E`?(r=t.error)==null||r.call(t,c):(i=t.complete)==null||i.call(t)}var ho=Si(function(e){return function(){e(this),this.name=`EmptyError`,this.message=`no elements in sequence`}});function go(e,t){var n=typeof t==`object`;return new Promise(function(r,i){var a=!1,o;e.subscribe({next:function(e){o=e,a=!0},error:i,complete:function(){a?r(o):n?r(t.defaultValue):i(new ho)}})})}function _o(e,t){var n=typeof t==`object`;return new Promise(function(r,i){var a=new Wi({next:function(e){r(e),a.unsubscribe()},error:i,complete:function(){n?r(t.defaultValue):i(new ho)}});e.subscribe(a)})}function vo(e){return e instanceof Date&&!isNaN(e)}var yo=Si(function(e){return function(t){t===void 0&&(t=null),e(this),this.message=`Timeout has occurred`,this.name=`TimeoutError`,this.info=t}});function bo(e,t){var n=vo(e)?{first:e}:typeof e==`number`?{each:e}:e,r=n.first,i=n.each,a=n.with,o=a===void 0?xo:a,s=n.scheduler,c=s===void 0?t??Oa:s,l=n.meta,u=l===void 0?null:l;if(r==null&&i==null)throw TypeError(`No timeout provided.`);return ia(function(e,t){var n,a,s=null,l=0,d=function(e){a=eo(t,c,function(){try{n.unsubscribe(),Ka(o({meta:u,lastValue:s,seen:l})).subscribe(t)}catch(e){t.error(e)}},e)};n=e.subscribe(aa(t,function(e){a?.unsubscribe(),l++,t.next(s=e),i>0&&d(i)},void 0,void 0,function(){a?.closed||a?.unsubscribe(),s=null})),!l&&d(r==null?i:typeof r==`number`?r:+r-c.now())})}function xo(e){throw new yo(e)}function F(e,t){return ia(function(n,r){var i=0;n.subscribe(aa(r,function(n){r.next(e.call(t,n,i++))}))})}var So=Array.isArray;function Co(e,t){return So(t)?e.apply(void 0,_i([],gi(t))):e(t)}function wo(e){return F(function(t){return Co(e,t)})}var To=Array.isArray,Eo=Object.getPrototypeOf,Do=Object.prototype,Oo=Object.keys;function ko(e){if(e.length===1){var t=e[0];if(To(t))return{args:t,keys:null};if(Ao(t)){var n=Oo(t);return{args:n.map(function(e){return t[e]}),keys:n}}}return{args:e,keys:null}}function Ao(e){return e&&typeof e==`object`&&Eo(e)===Do}function jo(e,t){return e.reduce(function(e,n,r){return e[n]=t[r],e},{})}function Mo(){var e=[...arguments],t=Pa(e),n=Na(e),r=ko(e),i=r.args,a=r.keys;if(i.length===0)return uo([],t);var o=new $i(No(i,t,a?function(e){return jo(a,e)}:Xi));return n?o.pipe(wo(n)):o}function No(e,t,n){return n===void 0&&(n=Xi),function(r){Po(t,function(){for(var i=e.length,a=Array(i),o=i,s=i,c=function(i){Po(t,function(){var c=uo(e[i],t),l=!1;c.subscribe(aa(r,function(e){a[i]=e,l||(l=!0,s--),s||r.next(n(a.slice()))},function(){--o||r.complete()}
4))},r)},l=0;l<i;l++)c(l)},r)}}function Po(e,t,n){e?eo(n,e,t):t()}function Fo(e,t,n,r,i,a,o,s){var c=[],l=0,u=0,d=!1,f=function(){d&&!c.length&&!l&&t.complete()},p=function(e){return l<r?m(e):c.push(e)},m=function(e){a&&t.next(e),l++;var s=!1;Ka(n(e,u++)).subscribe(aa(t,function(e){i?.(e),a?p(e):t.next(e)},function(){s=!0},void 0,function(){if(s)try{l--;for(var e=function(){var e=c.shift();o?eo(t,o,function(){return m(e)}):m(e)};c.length&&l<r;)e();f()}catch(e){t.error(e)}}))};return e.subscribe(aa(t,p,function(){d=!0,f()})),function(){s?.()}}function Io(e,t,n){return n===void 0&&(n=1/0),xi(t)?Io(function(n,r){return F(function(e,i){return t(n,e,r,i)})(Ka(e(n,r)))},n):(typeof t==`number`&&(n=t),ia(function(t,r){return Fo(t,r,e,n)}))}function Lo(e){return e===void 0&&(e=1/0),Io(Xi,e)}function Ro(){return Lo(1)}function zo(){var e=[...arguments];return Ro()(uo(e,Pa(e)))}function Bo(e){return new $i(function(t){Ka(e()).subscribe(t)})}function Vo(e,t,n){e===void 0&&(e=0),n===void 0&&(n=ka);var r=-1;return t!=null&&(ja(t)?n=t:r=t),new $i(function(t){var i=vo(e)?+e-n.now():e;i<0&&(i=0);var a=0;return n.schedule(function(){t.closed||(t.next(a++),0<=r?this.schedule(void 0,r):t.complete())},i)})}function Ho(){var e=[...arguments],t=Pa(e),n=Fa(e,1/0),r=e;return r.length?r.length===1?Ka(r[0]):Lo(n)(uo(r,t)):Aa}var Uo=new $i(Mi);function Wo(e,t){return ia(function(n,r){var i=0;n.subscribe(aa(r,function(n){return e.call(t,n,i++)&&r.next(n)}))})}function Go(e){return ia(function(t,n){var r=null,i=!1,a;r=t.subscribe(aa(n,void 0,void 0,function(o){a=Ka(e(o,Go(e)(t))),r?(r.unsubscribe(),r=null,a.subscribe(n)):i=!0})),i&&(r.unsubscribe(),r=null,a.subscribe(n))})}function Ko(e,t,n,r,i){return function(a,o){var s=n,c=t,l=0;a.subscribe(aa(o,function(t){var n=l++;c=s?e(c,t,n):(s=!0,t),r&&o.next(c)},i&&(function(){s&&o.next(c),o.complete()})))}}function qo(e,t){return xi(t)?Io(e,t,1):Io(e,1)}function Jo(){var e=[...arguments],t=Pa(e);return ia(function(n,r){Ro()(uo(_i([n],gi(e)),t)).subscribe(r)})}function Yo(){var e=[...arguments];return Jo.apply(void 0,_i([],gi(e)))}function Xo(e){return ia(function(t,n){var r=!1;t.subscribe(aa(n,function(e){r=!0,n.next(e)},function(){r||n.next(e),n.complete()}))})}function Zo(e){return e<=0?function(){return Aa}:ia(function(t,n){var r=0;t.subscribe(aa(n,function(t){++r<=e&&(n.next(t),e<=r&&n.complete())}))})}function Qo(){return ia(function(e,t){e.subscribe(aa(t,Mi))})}function $o(e){return F(function(){return e})}function es(e,t){return t?function(n){return zo(t.pipe(Zo(1),Qo()),n.pipe(es(e)))}:Io(function(t,n){return Ka(e(t,n)).pipe(Zo(1),$o(t))})}function ts(e,t){t===void 0&&(t=Oa);var n=Vo(e,t);return es(function(){return n})}function ns(){return ia(function(e,t){e.subscribe(aa(t,function(e){return mo(e,t)}))})}function rs(e,t){return t===void 0&&(t=Xi),e??=is,ia(function(n,r){var i,a=!0;n.subscribe(aa(r,function(n){var o=t(n);(a||!e(i,o))&&(a=!1,i=o,r.next(n))}))})}function is(e,t){return e===t}function as(){var e=[...arguments];return function(t){return zo(t,N.apply(void 0,_i([],gi(e))))}}function os(e){return ia(function(t,n){try{t.subscribe(n)}finally{n.add(e)}})}function ss(e,t){return ia(Ko(e,t,arguments.length>=2,!0))}function cs(e){e===void 0&&(e={});var t=e.connector,n=t===void 0?function(){return new ca}:t,r=e.resetOnError,i=r===void 0||r,a=e.resetOnComplete,o=a===void 0||a,s=e.resetOnRefCountZero,c=s===void 0||s;return function(e){var t,r,a,s=0,l=!1,u=!1,d=function(){r?.unsubscribe(),r=void 0},f=function(){d(),t=a=void 0,l=u=!1},p=function(){var e=t;f(),e?.unsubscribe()};return ia(function(e,m){s++,!u&&!l&&d();var h=a??=n();m.add(function(){s--,s===0&&!u&&!l&&(r=ls(p,c))}),h.subscribe(m),!t&&s>0&&(t=new Wi({next:function(e){return h.next(e)},error:function(e){u=!0,d(),r=ls(f,i,e),h.error(e)},complete:function(){l=!0,d(),r=ls(f,o),h.complete()}}),Ka(e).subscribe(t))})(e)}}function ls(e,t){var n=[...arguments].slice(2);if(t===!0){e();return}if(t!==!1){var r=new Wi({next:function(){r.unsubscribe(),e()}});return Ka(t.apply(void 0,_i([],gi(n)))).subscribe(r)}}function us(e,t,n){var r,i,a,o,s=!1;return e&&typeof e==`object`?(r=e.bufferSize,o=r===void 0?1/0:r,i=e.windowTime,t=i===void 0?1/0:i,a=e.refCount,s=a!==void 0&&a,n=e.sc
4heduler):o=e??1/0,cs({connector:function(){return new fa(o,t,n)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}function ds(e,t){return ia(function(n,r){var i=null,a=0,o=!1,s=function(){return o&&!i&&r.complete()};n.subscribe(aa(r,function(n){i?.unsubscribe();var o=0,c=a++;Ka(e(n,c)).subscribe(i=aa(r,function(e){return r.next(t?t(n,e,c,o++):e)},function(){i=null,s()}))},function(){o=!0,s()}))})}function fs(e){return ia(function(t,n){Ka(e).subscribe(aa(n,function(){return n.complete()},Mi)),!n.closed&&t.subscribe(n)})}function ps(e,t,n){var r=xi(e)||t||n?{next:e,error:t,complete:n}:e;return r?ia(function(e,t){var n;(n=r.subscribe)==null||n.call(r);var i=!0;e.subscribe(aa(t,function(e){var n;(n=r.next)==null||n.call(r,e),t.next(e)},function(){var e;i=!1,(e=r.complete)==null||e.call(r),t.complete()},function(e){var n;i=!1,(n=r.error)==null||n.call(r,e),t.error(e)},function(){var e,t;i&&((e=r.unsubscribe)==null||e.call(r)),(t=r.finalize)==null||t.call(r)}))}):Xi}function ms(){var e=[...arguments],t=Na(e);return ia(function(n,r){for(var i=e.length,a=Array(i),o=e.map(function(){return!1}),s=!1,c=function(t){Ka(e[t]).subscribe(aa(r,function(e){a[t]=e,!s&&!o[t]&&(o[t]=!0,(s=o.every(Xi))&&(o=null))},Mi))},l=0;l<i;l++)c(l);n.subscribe(aa(r,function(e){if(s){var n=_i([e],gi(a));r.next(t?t.apply(void 0,_i([],gi(n))):n)}}))})}function hs(e){return` \r
5	`.indexOf(e)>=0}function gs(e){for(var t=[`topLevel`],n=0,r,i,a,o=function(e){return t.push(e)},s=function(e){return t[t.length-1]=e},c=function(e){r??(r=n,i=t.length,a=e)},l=function(e){e===a&&(r=void 0,i=void 0,a=void 0)},u=function(){return t.pop()},d=function(){return n--},f=function(e){if(`0`<=e&&e<=`9`){o(`number`);return}switch(e){case`"`:o(`string`);return;case`-`:o(`numberNeedsDigit`);return;case`t`:o(`true`);return;case`f`:o(`false`);return;case`n`:o(`null`);return;case`[`:o(`arrayNeedsValue`);return;case`{`:o(`objectNeedsKey`);return}},p=e.length;n<p;n++){var m=e[n];switch(t[t.length-1]){case`topLevel`:f(m);break;case`string`:switch(m){case`"`:u();break;case`\\`:c(`stringEscape`),o(`stringEscaped`)}break;case`stringEscaped`:m===`u`?o(`stringUnicode`):(l(`stringEscape`),u());break;case`stringUnicode`:n-e.lastIndexOf(`u`,n)===4&&(l(`stringEscape`),u());break;case`number`:m===`.`?s(`numberNeedsDigit`):m===`e`||m===`E`?s(`numberNeedsExponent`):(m<`0`||m>`9`)&&(d(),u());break;case`numberNeedsDigit`:s(`number`);break;case`numberNeedsExponent`:s(m===`+`||m===`-`?`numberNeedsDigit`:`number`);break;case`true`:case`false`:case`null`:(m<`a`||m>`z`)&&(d(),u());break;case`arrayNeedsValue`:m===`]`?u():hs(m)||(l(`collectionItem`),s(`arrayNeedsComma`),f(m));break;case`arrayNeedsComma`:m===`]`?u():m===`,`&&(c(`collectionItem`),s(`arrayNeedsValue`));break;case`objectNeedsKey`:m===`}`?u():m===`"`&&(c(`collectionItem`),s(`objectNeedsColon`),o(`string`));break;case`objectNeedsColon`:m===`:`&&s(`objectNeedsValue`);break;case`objectNeedsValue`:hs(m)||(l(`collectionItem`),s(`objectNeedsComma`),f(m));break;case`objectNeedsComma`:m===`}`?u():m===`,`&&(c(`collectionItem`),s(`objectNeedsKey`))}}i!=null&&(t.length=i);for(var h=[r==null?e:e.slice(0,r)],g=function(t){return h.push(t.slice(e.length-e.lastIndexOf(t[0])))},ee=t.length-1;ee>=0;ee--)switch(t[ee]){case`string`:h.push(`"`);break;case`numberNeedsDigit`:case`numberNeedsExponent`:h.push(`0`);break;case`true`:g(`true`);break;case`false`:g(`false`);break;case`null`:g(`null`);break;case`arrayNeedsValue`:case`arrayNeedsComma`:h.push(`]`);break;case`objectNeedsKey`:case`objectNeedsColon`:case`objectNeedsValue`:case`objectNeedsComma`:h.push(`}`)}return h.join(``)}function _s(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function vs(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>
528&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var ys=4294967296;function bs(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=ys&&(i+=r/ys|0,r%=ys)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?Ts(r,i):ws(r,i)}function xs(e,t){let n=ws(e,t),r=n.hi&2147483648;r&&(n=Ts(n.lo,n.hi));let i=Ss(n.lo,n.hi);return r?`-`+i:i}function Ss(e,t){if({lo:e,hi:t}=Cs(e,t),t<=2097151)return String(ys*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+Es(o)+Es(a)}function Cs(e,t){return{lo:e>>>0,hi:t>>>0}}function ws(e,t){return{lo:e|0,hi:t|0}}function Ts(e,t){return t=~t,e?e=~e+1:t+=1,ws(e,t)}var Es=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function Ds(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function Os(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}var ks=As();function As(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(globalThis.Deno||typeof process!=`object`||{NODE_ENV:`development`}.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`invalid int64: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`invalid uint64: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),js(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),Ms(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),js(e),bs(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),Ms(e),bs(e)},dec(e,t){return xs(e,t)},uDec(e,t){return Ss(e,t)}}}function js(e){if(!/^-?[0-9]+$/.test(e))throw Error(`invalid int64: `+e)}function Ms(e){if(!/^[0-9]+$/.test(e))throw Error(`invalid uint64: `+e)}var Ns=Symbol.for(`@bufbuild/protobuf/text-encoding`);function Ps(){if(globalThis[Ns]==null){let e=new globalThis.TextEncoder,t=new globalThis.TextDecoder,n;globalThis[Ns]={encodeUtf8(t){return e.encode(t)},decodeUtf8(e,r){return r?(n===void 0&&(n=new globalThis.TextDecoder(`utf-8`,{fatal:!0})),n.decode(e)):t.decode(e)},checkUtf8(e){try{return!0}catch{return!1}}}}return globalThis[Ns]}var Fs;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(Fs||={});var I=class{constructor(e=Ps().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ls(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return Is(e),Ds(e,this.buf),this}bool(e){return this.buf.push(+!!e),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Rs(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ls(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Is(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Is(e),e=(e<<1^e>>31)>>>0,Ds(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ks.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ks.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ks.enc(e);return vs(t.lo,t.hi,this.buf),this}sint64(e){let t=ks.enc(e),n=t.hi>>31;return vs(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=ks.uEnc(e);return vs(t.lo,t.hi,this.buf),this}},L=class{constructor(e,t=Ps().decodeUtf8){this.decodeUtf8=t,this.varint64=_s,this.uint32=Os,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,t=this.uint32(),n=this.pos-e;if(n>5||n==5&&this.buf[this.pos-1]>15)throw Error(`illegal tag: varint overflows uint32`);let r=t>>>3,i=t&7;if(r<=0||i>5)throw Error(`illegal tag: field no `+r+` wire type `+i);return[r,i]}skip(e,t){let n=this.pos;switch(e){case Fs.Varint:for(;this.buf[this.pos++]&128;);break;case Fs.Bit64:this.pos+=4;case Fs.Bit32:this.pos+=4;break;case Fs.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Fs.StartGroup:for(;;){let[e,n]=this.tag();if(n===Fs.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ks.dec(...this.varint64())}uint64(){return ks.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,ks.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ks.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ks.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(e){return this.decodeUtf8(this.bytes(),e)}};function Is(e){if(typeof e==`string`)e=Number(e);else if(typeof e!=`number`)throw Error(`invalid int32: `+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error(`invalid int32: `+e)}function Ls(e){if(typeof e==`string`)e=Number(e);else if(typeof e!=`number`)throw Error(`invalid uint32: `+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error(`invalid uint32: `+e)}function Rs(e){if(typeof e==`string`){let t=e;if(e=Number(e),Number.isNaN(e)&&t!==`NaN`)throw Error(`invalid float32: `+t)}else if(typeof e!=`number`)throw Error(`invalid float32: `+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error(`invalid float32: `+e)}var zs=function(e){return e[e.NULL_VALUE=0]=`NULL_VALUE`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function Bs(){return{fields:{}}}var Vs={encode(e,t=new I){return Object.entries(e.fields).forEac
vendor: 50,783 bytes, line 5
5h(([e,n])=>{n!==void 0&&Us.encode({key:e,value:n},t.uint32(10).fork()).join()}),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Bs();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:{if(e!==10)break;let t=Us.decode(n,n.uint32());t.value!==void 0&&(i.fields[t.key]=t.value);continue}}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Vs.fromPartial(e??{})},fromPartial(e){let t=Bs();return t.fields=Object.entries(e.fields??{}).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),{}),t},wrap(e){let t=Bs();if(e!==void 0)for(let n of Object.keys(e))t.fields[n]=e[n];return t},unwrap(e){let t={};if(e.fields)for(let n of Object.keys(e.fields))t[n]=e.fields[n];return t}};function Hs(){return{key:``,value:void 0}}var Us={encode(e,t=new I){return e.key!==``&&t.uint32(10).string(e.key),e.value!==void 0&&R.encode(R.wrap(e.value),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Hs();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.key=n.string();continue;case 2:if(e!==18)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Us.fromPartial(e??{})},fromPartial(e){let t=Hs();return t.key=e.key??``,t.value=e.value??void 0,t}};function Ws(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var R={encode(e,t=new I){return e.nullValue!==void 0&&t.uint32(8).int32(e.nullValue),e.numberValue!==void 0&&t.uint32(17).double(e.numberValue),e.stringValue!==void 0&&t.uint32(26).string(e.stringValue),e.boolValue!==void 0&&t.uint32(32).bool(e.boolValue),e.structValue!==void 0&&Vs.encode(Vs.wrap(e.structValue),t.uint32(42).fork()).join(),e.listValue!==void 0&&Ks.encode(Ks.wrap(e.listValue),t.uint32(50).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Ws();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==8)break;i.nullValue=n.int32();continue;case 2:if(e!==17)break;i.numberValue=n.double();continue;case 3:if(e!==26)break;i.stringValue=n.string();continue;case 4:if(e!==32)break;i.boolValue=n.bool();continue;case 5:if(e!==42)break;i.structValue=Vs.unwrap(Vs.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.listValue=Ks.unwrap(Ks.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return R.fromPartial(e??{})},fromPartial(e){let t=Ws();return t.nullValue=e.nullValue??void 0,t.numberValue=e.numberValue??void 0,t.stringValue=e.stringValue??void 0,t.boolValue=e.boolValue??void 0,t.structValue=e.structValue??void 0,t.listValue=e.listValue??void 0,t},wrap(e){let t=Ws();if(e===null)t.nullValue=zs.NULL_VALUE;else if(typeof e==`boolean`)t.boolValue=e;else if(typeof e==`number`)t.numberValue=e;else if(typeof e==`string`)t.stringValue=e;else if(globalThis.Array.isArray(e))t.listValue=e;else if(typeof e==`object`)t.structValue=e;else if(e!==void 0)throw new globalThis.Error(`Unsupported any value type: `+typeof e);return t},unwrap(e){if(e.stringValue!==void 0)return e.stringValue;if(e?.numberValue!==void 0)return e.numberValue;if(e?.boolValue!==void 0)return e.boolValue;if(e?.structValue!==void 0)return e.structValue;if(e?.listValue!==void 0)return e.listValue;if(e?.nullValue!==void 0)return null}};function Gs(){return{values:[]}}var Ks={encode(e,t=new I){for(let n of e.values)R.encode(R.wrap(n),t.uint32(10).fork()).join();return t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Gs();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.values.push(R.unwrap(R.decode(n,n.uint32())));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Ks.fromPartial(e??{})},fromPartial(e){let t=Gs();return t.values=e.values?.map(e=>e)||[],t},wrap(e){let t=Gs();return t.values=e??[],t},unwrap(e){return e?.hasOwnProperty(`values`)&&globalThis.Array.isArray(e.values)?e.values:e}},qs=function(e){return e[e.ADD=0]=`ADD`,e[e.REMOVE=1]=`REMOVE`,e[e.REPLACE=2]=`REPLACE`,e[e.MOVE=3]=`MOVE`,e[e.COPY=4]=`COPY`,e[e.TEST=5]=`TEST`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function Js(){return{op:0,path:``,from:void 0,value:void 0}}var Ys={encode(e,t=new I){return e.op!==0&&t.uint32(8).int32(e.op),e.path!==``&&t.uint32(18).string(e.path),e.from!==void 0&&t.uint32(26).string(e.from),e.value!==void 0&&R.encode(R.wrap(e.value),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Js();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==8)break;i.op=n.int32();continue;case 2:if(e!==18)break;i.path=n.string();continue;case 3:if(e!==26)break;i.from=n.string();continue;case 4:if(e!==34)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Ys.fromPartial(e??{})},fromPartial(e){let t=Js();return t.op=e.op??0,t.path=e.path??``,t.from=e.from??void 0,t.value=e.value??void 0,t}};function Xs(){return{id:``,type:``,function:void 0,metadata:void 0}}var Zs={encode(e,t=new I){return e.id!==``&&t.uint32(10).string(e.id),e.type!==``&&t.uint32(18).string(e.type),e.function!==void 0&&$s.encode(e.function,t.uint32(26).fork()).join(),e.metadata!==void 0&&Vs.encode(Vs.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Xs();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.type=n.string();continue;case 3:if(e!==26)break;i.function=$s.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.metadata=Vs.unwrap(Vs.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Zs.fromPartial(e??{})},fromPartial(e){let t=Xs();return t.id=e.id??``,t.type=e.type??``,t.function=e.function!==void 0&&e.function!==null?$s.fromPartial(e.function):void 0,t.metadata=e.metadata??void 0,t}};function Qs(){return{name:``,arguments:``}}var $s={encode(e,t=new I){return e.name!==``&&t.uint32(10).string(e.name),e.arguments!==``&&t.uint32(18).string(e.arguments),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Qs();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.name=n.string();continue;case 2:if(e!==18)break;i.arguments=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return $s.fromPartial(e??{})},fromPartial(e){let t=Qs();return t.name=e.name??``,t.arguments=e.arguments??``,t}};function ec(){return{value:``,mimeType:``}}var tc={encode(e,t=new I){return e.value!==``&&t.uint32(10).string(e.value),e.mimeType!==``&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=ec();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return tc.fromPartial(e??{})},fromPartial(e){let t=ec();return t.value=e.value??``,t.mimeType=e.mimeType??``,t}};function nc(){return{value:``,mimeType:void 0}}var rc={encode(e,t=new I){return e.value!==``&&t.uint32(10).string(e.value),e.mimeType!==void 0&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=nc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rc.fromPartial(e??{})},fromPartial(e){let t=nc();return t.value=e.value??``,t.mimeType=e.mimeType??void 0,t}};function ic(){return{data:void 0,url:void 0}}var ac={encode(e,t=new I){return e.data!==void 0&&tc.encode(e.data,t.uint32(10).fork()).join(),e.url!==void 0&&rc.encode(e.url,t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=ic();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.data=tc.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.url=rc.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return ac.fromPartial(e??{})},fromPartial(e){let t=ic();return t.data=e.data!==void 0&&e.data!==null?tc.fromPartial(e.data):void 0,t.url=e.url!==void 0&&e.url!==null?rc.fromPartial(e.url):void 0,t}};function oc(){return{text:``}}var sc={encode(e,t=new I){return e.text!==``&&t.uint32(10).string(e.text),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=oc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.text=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return sc.fromPartial(e??{})},fromPartial(e){let t=oc();return t.text=e.text??``,t}};function cc(){return{source:void 0,metadata:void 0}}var lc={encode(e,t=new I){return e.source!==void 0&&ac.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&R.encode(R.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=cc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.source=ac.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return lc.fromPartial(e??{})},fromPartial(e){let t=cc();return t.source=e.source!==void 0&&e.source!==null?ac.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function uc(){return{source:void 0,metadata:void 0}}var dc={encode(e,t=new I){return e.source!==void 0&&ac.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&R.encode(R.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=uc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.source=ac.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dc.fromPartial(e??{})},fromPartial(e){let t=uc();return t.source=e.source!==void 0&&e.source!==null?ac.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function fc(){return{source:void 0,metadata:void 0}}var pc={encode(e,t=new I){return e.source!==void 0&&ac.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&R.encode(R.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=fc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.source=ac.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return pc.fromPartial(e??{})},fromPartial(e){let t=fc();return t.source=e.source!==void 0&&e.source!==null?ac.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function mc(){return{source:void 0,metadata:void 0}}var hc={encode(e,t=new I){return e.source!==void 0&&ac.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&R.encode(R.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=mc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.source=ac.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return hc.fromPartial(e??{})},fromPartial(e){let t=mc();return t.source=e.source!==void 0&&e.source!==null?ac.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function gc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var _c={encode(e,t=new I){return e.text!==void 0&&sc.encode(e.text,t.uint32(10).fork()).join(),e.image!==void 0&&lc.encode(e.image,t.uint32(18).fork()).join(),e.audio!==void 0&&dc.encode(e.audio,t.uint32(26).fork()).join(),e.video!==void 0&&pc.encode(e.video,t.uint32(34).fork()).join(),e.document!==void 0&&hc.encode(e.document,t.uint32(42).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=gc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.text=sc.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.image=lc.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.audio=dc.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.video=pc.decode(n,n.uint32());continue;case 5:if(e!==42)break;i.document=hc.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return _c.fromPartial(e??{})},fromPartial(e){let t=gc();return t.text=e.text!==void 0&&e.text!==null?sc.fromPartial(e.text):void 0,t.image=e.image!==void 0&&e.image!==null?lc.fromPartial(e.image):void 0,t.audio=e.audio!==void 0&&e.audio!==null?dc.fromPartial(e.audio):void 0,t.video=e.video!==void 0&&e.video!==null?pc.fromPartial(e.video):void 0,t.document=e.document!==void 0&&e.document!==null?hc.fromPartial(e.document):void 0,t}};function vc(){return{id:``,role:``,content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[],metadata:void 0,subagentRunId:void 0}}var yc={encode(e,t=new I){e.id!==``&&t.uint32(10).string(e.id),e.role!==``&&t.uint32(18).string(e.role),e.content!==void 0&&t.uint32(26).string(e.content),e.name!==void 0&&t.uint32(34).string(e.name);for(let n of e.toolCalls)Zs.encode(n,t.uint32(42).fork()).join();e.toolCallId!==void 0&&t.uint32(50).string(e.toolCallId),e.error!==void 0&&t.uint32(58).string(e.error);for(let n of e.contentParts)_c.encode(n,t.uint32(66).fork()).join();return e.metadata!==void 0&&Vs.encode(Vs.wrap(e.metadata),t.uint32(74).fork()).join(),e.subagentRunId!==void 0&&t.uint32(82).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=vc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.role=n.string();continue;case 3:if(e!==26)break;i.content=n.string();continue;case 4:if(e!==34)break;i.name=n.string();continue;case 5:if(e!==42)break;i.toolCalls.push(Zs.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.toolCallId=n.string();continue;case 7:if(e!==58)break;i.error=n.string();continue;case 8:if(e!==66)break;i.contentParts.push(_c.decode(n,n.uint32()));continue;case 9:if(e!==74)break;i.metadata=Vs.unwrap(Vs.decode(n,n.uint32()));continue;case 10:if(e!==82)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return yc.fromPartial(e??{})},fromPartial(e){let t=vc();return t.id=e.id??``,t.role=e.role??``,t.content=e.content??void 0,t.name=e.name??void 0,t.toolCalls=e.toolCalls?.map(e=>Zs.fromPartial(e))||[],t.toolCallId=e.toolCallId??void 0,t.error=e.error??void 0,t.contentParts=e.contentParts?.map(e=>_c.fromPartial(e))||[],t.metadata=e.metadata??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function bc(){return{id:``,reason:``,message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0,subagentRunId:void 0}}var xc={encode(e,t=new I){return e.id!==``&&t.uint32(10).string(e.id),e.reason!==``&&t.uint32(18).string(e.reason),e.message!==void 0&&t.uint32(26).string(e.message),e.toolCallId!==void 0&&t.uint32(34).string(e.toolCallId),e.responseSchema!==void 0&&R.encode(R.wrap(e.responseSchema),t.uint32(42).fork()).join(),e.expiresAt!==void 0&&t.uint32(50).string(e.expiresAt),e.metadata!==void 0&&R.encode(R.wrap(e.metadata),t.uint32(58).fork()).join(),e.subagentRunId!==void 0&&t.uint32(66).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=bc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.reason=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.toolCallId=n.string();continue;case 5:if(e!==42)break;i.responseSchema=R.unwrap(R.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.expiresAt=n.string();continue;case 7:if(e!==58)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return xc.fromPartial(e??{})},fromPartial(e){let t=bc();return t.id=e.id??``,t.reason=e.reason??``,t.message=e.message??void 0,t.toolCallId=e.toolCallId??void 0,t.responseSchema=e.responseSchema??void 0,t.expiresAt=e.expiresAt??void 0,t.metadata=e.metadata??void 0,t.subagentRunId=e.subagentRunId??void 0,t}},Sc=function(e){return e[e.TEXT_MESSAGE_START=0]=`TEXT_MESSAGE_START`,e[e.TEXT_MESSAGE_CONTENT=1]=`TEXT_MESSAGE_CONTENT`,e[e.TEXT_MESSAGE_END=2]=`TEXT_MESSAGE_END`,e[e.TOOL_CALL_START=3]=`TOOL_CALL_START`,e[e.TOOL_CALL_ARGS=4]=`TOOL_CALL_ARGS`,e[e.TOOL_CALL_END=5]=`TOOL_CALL_END`,e[e.STATE_SNAPSHOT=6]=`STATE_SNAPSHOT`,e[e.STATE_DELTA=7]=`STATE_DELTA`,e[e.MESSAGES_SNAPSHOT=8]=`MESSAGES_SNAPSHOT`,e[e.RAW=9]=`RAW`,e[e.CUSTOM=10]=`CUSTOM`,e[e.RUN_STARTED=11]=`RUN_STARTED`,e[e.RUN_FINISHED=12]=`RUN_FINISHED`,e[e.RUN_ERROR=13]=`RUN_ERROR`,e[e.STEP_STARTED=14]=`STEP_STARTED`,e[e.STEP_FINISHED=15]=`STEP_FINISHED`,e[e.SUBAGENT_STARTED=16]=`SUBAGENT_STARTED`,e[e.SUBAGENT_FINISHED=17]=`SUBAGENT_FINISHED`,e[e.SUBAGENT_ERROR=18]=`SUBAGENT_ERROR`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function Cc(){return{type:0,timestamp:void 0,rawEvent:void 0,metadata:void 0}}var z={encode(e,t=new I){return e.type!==0&&t.uint32(8).int32(e.type),e.timestamp!==void 0&&t.uint32(16).int64(e.timestamp),e.rawEvent!==void 0&&R.encode(R.wrap(e.rawEvent),t.uint32(26).fork()).join(),e.metadata!==void 0&&Vs.encode(Vs.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Cc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==8)break;i.type=n.int32();continue;case 2:if(e!==16)break;i.timestamp=gl(n.int64());continue;case 3:if(e!==26)break;i.rawEvent=R.unwrap(R.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=Vs.unwrap(Vs.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return z.fromPartial(e??{})},fromPartial(e){let t=Cc();return t.type=e.type??0,t.timestamp=e.timestamp??void 0,t.rawEvent=e.rawEvent??void 0,t.metadata=e.metadata??void 0,t}};function wc(){return{baseEvent:void 0,messageId:``,role:void 0,name:void 0,subagentRunId:void 0}}var Tc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.name!==void 0&&t.uint32(34).string(e.name),e.subagentRunId!==void 0&&t.uint32(42).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=wc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.role=n.string();continue;case 4:if(e!==34)break;i.name=n.string();continue;case 5:if(e!==42)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Tc.fromPartial(e??{})},fromPartial(e){let t=wc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.role=e.role??void 0,t.name=e.name??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Ec(){return{baseEvent:void 0,messageId:``,delta:``,subagentRunId:void 0}}var Dc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.delta!==``&&t.uint32(26).string(e.delta),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Ec();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.delta=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Dc.fromPartial(e??{})},fromPartial(e){let t=Ec();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.delta=e.delta??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Oc(){return{baseEvent:void 0,messageId:``,subagentRunId:void 0}}var kc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Oc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return kc.fromPartial(e??{})},fromPartial(e){let t=Oc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Ac(){return{baseEvent:void 0,toolCallId:``,toolCallName:``,parentMessageId:void 0,subagentRunId:void 0}}var jc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.toolCallName!==``&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.subagentRunId!==void 0&&t.uint32(42).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Ac();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.toolCallName=n.string();continue;case 4:if(e!==34)break;i.parentMessageId=n.string();continue;case 5:if(e!==42)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return jc.fromPartial(e??{})},fromPartial(e){let t=Ac();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.toolCallName=e.toolCallName??``,t.parentMessageId=e.parentMessageId??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Mc(){return{baseEvent:void 0,toolCallId:``,delta:``,subagentRunId:void 0}}var Nc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.delta!==``&&t.uint32(26).string(e.delta),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Mc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.delta=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Nc.fromPartial(e??{})},fromPartial(e){let t=Mc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.delta=e.delta??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Pc(){return{baseEvent:void 0,toolCallId:``,subagentRunId:void 0}}var Fc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Pc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Fc.fromPartial(e??{})},fromPartial(e){let t=Pc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Ic(){return{baseEvent:void 0,snapshot:void 0,subagentRunId:void 0}}var Lc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.snapshot!==void 0&&R.encode(R.wrap(e.snapshot),t.uint32(18).fork()).join(),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Ic();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.snapshot=R.unwrap(R.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Lc.fromPartial(e??{})},fromPartial(e){let t=Ic();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.snapshot=e.snapshot??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Rc(){return{baseEvent:void 0,delta:[],subagentRunId:void 0}}var zc={encode(e,t=new I){e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.delta)Ys.encode(n,t.uint32(18).fork()).join();return e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Rc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.delta.push(Ys.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return zc.fromPartial(e??{})},fromPartial(e){let t=Rc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.delta=e.delta?.map(e=>Ys.fromPartial(e))||[],t.subagentRunId=e.subagentRunId??void 0,t}};function Bc(){return{baseEvent:void 0,messages:[]}}var Vc={encode(e,t=new I){e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.messages)yc.encode(n,t.uint32(18).fork()).join();return t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Bc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messages.push(yc.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Vc.fromPartial(e??{})},fromPartial(e){let t=Bc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.messages=e.messages?.map(e=>yc.fromPartial(e))||[],t}};function Hc(){return{baseEvent:void 0,event:void 0,source:void 0,subagentRunId:void 0}}var Uc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.event!==void 0&&R.encode(R.wrap(e.event),t.uint32(18).fork()).join(),e.source!==void 0&&t.uint32(26).string(e.source),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Hc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.event=R.unwrap(R.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.source=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Uc.fromPartial(e??{})},fromPartial(e){let t=Hc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.event=e.event??void 0,t.source=e.source??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Wc(){return{baseEvent:void 0,name:``,value:void 0,subagentRunId:void 0}}var Gc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.name!==``&&t.uint32(18).string(e.name),e.value!==void 0&&R.encode(R.wrap(e.value),t.uint32(26).fork()).join(),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Wc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.name=n.string();continue;case 3:if(e!==26)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Gc.fromPartial(e??{})},fromPartial(e){let t=Wc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.name=e.name??``,t.value=e.value??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Kc(){return{baseEvent:void 0,threadId:``,runId:``}}var qc={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==``&&t.uint32(18).string(e.threadId),e.runId!==``&&t.uint32(26).string(e.runId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Kc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.threadId=n.string();continue;case 3:if(e!==26)break;i.runId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return qc.fromPartial(e??{})},fromPartial(e){let t=Kc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??``,t.runId=e.runId??``,t}};function Jc(){return{provider:void 0,model:void 0,inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0}}var Yc={encode(e,t=new I){return e.provider!==void 0&&t.uint32(10).string(e.provider),e.model!==void 0&&t.uint32(18).string(e.model),e.inputTokens!==void 0&&t.uint32(24).int64(e.inputTokens),e.outputTokens!==void 0&&t.uint32(32).int64(e.outputTokens),e.totalTokens!==void 0&&t.uint32(40).int64(e.totalTokens),e.reasoningTokens!==void 0&&t.uint32(48).int64(e.reasoningTokens),e.cachedInputTokens!==void 0&&t.uint32(56).int64(e.cachedInputTokens),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Jc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.provider=n.string();continue;case 2:if(e!==18)break;i.model=n.string();continue;case 3:if(e!==24)break;i.inputTokens=gl(n.int64());continue;case 4:if(e!==32)break;i.outputTokens=gl(n.int64());continue;case 5:if(e!==40)break;i.totalTokens=gl(n.int64());continue;case 6:if(e!==48)break;i.reasoningTokens=gl(n.int64());continue;case 7:if(e!==56)break;i.cachedInputTokens=gl(n.int64());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Yc.fromPartial(e??{})},fromPartial(e){let t=Jc();return t.provider=e.provider??void 0,t.model=e.model??void 0,t.inputTokens=e.inputTokens??void 0,t.outputTokens=e.outputTokens??void 0,t.totalTokens=e.totalTokens??void 0,t.reasoningTokens=e.reasoningTokens??void 0,t.cachedInputTokens=e.cachedInputTokens??void 0,t}};function Xc(){return{baseEvent:void 0,threadId:``,runId:``,result:void 0,outcome:``,interrupts:[],usage:[]}}var Zc={encode(e,t=new I){e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==``&&t.uint32(18).string(e.threadId),e.runId!==``&&t.uint32(26).string(e.runId),e.result!==void 0&&R.encode(R.wrap(e.result),t.uint32(34).fork()).join(),e.outcome!==``&&t.uint32(42).string(e.outcome);for(let n of e.interrupts)xc.encode(n,t.uint32(50).fork()).join();for(let n of e.usage)Yc.encode(n,t.uint32(58).fork()).join();return t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Xc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.threadId=n.string();continue;case 3:if(e!==26)break;i.runId=n.string();continue;case 4:if(e!==34)break;i.result=R.unwrap(R.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.outcome=n.string();continue;case 6:if(e!==50)break;i.interrupts.push(xc.decode(n,n.uint32()));continue;case 7:if(e!==58)break;i.usage.push(Yc.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Zc.fromPartial(e??{})},fromPartial(e){let t=Xc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??``,t.runId=e.runId??``,t.result=e.result??void 0,t.outcome=e.outcome??``,t.interrupts=e.interrupts?.map(e=>xc.fromPartial(e))||[],t.usage=e.usage?.map(e=>Yc.fromPartial(e))||[],t}};function Qc(){return{baseEvent:void 0,code:void 0,message:``,usage:[]}}var $c={encode(e,t=new I){e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.code!==void 0&&t.uint32(18).string(e.code),e.message!==``&&t.uint32(26).string(e.message);for(let n of e.usage)Yc.encode(n,t.uint32(34).fork()).join();return t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=Qc();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.code=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.usage.push(Yc.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return $c.fromPartial(e??{})},fromPartial(e){let t=Qc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.code=e.code??void 0,t.message=e.message??``,t.usage=e.usage?.map(e=>Yc.fromPartial(e))||[],t}};function el(){return{baseEvent:void 0,stepName:``,subagentRunId:void 0}}var tl={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==``&&t.uint32(18).string(e.stepName),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=el();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.stepName=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return tl.fromPartial(e??{})},fromPartial(e){let t=el();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??``,t.subagentRunId=e.subagentRunId??void 0,t}};function nl(){return{baseEvent:void 0,stepName:``,subagentRunId:void 0}}var rl={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==``&&t.uint32(18).string(e.stepName),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=nl();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.stepName=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rl.fromPartial(e??{})},fromPartial(e){let t=nl();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??``,t.subagentRunId=e.subagentRunId??void 0,t}};function il(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0,subagentRunId:void 0}}var al={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==void 0&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.delta!==void 0&&t.uint32(34).string(e.delta),e.name!==void 0&&t.uint32(42).string(e.name),e.subagentRunId!==void 0&&t.uint32(50).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=il();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.role=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue;case 5:if(e!==42)break;i.name=n.string();continue;case 6:if(e!==50)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return al.fromPartial(e??{})},fromPartial(e){let t=il();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??void 0,t.role=e.role??void 0,t.delta=e.delta??void 0,t.name=e.name??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function ol(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0,subagentRunId:void 0}}var sl={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==void 0&&t.uint32(18).string(e.toolCallId),e.toolCallName!==void 0&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.delta!==void 0&&t.uint32(42).string(e.delta),e.subagentRunId!==void 0&&t.uint32(50).string(e.subagentRunId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=ol();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.toolCallName=n.string();continue;case 4:if(e!==34)break;i.parentMessageId=n.string();continue;case 5:if(e!==42)break;i.delta=n.string();continue;case 6:if(e!==50)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return sl.fromPartial(e??{})},fromPartial(e){let t=ol();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??void 0,t.toolCallName=e.toolCallName??void 0,t.parentMessageId=e.parentMessageId??void 0,t.delta=e.delta??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function cl(){return{baseEvent:void 0,subagentRunId:``,name:``,description:void 0,parentSubagentRunId:void 0,parentToolCallId:void 0,parentMessageId:void 0}}var ll={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.name!==``&&t.uint32(26).string(e.name),e.description!==void 0&&t.uint32(34).string(e.description),e.parentSubagentRunId!==void 0&&t.uint32(42).string(e.parentSubagentRunId),e.parentToolCallId!==void 0&&t.uint32(50).string(e.parentToolCallId),e.parentMessageId!==void 0&&t.uint32(58).string(e.parentMessageId),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=cl();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.name=n.string();continue;case 4:if(e!==34)break;i.description=n.string();continue;case 5:if(e!==42)break;i.parentSubagentRunId=n.string();continue;case 6:if(e!==50)break;i.parentToolCallId=n.string();continue;case 7:if(e!==58)break;i.parentMessageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return ll.fromPartial(e??{})},fromPartial(e){let t=cl();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.name=e.name??``,t.description=e.description??void 0,t.parentSubagentRunId=e.parentSubagentRunId??void 0,t.parentToolCallId=e.parentToolCallId??void 0,t.parentMessageId=e.parentMessageId??void 0,t}};function ul(){return{baseEvent:void 0,subagentRunId:``,result:void 0,outcome:``,interruptIds:[]}}var dl={encode(e,t=new I){e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.result!==void 0&&R.encode(R.wrap(e.result),t.uint32(26).fork()).join(),e.outcome!==``&&t.uint32(34).string(e.outcome);for(let n of e.interruptIds)t.uint32(42).string(n);return t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=ul();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.result=R.unwrap(R.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.outcome=n.string();continue;case 5:if(e!==42)break;i.interruptIds.push(n.string());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dl.fromPartial(e??{})},fromPartial(e){let t=ul();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.result=e.result??void 0,t.outcome=e.outcome??``,t.interruptIds=e.interruptIds?.map(e=>e)||[],t}};function fl(){return{baseEvent:void 0,subagentRunId:``,message:``,code:void 0}}var pl={encode(e,t=new I){return e.baseEvent!==void 0&&z.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.message!==``&&t.uint32(26).string(e.message),e.code!==void 0&&t.uint32(34).string(e.code),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=fl();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.baseEvent=z.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.code=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return pl.fromPartial(e??{})},fromPartial(e){let t=fl();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?z.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.message=e.message??``,t.code=e.code??void 0,t}};function ml(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0,subagentStarted:void 0,subagentFinished:void 0,subagentError:void 0}}var hl={encode(e,t=new I){return e.textMessageStart!==void 0&&Tc.encode(e.textMessageStart,t.uint32(10).fork()).join(),e.textMessageContent!==void 0&&Dc.encode(e.textMessageContent,t.uint32(18).fork()).join(),e.textMessageEnd!==void 0&&kc.encode(e.textMessageEnd,t.uint32(26).fork()).join(),e.toolCallStart!==void 0&&jc.encode(e.toolCallStart,t.uint32(34).fork()).join(),e.toolCallArgs!==void 0&&Nc.encode(e.toolCallArgs,t.uint32(42).fork()).join(),e.toolCallEnd!==void 0&&Fc.encode(e.toolCallEnd,t.uint32(50).fork()).join(),e.stateSnapshot!==void 0&&Lc.encode(e.stateSnapshot,t.uint32(58).fork()).join(),e.stateDelta!==void 0&&zc.encode(e.stateDelta,t.uint32(66).fork()).join(),e.messagesSnapshot!==void 0&&Vc.encode(e.messagesSnapshot,t.uint32(74).fork()).join(),e.raw!==void 0&&Uc.encode(e.raw,t.uint32(82).fork()).join(),e.custom!==void 0&&Gc.encode(e.custom,t.uint32(90).fork()).join(),e.runStarted!==void 0&&qc.encode(e.runStarted,t.uint32(98).fork()).join(),e.runFinished!==void 0&&Zc.encode(e.runFinished,t.uint32(106).fork()).join(),e.runError!==void 0&&$c.encode(e.runError,t.uint32(114).fork()).join(),e.stepStarted!==void 0&&tl.encode(e.stepStarted,t.uint32(122).fork()).join(),e.stepFinished!==void 0&&rl.encode(e.stepFinished,t.uint32(130).fork()).join(),e.textMessageChunk!==void 0&&al.encode(e.textMessageChunk,t.uint32(138).fork()).join(),e.toolCallChunk!==void 0&&sl.encode(e.toolCallChunk,t.uint32(146).fork()).join(),e.subagentStarted!==void 0&&ll.encode(e.subagentStarted,t.uint32(154).fork()).join(),e.subagentFinished!==void 0&&dl.encode(e.subagentFinished,t.uint32(162).fork()).join(),e.subagentError!==void 0&&pl.encode(e.subagentError,t.uint32(170).fork()).join(),t},decode(e,t){let n=e instanceof L?e:new L(e),r=t===void 0?n.len:n.pos+t,i=ml();for(;n.pos<r;){let e=n.uint32();switch(e>>>3){case 1:if(e!==10)break;i.textMessageStart=Tc.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.textMessageContent=Dc.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.textMessageEnd=kc.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.toolCallStart=jc.decode(n,n.uint32());continue;case 5:if(e!==42)break;i.toolCallArgs=Nc.decode(n,n.uint32());continue;case 6:if(e!==50)break;i.toolCallEnd=Fc.decode(n,n.uint32());continue;case 7:if(e!==58)break;i.stateSnapshot=Lc.decode(n,n.uint32());continue;case 8:if(e!==66)break;i.stateDelta=zc.decode(n,n.uint32());continue;case 9:if(e!==74)break;i.messagesSnapshot=Vc.decode(n,n.uint32());continue;case 10:if(e!==82)break;i.raw=Uc.decode(n,n.uint32());continue;case 11:if(e!==90)break;i.custom=Gc.decode(n,n.uint32());continue;case 12:if(e!==98)break;i.runStarted=qc.decode(n,n.uint32());continue;case 13:if(e!==106)break;i.runFinished=Zc.decode(n,n.uint32());continue;case 14:if(e!==114)break;i.runError=$c.decode(n,n.uint32());continue;case 15:if(e!==122)break;i.stepStarted=tl.decode(n,n.uint32());continue;case 16:if(e!==130)break;i.stepFinished=rl.decode(n,n.uint32());continue;case 17:if(e!==138)break;i.textMessageChunk=al.decode(n,n.uint32());continue;case 18:if(e!==146)break;i.toolCallChunk=sl.decode(n,n.uint32());continue;case 19:if(e!==154)break;i.subagentStarted=ll.decode(n,n.uint32());continue;case 20:if(e!==162)break;i.subagentFinished=dl.decode(n,n.uint32());continue;case 21:if(e!==170)break;i.subagentError=pl.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return hl.fromPartial(e??{})},fromPartial(e){let t=ml();return t.textMessageStart=e.textMessageStart!==void 0&&e.textMessageStart!==null?Tc.fromPartial(e.textMessageStart):void 0,t.textMessageContent=e.textMessageContent!==void 0&&e.textMessageContent!==null?Dc.fromPartial(e.textMessageContent):void 0,t.textMessageEnd=e.textMessageEnd!==void 0&&e.textMessageEnd!==null?kc.fromPartial(e.textMessageEnd):void 0,t.toolCallStart=e.toolCallStart!==void 0&&e.toolCallStart!==null?jc.fromPartial(e.toolCallStart):void 0,t.toolCallArgs=e.toolCallArgs!==void 0&&e.toolCallArgs!==null?Nc.fromPartial(e.toolCallArgs):void 0,t.toolCallEnd=e.toolCallEnd!==void 0&&e.toolCallEnd!==null?Fc.fromPartial(e.toolCallEnd):void 0,t.stateSnapshot=e.stateSnapshot!==void 0&&e.stateSnapshot!==null?Lc.fromPartial(e.stateSnapshot):void 0,t.stateDelta=e.stateDelta!==void 0&&e.stateDelta!==null?zc.fromPartial(e.stateDelta):void 0,t.messagesSnapshot=e.messagesSnapshot!==void 0&&e.messagesSnapshot!==null?Vc.fromPartial(e.messagesSnapshot):void 0,t.raw=e.raw!==void 0&&e.raw!==null?Uc.fromPartial(e.raw):void 0,t.custom=e.custom!==void 0&&e.custom!==null?Gc.fromPartial(e.custom):void 0,t.runStarted=e.runStarted!==void 0&&e.runStarted!==null?qc.fromPartial(e.runStarted):void 0,t.runFinished=e.runFinished!==void 0&&e.runFinished!==null?Zc.fromPartial(e.runFinished):void 0,t.runError=e.runError!==void 0&&e.runError!==null?$c.fromPartial(e.runError):void 0,t.stepStarted=e.stepStarted!==void 0&&e.stepStarted!==null?tl.fromPartial(e.stepStarted):void 0,t.stepFinished=e.stepFinished!==void 0&&e.stepFinished!==null?rl.fromPartial(e.stepFinished):void 0,t.textMessageChunk=e.textMessageChunk!==void 0&&e.textMessageChunk!==null?al.fromPartial(e.textMessageChunk):void 0,t.toolCallChunk=e.toolCallChunk!==void 0&&e.toolCallChunk!==null?sl.fromPartial(e.toolCallChunk):void 0,t.subagentStarted=e.subagentStarted!==void 0&&e.subagentStarted!==null?ll.fromPartial(e.subagentStarted):void 0,t.subagentFinished=e.subagentFinished!==void 0&&e.subagentFinished!==null?dl.fromPartial(e.subagentFinished):void 0,t.subagentError=e.subagentError!==void 0&&e.subagentError!==null?pl.fromPartial(e.subagentError):void 0,t}};function gl(e){let t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error(`Value is larger than Number.MAX_SAFE_INTEGER`);if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error(`Value is smaller than Number.MIN_SAFE_INTEGER`);return t}var _l=e=>e&&typeof e==`object`?e:void 0,vl=e=>{let t=_l(e);if(t){if(t.data){let e=t.data;return{type:`data`,value:e.value,mimeType:e.mimeType}}if(t.url){let e=t.url;return{type:`url`,value:e.value,mimeType:e.mimeType}}}},yl=e=>{let t=_l(e);if(t){if(t.text)return{type:`text`,text:t.text.text};if(t.image){let e=t.image;return{type:`image`,source:vl(e.source),metadata:e.metadata}}if(t.audio){let e=t.audio;return{type:`audio`,source:vl(e.source),metadata:e.metadata}}if(t.video){let e=t.video;return{type:`video`,source:vl(e.source),metadata:e.metadata}}if(t.document){let e=t.document;return{type:`document`,source:vl(e.source),metadata:e.metadata}}}};function bl(e){let t=hl.decode(e),n=Object.values(t).find(e=>e!==void 0);if(!n)throw Error(`Invalid event`);if(n.type=Sc[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,n.baseEvent.metadata!==void 0&&(n.metadata=n.baseEvent.metadata),delete n.baseEvent,n.type===j.MESSAGES_SNAPSHOT)for(let e of n.messages){let t=e;if(t.role===`user`&&Array.isArray(t.contentParts)){let e=t.contentParts.map(e=>yl(e)).filter(e=>e!==void 0);e.length>0&&(t.content=e)}Array.isArray(t.contentParts)&&t.contentParts.length===0&&(t.contentParts=void 0),t.toolCalls?.length===0&&(t.toolCalls=void 0)}if(n.type===j.RUN_FINISHED){let e=n,t=typeof e.outcome==`string`&&e.outcome!==``?e.outcome:void 0,r=Array.isArray(e.interrupts)?e.interrupts:[];delete e.interrupts,t===`interrupt`?e.outcome={type:`interrupt`,interrupts:r}:t===`success`?e.outcome={type:`success`}:delete e.outcome}if(n.type===j.SUBAGENT_FINISHED){let e=n,t=typeof e.outcome==`string`&&e.outcome!==``?e.outcome:void 0,r=Array.isArray(e.interruptIds)?e.interruptIds:[];delete e.interruptIds,t===`suspended`?e.outcome={type:`suspended`,...r.length>0&&{interruptIds:r}}:t===`success`?e.outcome={type:`success`}:delete e.outcome}if((n.type===j.RUN_FINISHED||n.type===j.RUN_ERROR)&&Array.isArray(n.usage)&&n.usage.length===0&&delete n.usage,n.type===j.STATE_DELTA)for(let e of n.delta)e.op=qs[e.op].toLowerCase(),Object.keys(e).forEach(t=>{e[t]===void 0&&delete e[t]});
5return Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),Er.parse(n)}var xl=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Sl=e=>{if(typeof e!=`string`)throw TypeError(`Invalid argument expected string`);let t=e.match(xl);if(!t)throw Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Cl=e=>e===`*`||e===`x`||e===`X`,wl=e=>{let t=parseInt(e,10);return isNaN(t)?e:t},Tl=(e,t)=>typeof e==typeof t?[e,t]:[String(e),String(t)],El=(e,t)=>{if(Cl(e)||Cl(t))return 0;let[n,r]=Tl(wl(e),wl(t));return n>r?1:n<r?-1:0},Dl=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){let r=El(e[n]||`0`,t[n]||`0`);if(r!==0)return r}return 0},Ol=(e,t)=>{let n=Sl(e),r=Sl(t),i=n.pop(),a=r.pop(),o=Dl(n,r);return o===0?i&&a?Dl(i.split(`.`),a.split(`.`)):i||a?i?-1:1:0:o},B=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return Array.isArray(e)?[...e]:{...e}}};function kl(){return r()}function Al(e){if(Object.freeze(e),typeof e==`object`&&e)for(let t of Object.values(e))typeof t==`object`&&t&&!Object.isFrozen(t)&&Al(t);return e}var jl=524288;function Ml(e,t,n){let r=0,i=[e,t],a=new WeakSet;for(;i.length>0;){let e=i.pop();if(typeof e==`string`){if(r+=e.length,r>n)return!0}else if(typeof e==`object`&&e){if(a.has(e))continue;if(a.add(e),Array.isArray(e))for(let t=0;t<e.length;t++)i.push(e[t]);else{let t=Object.keys(e);for(let a=0;a<t.length;a++){let o=t[a];if(r+=o.length,r>n)return!0;i.push(e[o])}}}}return!1}async function V(e,t,n,r){let i=typeof process<`u`&&!0,a=i&&!!{NODE_ENV:`development`}.VITEST_WORKER_ID,o=i&&!!{NODE_ENV:`development`}.VITEST_WORKER_ID,s=o&&!Ml(t,n,jl),c=s?B(t):t,l=s?B(n):n,u=!1,d=!1,f;for(let t of e)try{s&&(Al(c),Al(l));let e=await r(t,c,l);if(e===void 0)continue;let n=!1;if(e.messages!==void 0&&e.messages!==c&&(c=B(e.messages),u=!0,n=!0),e.state!==void 0&&e.state!==l&&(l=B(e.state),d=!0,n=!0),s&&n&&Ml(c,l,jl)&&(s=!1),f=e.stopPropagation,f===!0)break}catch(e){if(o&&e instanceof TypeError){if(a)throw e;console.error(`AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.`,e)}else a||console.error(`Subscriber error:`,e);continue}return{...u?{messages:Object.isFrozen(c)?B(c):c}:{},...d?{state:Object.isFrozen(l)?B(l):l}:{},...f===void 0?{}:{stopPropagation:f}}}function Nl(e){if(!e)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(e===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let t=e.events??!0,n=e.lifecycle??!0,r=e.verbose??!1;return{enabled:t||n,events:t,lifecycle:n,verbose:r}}function Pl(e){if(e instanceof Fl)return e;if(e===!0)return new Fl(Nl(!0))}var Fl=class{constructor(e){this.config=e}event(e,t,n,r){this.config.events&&(this.config.verbose?console.debug(`[${e}] ${t}`,typeof n==`string`?n:JSON.stringify(n)):console.debug(`[${e}] ${t}`,r??n))}lifecycle(e,t,n){this.config.lifecycle&&(n?console.debug(`[${e}] ${t}`,n):console.debug(`[${e}] ${t}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function Il(e){return e.enabled?new Fl(e):void 0}function Ll(e,t,n){if(t){let r=e.find(e=>e.id===t);if(r?.role===`assistant`)return r;r&&console.warn(`TOOL_CALL_START: parentMessageId '${t}' matches a '${r.role}' message, not assistant — falling back to toolCallId`);let i={id:r?n:t,role:`assistant`,toolCalls:[]};return e.push(i),i}let r={id:n,role:`assistant`,toolCalls:[]};return e.push(r),r}function Rl(e,t){return!e||t.metadata===void 0?!1:(e.metadata=sn(e.metadata,B(t.metadata)),!0)}var zl=(e,t,n,r,i)=>{let a=Pl(i),o=B(n.messages),s=B(e.state),c={},l=e=>{e.messages!==void 0&&(o=e.messages,c.messages=e.messages),e.state!==void 0&&(s=e.state,c.state=e.state)},u=()=>{let e=B(c);return c={},e.messages!==void 0||e.state!==void 0?N(e):Aa};return t.pipe(qo(async t=>{let i=await V(r,o,s,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));
vendor: 25,002 bytes, lines 5-7
5if(l(i),i.stopPropagation===!0?a?.event(`APPLY`,`Event dropped:`,t,{type:t.type,reason:`stopPropagation by subscriber`}):a?.event(`APPLY`,`Event applied:`,t,{type:t.type,subscribers:r.length}),i.stopPropagation===!0)return u();switch(t.type){case j.TEXT_MESSAGE_START:{let i=await V(r,o,s,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{messageId:e,role:n=`assistant`,name:r,subagentRunId:i}=t,a=o.find(t=>t.id===e);if(a?.role===`activity`)return console.warn(`TEXT_MESSAGE_START: Message '${e}' is an activity message — message ids must be unique across activity and text messages`),u();let s=a;if(!s){let t={id:e,role:n,content:``,...r!==void 0&&{name:r},...i!=null&&{subagentRunId:i}};o.push(t),s=t}let c=Rl(s,t);(!a||c)&&l({messages:o})}return u()}case j.TEXT_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,c=o.find(e=>e.id===i);if(!c)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${i}'`),u();if(c.role===`activity`)return console.warn(`TEXT_MESSAGE_CONTENT: Message '${i}' is an activity message — message ids must be unique across activity and text messages`),u();let d=await V(r,o,s,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof c.content==`string`?c.content:``}));return l(d),d.stopPropagation!==!0&&(c.content=`${typeof c.content==`string`?c.content:``}${a}`,Rl(c,t),l({messages:o})),u()}case j.TEXT_MESSAGE_END:{let{messageId:i}=t,a=o.find(e=>e.id===i);if(!a)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${i}'`),u();if(a.role===`activity`)return console.warn(`TEXT_MESSAGE_END: Message '${i}' is an activity message — message ids must be unique across activity and text messages`),u();let c=await V(r,o,s,(r,i,o)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,textMessageBuffer:typeof a.content==`string`?a.content:``}));return l(c),c.stopPropagation!==!0&&Rl(a,t)&&l({messages:o}),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:o,state:s,agent:n,input:e})})),u()}case j.TOOL_CALL_START:{let i=await V(r,o,s,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r,subagentRunId:i}=t,a=o.find(t=>t.toolCalls?.some(t=>t.id===e))?.toolCalls?.find(t=>t.id===e);if(a){let r=a.function.name!==n;return r&&(console.warn(`TOOL_CALL_START: tool call '${e}' already exists with name '${a.function.name}' — updating it to '${n}'`),a.function.name=n),(Rl(a,t)||r)&&l({messages:o}),u()}let s=new Set(o.map(e=>e.id)),c=Ll(o,r,e);!s.has(c.id)&&i!=null&&c.subagentRunId===void 0&&(c.subagentRunId=i),c.toolCalls??=[];let d={id:e,type:`function`,function:{name:n,arguments:``}};c.toolCalls.push(d),Rl(d,t),l({messages:o})}return u()}case j.TOOL_CALL_ARGS:{let{toolCallId:i,delta:a}=t,c=o.find(e=>e.toolCalls?.some(e=>e.id===i));if(!c)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${i}'`),u();let d=c.toolCalls?.find(e=>e.id===i);if(!d)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i}'`),u();let f=await V(r,o,s,(r,i,a)=>{let o=d.function.arguments,s=d.function.name,c={};try{c=gs(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return l(f),f.stopPropagation!==!0&&(d.function.arguments+=a,Rl(d,t),l({messages:o})),u()}case j.TOOL_CALL_END:{let{toolCallId:i}=t,a=o.find(e=>e.toolCalls?.some(e=>e.id===i));if(!a)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${i}'`),u();let c=a.toolCalls?.find(e=>e.id===i);if(!c)return console.warn(`TOOL_CALL_END: No tool call found with ID '${i}'`),u();let d=await V(r,o,s,(r,i,a)=>{let o=c.function.arguments,s=c.function.name,l={};try{l=JSON.parse(o)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:s,toolCallArgs:l})});return l(d),d.stopPropagation!==!0&&Rl(c,t)&&l({messages:o}),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:c,messages:o,state:s,agent:n,input:e})})),u()}case j.TOOL_CALL_RESULT:{let i=await V(r,o,s,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{messageId:i,toolCallId:a,content:c,role:u,subagentRunId:d}=t,f={id:i,toolCallId:a,role:u||`tool`,content:c,...d!=null&&{subagentRunId:d}};Rl(f,t);let p=o.findIndex(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.id===a));if(p===-1)o.push(f);else{let e=p+1;for(;e<o.length&&o[e].role===`tool`;)e++;o.splice(e,0,f)}await Promise.all(r.map(t=>{t.onNewMessage?.({message:f,messages:o,state:s,agent:n,input:e})})),l({messages:o})}return u()}case j.STATE_SNAPSHOT:{let i=await V(r,o,s,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{snapshot:e}=t;s=e,l({state:s})}return u()}case j.STATE_DELTA:{let i=await V(r,o,s,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{delta:e}=t;try{s=ci.applyPatch(s,e,!0,!1).newDocument,l({state:s})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(s,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return u()}case j.MESSAGES_SNAPSHOT:{let i=await V(r,o,s,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{messages:e}=t,n=e.map(e=>{if(e.subagentRunId!==null)return e;let t={...e};return delete t.subagentRunId,t}),r=new Map(n.map(e=>[e.id,e])),i=n.some(e=>e.role===`activity`),a=n.some(e=>e.role===`reasoning`),s=e=>e.role===`activity`&&!i||e.role===`reasoning`&&!a;o=o.filter(e=>s(e)||r.has(e.id)).map(e=>s(e)?e:r.get(e.id));let c=new Set(o.map(e=>e.id));for(let e of n)c.has(e.id)||o.push(e);l({messages:o})}return u()}case j.ACTIVITY_SNAPSHOT:{let i=t,a=o.findIndex(e=>e.id===i.messageId),c=a>=0?o[a]:void 0,d=c?.role===`activity`?c:void 0,f=i.replace??!0,p=await V(r,o,s,(t,r,a)=>t.onActivitySnapshotEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:d,existingMessage:c}));if(l(p),p.stopPropagation!==!0){let t={id:i.messageId,role:`activity`,activityType:i.activityType,content:B(i.content),...i.subagentRunId!=null&&{subagentRunId:i.subagentRunId}},c,u;a===-1?(o.push(t),c=t,u=t):d?(f&&(o[a]={...d,activityType:i.activityType,content:B(i.content),subagentRunId:i.subagentRunId},i.subagentRunId??delete o[a].subagentRunId),u=o[a]):f&&(o[a]=t,c=t,u=t),Rl(u,i),l({messages:o}),c&&await Promise.all(r.map(t=>t.onNewMessage?.({message:c,messages:o,state:s,agent:n,input:e})))}return u()}case j.ACTIVITY_DELTA:{let i=t,a=o.findIndex(e=>e.id===i.messageId);if(a===-1)return u();let c=o[a];if(c.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${i.messageId}' is not an activity message`),u();let d=c,f=await V(r,o,s,(t,r,a)=>t.onActivityDeltaEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:d}));if(l(f),f.stopPropagation!==!0)try{Rl(d,i)&&l({messages:o});let e=B(d.content??{}),t=ci.applyPatch(e,i.patch??[],!0,!1).newDocument;o[a]={...d,content:B(t),activityType:i.activityType},l({messages:o})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${i.messageId}': ${t}`)}return u()}case j.RAW:return l(await V(r,o,s,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.CUSTOM:return l(await V(r,o,s,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.RUN_STARTED:{let i=await V(r,o,s,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages){let e=t;if(t.subagentRunId===null){let n={...t};delete n.subagentRunId,e=n}o.find(t=>t.id===e.id)||o.push(e)}l({messages:o})}}return u()}case j.RUN_FINISHED:{let i=t,a=i.outcome?.type===`interrupt`?{event:i,outcome:`interrupt`,interrupts:i.outcome.interrupts}:{event:i,outcome:`success`,result:i.result},c=await V(r,o,s,(t,r,i)=>t.onRunFinishedEvent?.({...a,messages:r,state:i,agent:n,input:e}));return l(c),c.stopPropagation!==!0&&(n.pendingInterrupts=a.outcome===`interrupt`?a.interrupts.map(e=>{if(e.subagentRunId!==null)return e;let t={...e};return delete t.subagentRunId,t}):[]),u()}case j.RUN_ERROR:return l(await V(r,o,s,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.STEP_STARTED:return l(await V(r,o,s,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.STEP_FINISHED:return l(await V(r,o,s,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be transformed before being applied`);case j.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be transformed before being applied`);case j.THINKING_START:return u();case j.THINKING_END:return u();case j.THINKING_TEXT_MESSAGE_START:return u();case j.THINKING_TEXT_MESSAGE_CONTENT:return u();case j.THINKING_TEXT_MESSAGE_END:return u();case j.REASONING_START:return l(await V(r,o,s,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.REASONING_MESSAGE_START:{let i=await V(r,o,s,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(i),i.stopPropagation!==!0){let{messageId:e,subagentRunId:n}=t,r=o.find(t=>t.id===e),i=r;if(!i){let t={id:e,role:`reasoning`,content:``,...n!=null&&{subagentRunId:n}};o.push(t),i=t}let a=Rl(i,t);(!r||a)&&l({messages:o})}return u()}case j.REASONING_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,c=o.find(e=>e.id===i);if(!c)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${i}'`),u();let d=await V(r,o,s,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof c.content==`string`?c.content:``}));return l(d),d.stopPropagation!==!0&&(c.content=`${typeof c.content==`string`?c.content:``}${a}`,Rl(c,t),l({messages:o})),u()}case j.REASONING_MESSAGE_END:{let{messageId:i}=t,a=o.find(e=>e.id===i);if(!a)return console.warn(`REASONING_MESSAGE_END: No message found with ID '${i}'`),u();let c=await V(r,o,s,(r,i,o)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,reasoningMessageBuffer:typeof a.content==`string`?a.content:``}));return l(c),c.stopPropagation!==!0&&Rl(a,t)&&l({messages:o}),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:o,state:s,agent:n,input:e})})),u()}case j.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case j.REASONING_END:return l(await V(r,o,s,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.REASONING_ENCRYPTED_VALUE:{let{subtype:i,entityId:a,encryptedValue:d}=t,f=await V(r,o,s,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(l(f),f.stopPropagation!==!0){let e=!1;if(i===`tool-call`){for(let t of o)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===a);if(n){n.encryptedValue=d,e=!0;break}}}else{let t=o.find(e=>e.id===a);t?.role!==`activity`&&t&&(t.encryptedValue=d,e=!0)}e&&(c.messages=o)}return u()}case j.SUBAGENT_STARTED:return l(await V(r,o,s,(r,i,a)=>r.onSubagentStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.SUBAGENT_FINISHED:return l(await V(r,o,s,(r,i,a)=>r.onSubagentFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u();case j.SUBAGENT_ERROR:return l(await V(r,o,s,(r,i,a)=>r.onSubagentErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),u()}return t.type,u()}),Lo(),r.length>0?Xo({}):e=>e)},Bl=e=>t=>{let n=Pl(e),r=new Set,i=new Set,a=new Set,o={message:new Map,toolCall:new Map,activity:new Map,reasoning:new Map},s=!1,c=!1,l=!1,u=new Map,d=e=>{let t=u.get(e);return t||(t=new Map,u.set(e,t)),t},f=()=>{for(let e of u.values())if(e.size>0)return!0;return!1},p=new Map,m=new Set,h=!1,g=!1,ee=!1,te=()=>{r.clear(),i.clear(),a.clear(),o.message.clear(),o.toolCall.clear(),o.activity.clear(),o.reasoning.clear(),u.clear(),p.clear(),m.clear(),h=!1,g=!1,s=!1,c=!1,ee=!0},ne=(e,t)=>{let n=e??[];if(Array.isArray(n))for(let e of n){if(!e||typeof e.id!=`string`)continue;if(e.subagentRunId===null)return new A(`Cannot send a message (id '${e.id}') with 'subagentRunId: null'. The field is optional — omit it entirely.`);let n=e.role===`reasoning`?o.reasoning:e.role===`activity`?o.activity:o.message;(t||!n.has(e.id))&&n.set(e.id,{subagentRunId:e.subagentRunId});for(let n of e.toolCalls??[])n&&typeof n.id==`string`&&(t||!o.toolCall.has(n.id))&&o.toolCall.set(n.id,{subagentRunId:e.subagentRunId??void 0})}},re=(e,t,n,r,i)=>{if(t!==void 0&&n&&n.subagentRunId!==t)return new A(`Cannot send '${e}': subagentRunId '${t}' does not match the ${r} '${i}' opener's subagent '${n.subagentRunId??`(the parent agent)`}'.`)};return t.pipe(Io(e=>{let t=e.type;if(n?.event(`VERIFY`,`Event:`,e,{type:e.type}),c&&t!==j.RUN_STARTED)return P(()=>new A(`Cannot send event type '${t}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&t!==j.RUN_ERROR&&t!==j.RUN_STARTED)return P(()=>new A(`Cannot send event type '${t}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!l){if(l=!0,t!==j.RUN_STARTED&&t!==j.RUN_ERROR)return P(()=>new A(`First event must be 'RUN_STARTED'`))}else if(t===j.RUN_STARTED){if(ee&&!s&&!c)return P(()=>new A(`Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run.`));(s||c)&&te()}if(e.subagentRunId===null)return P(()=>new A(`Cannot send '${t}' with 'subagentRunId: null'. The field is optional — omit it entirely.`));if(t===j.SUBAGENT_STARTED||t===j.SUBAGENT_FINISHED||t===j.SUBAGENT_ERROR){let n=t===j.SUBAGENT_STARTED?[`description`,`parentSubagentRunId`,`parentToolCallId`,`parentMessageId`]:t===j.SUBAGENT_FINISHED?[`outcome`]:[`code`];for(let r of n)if(e[r]===null)return P(()=>new A(`Cannot send '${t}' with '${r}: null'. The field is optional — omit it entirely.`));let r=e.outcome;if(r!=null&&r.type!==`success`&&r.type!==`suspended`)return P(()=>new A(`Cannot send '${t}' with outcome type '${String(r.type)}'. The outcome is either { type: "success" } or { type: "suspended" }.`));if(r&&r.interruptIds===null)return P(()=>new A(`Cannot send '${t}' with 'outcome.interruptIds: null'. The field is optional — omit it entirely.`));if(r&&Array.isArray(r.interruptIds)&&r.interruptIds.some(e=>typeof e!=`string`))return P(()=>new A(`Cannot send '${t}' with a non-string entry in 'outcome.interruptIds'. Interrupt ids are strings.`))}if(t===j.RUN_FINISHED){let t=e.outcome;if(t?.type===`interrupt`&&Array.isArray(t.interrupts)){for(let e of t.interrupts)if(e&&e.subagentRunId===null)return P(()=>new A(`Cannot send 'RUN_FINISHED' with an interrupt (id '${e.id}') carrying 'subagentRunId: null'. The field is optional — omit it entirely.`))}}switch(t){case j.TEXT_MESSAGE_START:{let n=e.messageId;if(r.has(n))return P(()=>new A(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${n}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`));let i=o.message.get(n);if(i){let r=re(t,e.subagentRunId,i,`message`,n);if(r)return P(()=>r)}return r.add(n),i||o.message.set(n,{subagentRunId:e.subagentRunId}),N(e)}case j.TEXT_MESSAGE_CONTENT:{let n=e.messageId;if(!r.has(n))return P(()=>new A(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${n}'. Start a text message with 'TEXT_MESSAGE_START' first.`));let i=re(t,e.subagentRunId,o.message.get(n),`message`,n);return i?P(()=>i):N(e)}case j.TEXT_MESSAGE_END:{let n=e.messageId;if(!r.has(n))return P(()=>new A(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${n}'. A 'TEXT_MESSAGE_START' event must be sent first.`));let i=re(t,e.subagentRunId,o.message.get(n),`message`,n);return i?P(()=>i):(r.delete(n),N(e))}case j.TOOL_CALL_START:{let n=e.toolCallId;if(i.has(n))return P(()=>new A(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${n}' is already in progress. Complete it with 'TOOL_CALL_END' first.`));let r=e.parentMessageId,a=e.subagentRunId,s;if(r!==void 0){let e=o.message.get(r);if(e){if(a!==void 0&&a!==e.subagentRunId)return P(()=>new A(`Cannot send 'TOOL_CALL_START': subagentRunId '${a}' does not match its parent message '${r}' owner '${e.subagentRunId??`(the parent agent)`}'. A tool call belongs to the message that carries it.`));s=e}}let c=o.toolCall.get(n);if(c){let e=re(t,a,c,`tool call`,n);if(e)return P(()=>e);if(a===void 0&&s&&s.subagentRunId!==c.subagentRunId)return P(()=>new A(`Cannot send 'TOOL_CALL_START': tool call '${n}' is owned by '${c.subagentRunId??`(the parent agent)`}' but its parent message '${r}' is owned by '${s.subagentRunId??`(the parent agent)`}'. A tool call belongs to the message that carries it.`))}return i.add(n),c||o.toolCall.set(n,a===void 0?s??{subagentRunId:void 0}:{subagentRunId:a}),N(e)}case j.TOOL_CALL_ARGS:{let n=e.toolCallId;if(!i.has(n))return P(()=>new A(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${n}'. Start a tool call with 'TOOL_CALL_START' first.`));let r=re(t,e.subagentRunId,o.toolCall.get(n),`tool call`,n);return r?P(()=>r):N(e)}case j.TOOL_CALL_END:{let n=e.toolCallId;if(!i.has(n))return P(()=>new A(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${n}'. A 'TOOL_CALL_START' event must be sent first.`));let r=re(t,e.subagentRunId,o.toolCall.get(n),`tool call`,n);return r?P(()=>r):(i.delete(n),N(e))}case j.STEP_STARTED:{let t=e.stepName,n=e.subagentRunId;return d(n).has(t)?P(()=>new A(`Step "${t}" is already active for 'STEP_STARTED'${n===void 0?``:` in subagent '${n}'`}`)):(d(n).set(t,!0),N(e))}case j.STEP_FINISHED:{let t=e.stepName,n=e.subagentRunId;if(!d(n).has(t)){let e,r=!1;for(let[i,a]of u)if(i!==n&&a.has(t)){e=i,r=!0;break}return P(r?()=>new A(`Cannot send 'STEP_FINISHED' for step "${t}" attributed to ${n===void 0?`the parent agent`:`subagent '${n}'`}: that step is open under ${e===void 0?`the parent agent`:`subagent '${e}'`}. A step must be finished by whoever started it.`):()=>new A(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}return d(n).delete(t),N(e)}case j.ACTIVITY_SNAPSHOT:{let t=e.messageId;return(!o.activity.has(t)||e.replace!==!1)&&o.activity.set(t,{subagentRunId:e.subagentRunId}),N(e)}case j.TOOL_CALL_RESULT:{let t=e.messageId;return typeof t==`string`&&o.message.set(t,{subagentRunId:e.subagentRunId}),N(e)}case j.REASONING_START:case j.REASONING_MESSAGE_START:{let n=e.messageId,r=o.reasoning.get(n);if(r){let i=re(t,e.subagentRunId,r,`reasoning message`,n);if(i)return P(()=>i)}return a.add(n),r||o.reasoning.set(n,{subagentRunId:e.subagentRunId}),N(e)}case j.REASONING_MESSAGE_CONTENT:case j.REASONING_MESSAGE_END:case j.REASONING_END:{let n=e.messageId,r=re(t,e.subagentRunId,o.reasoning.get(n),`reasoning message`,n);return r?P(()=>r):(t===j.REASONING_END&&a.delete(n),N(e))}case j.REASONING_ENCRYPTED_VALUE:{let n=e.entityId,r=e.subtype,i=r===`tool-call`?o.toolCall.get(n):r===`message`?o.message.get(n)??o.reasoning.get(n):o.reasoning.get(n),a=r===`tool-call`?`tool call`:r===`message`?`message`:`reasoning message`,s=re(t,e.subagentRunId,i,a,n);return s?P(()=>s):N(e)}case j.ACTIVITY_DELTA:{let n=e.messageId,r=re(t,e.subagentRunId,o.activity.get(n),`activity`,n);return r?P(()=>r):N(e)}case j.SUBAGENT_STARTED:{if(typeof e.subagentRunId!=`string`)return P(()=>new A(`Cannot send 'SUBAGENT_STARTED' without a 'subagentRunId'.`));if(typeof e.name!=`string`)return P(()=>new A(`Cannot send 'SUBAGENT_STARTED' without a 'name'.`));let t=e.subagentRunId,n=e.parentSubagentRunId;return p.has(t)?P(()=>new A(`Cannot send 'SUBAGENT_STARTED': subagent '${t}' is already active. Finish it with 'SUBAGENT_FINISHED' first.`)):m.has(t)?P(()=>new A(`Cannot send 'SUBAGENT_STARTED': subagent '${t}' has already finished in this run. Subagent IDs are per-invocation and cannot be reused.`)):n!==void 0&&!p.has(n)&&!m.has(n)?P(()=>new A(`Cannot send 'SUBAGENT_STARTED': parentSubagentRunId '${n}' has not been started in this run.`)):(p.set(t,!0),N(e))}case j.SUBAGENT_FINISHED:case j.SUBAGENT_ERROR:{if(typeof e.subagentRunId!=`string`)return P(()=>new A(`Cannot send '${t}' without a 'subagentRunId'.`));if(t===j.SUBAGENT_ERROR&&typeof e.message!=`string`)return P(()=>new A(`Cannot send 'SUBAGENT_ERROR' without a 'message'.`));let n=e.subagentRunId;return p.has(n)?(p.delete(n),m.add(n),N(e)):P(()=>new A(`Cannot send '${t}': no active subagent found with ID '${n}'. A 'SUBAGENT_STARTED' event must be sent first.`))}case j.MESSAGES_SNAPSHOT:{let t=ne(e.messages,!0);if(t)return P(()=>t)}return N(e);case j.RUN_STARTED:ee=!0;{let t=ne((e.input??{}).messages,!1);if(t)return P(()=>t)}return N(e);case j.RUN_FINISHED:if(f()){let e=[];for(let[t,n]of u)for(let r of n.keys())e.push(t===void 0?r:`${r} (subagent '${t}')`);let t=e.join(`, `);return P(()=>new A(`Cannot send 'RUN_FINISHED' while steps are still active: ${t}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return P(()=>new A(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(i.size>0){let e=Array.from(i.keys()).join(`, `);return P(()=>new A(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}if(p.size>0){let e=Array.from(p.keys()).join(`, `);return P(()=>new A(`Cannot send 'RUN_FINISHED' while subagents are still active: ${e}`))}return s=!0,N(e);case j.RUN_ERROR:return c=!0,N(e);case j.CUSTOM:return N(e);case j.THINKING_TEXT_MESSAGE_START:return h?g?P(()=>new A(`Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.`)):(g=!0,N(e)):P(()=>new A(`Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first.`));case j.THINKING_TEXT_MESSAGE_CONTENT:return g?N(e):P(()=>new A(`Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first.`));case j.THINKING_TEXT_MESSAGE_END:return g?(g=!1,N(e)):P(()=>new A(`Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first.`));case j.THINKING_START:return h?P(()=>new A(`Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.`)):(h=!0,N(e));case j.THINKING_END:return h?(h=!1,N(e)):P(()=>new A(`Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first.`));default:return N(e)}}))},Vl=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({}),Hl=e=>Bo(()=>uo(e())).pipe(ds(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return uo(e.text()).pipe(Io(n=>{let r=n;if(t.includes(`application/json`))try{r=JSON.parse(n)}catch{}let i=Error(`HTTP ${e.status}: ${typeof r==`string`?r:JSON.stringify(r)}`);return i.status=e.status,i.payload=r,P(()=>i)}))}let t={type:Vl.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new $i(e=>(e.next(t),(async()=>{try{for(;;){let{done:t,value:r}=await n.read();if(t)break;let i={type:Vl.DATA,data:r};e.next(i)}e.complete()}catch(t){e.error(t)}})(),()=>{n.cancel().catch(e=>{if(e?.name!==`AbortError`)throw e})})):P(()=>Error(`Failed to getReader() from response`))})),Ul=(e,t)=>{let n=Pl(t),r=new ca,i=new TextDecoder(`utf-8`,{fatal:!1}),a=``;e.subscribe({next:e=>{if(e.type!==Vl.HEADERS&&e.type===Vl.DATA&&e.data){let t=i.decode(e.data,{stream:!0});a+=t;let n=a.split(/\n\n/);a=n.pop()||``;for(let e of n)o(e)}},error:e=>r.error(e),complete:()=>{a&&(a+=i.decode(),o(a)),r.complete()}});function o(e){let t=e.split(`
6`),i=[];for(let e of t)e.startsWith(`data:`)&&i.push(e.slice(5).replace(/^ /,``));if(i.length>0)try{let e=i.join(`
7`),t=JSON.parse(e);n?.event(`SSE`,`Event received:`,t,{type:t.type}),r.next(t)}catch(e){r.error(e)}}return r.asObservable()},Wl=e=>{let t=new ca,n=new Uint8Array;e.subscribe({next:e=>{if(e.type!==Vl.HEADERS&&e.type===Vl.DATA&&e.data){let t=new Uint8Array(n.length+e.data.length);t.set(n,0),t.set(e.data,n.length),n=t,r()}},error:e=>t.error(e),complete:()=>{if(n.length>0)try{r()}catch{console.warn(`Incomplete or invalid protocol buffer data at stream end`)}t.complete()}});function r(){for(;n.length>=4;){let e=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<e)break;try{let r=bl(n.slice(4,e));t.next(r),n=n.slice(e)}catch(e){let n=e instanceof Error?e.message:String(e);t.error(Error(`Failed to decode protocol buffer message: ${n}`));return}}}return t.asObservable()},Gl=(e,t)=>
vendor: 6,446 bytes, lines 7-8
7{let n=Pl(t),r=new ca,i=new fa,a=!1;return e.subscribe({next:e=>{if(i.next(e),e.type===Vl.HEADERS&&!a){a=!0;let t=e.headers.get(`content-type`);n?.lifecycle(`HTTP`,`Stream format detected:`,{contentType:t,parser:t===`application/vnd.ag-ui.event+proto`?`protobuf`:`sse`}),t===`application/vnd.ag-ui.event+proto`?Wl(i).subscribe({next:e=>r.next(e),error:e=>r.error(e),complete:()=>r.complete()}):Ul(i,n).subscribe({next:e=>{try{let t=Er.parse(e);n?.event(`HTTP`,`Event validated:`,t,{type:t.type,valid:!0}),r.next(t)}catch(t){n?.event(`HTTP`,`Event invalid:`,{json:e,error:String(t)}),r.error(t)}},error:e=>{if(e?.name===`AbortError`){r.next({type:j.RUN_ERROR,message:e.message||`Request aborted`,code:`abort`,rawEvent:e}),r.complete();return}return r.error(e)},complete:()=>r.complete()})}else a||r.error(Error(`No headers event received before data events`))},error:e=>{i.error(e),r.error(e)},complete:()=>{i.complete()}}),r.asObservable()},Kl=tn([`TextMessageStart`,`TextMessageContent`,`TextMessageEnd`,`ActionExecutionStart`,`ActionExecutionArgs`,`ActionExecutionEnd`,`ActionExecutionResult`,`AgentStateMessage`,`MetaEvent`,`RunStarted`,`RunFinished`,`RunError`,`NodeStarted`,`NodeFinished`]),ql=tn([`LangGraphInterruptEvent`,`PredictState`,`Exit`]);$t(`type`,[O({type:k(Kl.enum.TextMessageStart),messageId:E(),parentMessageId:E().optional(),role:E().optional()}),O({type:k(Kl.enum.TextMessageContent),messageId:E(),content:E()}),O({type:k(Kl.enum.TextMessageEnd),messageId:E()}),O({type:k(Kl.enum.ActionExecutionStart),actionExecutionId:E(),actionName:E(),parentMessageId:E().optional()}),O({type:k(Kl.enum.ActionExecutionArgs),actionExecutionId:E(),args:E()}),O({type:k(Kl.enum.ActionExecutionEnd),actionExecutionId:E()}),O({type:k(Kl.enum.ActionExecutionResult),actionName:E(),actionExecutionId:E(),result:E()}),O({type:k(Kl.enum.AgentStateMessage),threadId:E(),agentName:E(),nodeName:E(),runId:E(),active:D(),role:E(),state:E(),running:D()}),O({type:k(Kl.enum.MetaEvent),name:ql,value:Yt()}),O({type:k(Kl.enum.RunError),message:E(),code:E().optional()})]),O({id:E(),role:E(),content:E(),parentMessageId:E().optional()}),O({id:E(),name:E(),arguments:Yt(),parentMessageId:E().optional()}),O({id:E(),result:Yt(),actionExecutionId:E(),actionName:E()});var Jl=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=e.filter(e=>e.type===`text`).map(e=>e.text).filter(e=>e.length>0);if(t.length!==0)return t.join(`
8`)},Yl=(e,t,n)=>r=>{let i={},a=!0,o=!0,s=``,c=null,l=null,u=[],d={},f=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,i=e)};return r.pipe(Io(r=>{switch(r.type){case j.TEXT_MESSAGE_START:{let e=r;return[{type:Kl.enum.TextMessageStart,messageId:e.messageId,role:e.role}]}case j.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:Kl.enum.TextMessageContent,messageId:e.messageId,content:e.delta}]}case j.TEXT_MESSAGE_END:{let e=r;return[{type:Kl.enum.TextMessageEnd,messageId:e.messageId}]}case j.TOOL_CALL_START:{let e=r;return u.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),o=!0,d[e.toolCallId]=e.toolCallName,[{type:Kl.enum.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case j.TOOL_CALL_ARGS:{let c=r,d=u.find(e=>e.id===c.toolCallId);if(!d)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];d.function.arguments+=c.delta;let p=!1;if(l){let e=l.find(e=>e.tool==d.function.name);if(e)try{let t=JSON.parse(gs(d.function.arguments));e.tool_argument&&e.tool_argument in t?(f({...i,[e.state_key]:t[e.tool_argument]}),p=!0):e.tool_argument||(f({...i,[e.state_key]:t}),p=!0)}catch{}}return[{type:Kl.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...p?[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]:[]]}case j.TOOL_CALL_END:{let e=r;return[{type:Kl.enum.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case j.TOOL_CALL_RESULT:{let e=r;return[{type:Kl.enum.ActionExecutionResult,actionExecutionId:e.toolCallId,result:e.content,actionName:d[e.toolCallId]||`unknown`}]}case j.RAW:return[];case j.CUSTOM:{let e=r;switch(e.name){case`Exit`:a=!1;break;case`PredictState`:l=e.value}return[{type:Kl.enum.MetaEvent,name:e.name,value:e.value}]}case j.STATE_SNAPSHOT:return f(r.snapshot),[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}];case j.STATE_DELTA:{let c=r,l=ci.applyPatch(i,c.delta,!0,!1);return l?(f(l.newDocument),[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]):[]}case j.MESSAGES_SNAPSHOT:return c=r.messages,[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:c}:{}}),active:!0}];case j.RUN_STARTED:return[];case j.RUN_FINISHED:return c&&(i.messages=c),Object.keys(i).length===0?[]:[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:Xl(c)}:{}}),active:!1}];case j.RUN_ERROR:{let e=r;return[{type:Kl.enum.RunError,message:e.message,code:e.code}]}case j.STEP_STARTED:return s=r.stepName,u=[],l=null,[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!0}];case j.STEP_FINISHED:return u=[],l=null,[{type:Kl.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!1}];default:return[]}}))};function Xl(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=Jl(n.content);if(e){let r={id:n.id,role:n.role,content:e};t.push(r)}if(n.role===`assistant`&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let r={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:n.id};t.push(r)}}else if(n.role===`tool`){let r=`unknown`;for(let t of e)if(t.role===`assistant`&&t.toolCalls?.length){for(let e of t.toolCalls)if(e.id===n.toolCallId){r=e.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};t.push(i)}return t}var Zl=e=>e.kind===`tool`?e.fields.toolCallId:e.fields.messageId,Ql=e=>e===`tool`?`toolCallId`:`messageId`,$l=(e,t)=>
vendor: 7,340 bytes, line 8
8t.metadata===void 0?e:{...e,metadata:t.metadata},eu=e=>t=>{let n=Pl(e),r=new Map,i=e=>{let t=r.get(e);if(!t)return[];switch(r.delete(e),t.kind){case`text`:{let e={type:j.TEXT_MESSAGE_END,messageId:t.fields.messageId,...t.fields.subagentRunId!=null&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`TEXT_MESSAGE_END`,e,{messageId:e.messageId}),[e]}case`tool`:{let e={type:j.TOOL_CALL_END,toolCallId:t.fields.toolCallId,...t.fields.subagentRunId!=null&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`TOOL_CALL_END`,e,{toolCallId:e.toolCallId}),[e]}case`reasoning`:{let e={type:j.REASONING_MESSAGE_END,messageId:t.fields.messageId,...t.fields.subagentRunId!=null&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`REASONING_MESSAGE_END`,e,{messageId:e.messageId}),[e]}}},a=()=>[...r.keys()].flatMap(e=>i(e)),o=(e,t)=>{for(let[n,i]of r)if(i.kind===e&&Zl(i)===t)return{owner:n}},s=(e,t,n,i,a)=>{if(t!==void 0){let r=o(e,t);if(r){if(n!==void 0&&n!==r.owner)throw Error(`Cannot continue ${a} '${t}': chunk subagentRunId '${n}' does not match the open stream's subagent '${r.owner??`(the parent agent)`}'.`);return r.owner}return n}if(n!==void 0)return n;if(r.get(void 0)?.kind===e)return;let s=[...r.entries()].filter(([,t])=>t.kind===e);if(s.length===1)return s[0][0];if(s.length>1)throw Error(`Ambiguous ${i}: it carries neither a ${Ql(e)} nor a subagentRunId, but ${s.length} lanes have an open ${a}. Attribute the chunk to the subagent it belongs to.`)};return t.pipe(Io(e=>{switch(e.type){case j.TEXT_MESSAGE_START:case j.TEXT_MESSAGE_CONTENT:case j.TEXT_MESSAGE_END:case j.TOOL_CALL_START:case j.TOOL_CALL_ARGS:case j.TOOL_CALL_END:case j.TOOL_CALL_RESULT:case j.STATE_SNAPSHOT:case j.STATE_DELTA:case j.CUSTOM:case j.STEP_STARTED:case j.STEP_FINISHED:case j.THINKING_START:case j.THINKING_END:case j.THINKING_TEXT_MESSAGE_START:case j.THINKING_TEXT_MESSAGE_CONTENT:case j.THINKING_TEXT_MESSAGE_END:case j.REASONING_START:case j.REASONING_MESSAGE_START:case j.REASONING_MESSAGE_CONTENT:case j.REASONING_MESSAGE_END:case j.REASONING_END:return[...i(e.subagentRunId??void 0),e];case j.RUN_STARTED:case j.RUN_FINISHED:case j.RUN_ERROR:case j.MESSAGES_SNAPSHOT:return[...a(),e];case j.RAW:case j.ACTIVITY_SNAPSHOT:case j.ACTIVITY_DELTA:case j.REASONING_ENCRYPTED_VALUE:case j.SUBAGENT_STARTED:return[e];case j.SUBAGENT_FINISHED:case j.SUBAGENT_ERROR:{let t=e.subagentRunId;return t==null?[e]:[...i(t),e]}case j.TEXT_MESSAGE_CHUNK:{let t=e,a=s(`text`,t.messageId,t.subagentRunId??void 0,`TEXT_MESSAGE_CHUNK`,`text message`),o=r.get(a),c=[],l;if(o?.kind===`text`&&(t.messageId===void 0||t.messageId===o.fields.messageId))l=o.fields;else{if(c.push(...i(a)),t.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);l={messageId:t.messageId,name:t.name,subagentRunId:t.subagentRunId},r.set(a,{kind:`text`,fields:l});let e=$l({type:j.TEXT_MESSAGE_START,messageId:t.messageId,role:t.role||`assistant`,...t.name!==void 0&&{name:t.name},...t.subagentRunId!=null&&{subagentRunId:t.subagentRunId}},t);c.push(e),n?.event(`TRANSFORM`,`TEXT_MESSAGE_START`,e,{messageId:t.messageId})}if(t.delta!==void 0){let e=t.subagentRunId??l.subagentRunId,r=$l({type:j.TEXT_MESSAGE_CONTENT,messageId:l.messageId,delta:t.delta,...e!=null&&{subagentRunId:e}},t);c.push(r),n?.event(`TRANSFORM`,`TEXT_MESSAGE_CONTENT`,r,{messageId:l.messageId})}if(c.length===0&&t.metadata!==void 0){let e=t.subagentRunId??l.subagentRunId;c.push({type:j.TEXT_MESSAGE_CONTENT,messageId:l.messageId,delta:``,metadata:t.metadata,...e!=null&&{subagentRunId:e}})}return c}case j.TOOL_CALL_CHUNK:{let t=e,a=s(`tool`,t.toolCallId,t.subagentRunId??void 0,`TOOL_CALL_CHUNK`,`tool call`),o=r.get(a),c=[],l;if(o?.kind===`tool`&&(t.toolCallId===void 0||t.toolCallId===o.fields.toolCallId))l=o.fields;else{if(c.push(...i(a)),t.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(t.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);l={toolCallId:t.toolCallId,toolCallName:t.toolCallName,parentMessageId:t.parentMessageId,subagentRunId:t.subagentRunId},r.set(a,{kind:`tool`,fields:l});let e=$l({type:j.TOOL_CALL_START,toolCallId:t.toolCallId,toolCallName:t.toolCallName,parentMessageId:t.parentMessageId,...t.subagentRunId!=null&&{subagentRunId:t.subagentRunId}},t);c.push(e),n?.event(`TRANSFORM`,`TOOL_CALL_START`,e,{toolCallId:t.toolCallId,toolCallName:t.toolCallName})}if(t.delta!==void 0){let e=t.subagentRunId??l.subagentRunId,r=$l({type:j.TOOL_CALL_ARGS,toolCallId:l.toolCallId,delta:t.delta,...e!=null&&{subagentRunId:e}},t);c.push(r),n?.event(`TRANSFORM`,`TOOL_CALL_ARGS`,r,{toolCallId:l.toolCallId})}if(c.length===0&&t.metadata!==void 0){let e=t.subagentRunId??l.subagentRunId;c.push({type:j.TOOL_CALL_ARGS,toolCallId:l.toolCallId,delta:``,metadata:t.metadata,...e!=null&&{subagentRunId:e}})}return c}case j.REASONING_MESSAGE_CHUNK:{let t=e,a=s(`reasoning`,t.messageId,t.subagentRunId??void 0,`REASONING_MESSAGE_CHUNK`,`reasoning message`),o=r.get(a),c=[],l;if(o?.kind===`reasoning`&&(t.messageId===void 0||t.messageId===o.fields.messageId))l=o.fields;else{if(c.push(...i(a)),t.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);l={messageId:t.messageId,subagentRunId:t.subagentRunId},r.set(a,{kind:`reasoning`,fields:l});let e=$l({type:j.REASONING_MESSAGE_START,messageId:t.messageId,role:`reasoning`,...t.subagentRunId!=null&&{subagentRunId:t.subagentRunId}},t);c.push(e),n?.event(`TRANSFORM`,`REASONING_MESSAGE_START`,e,{messageId:t.messageId})}if(t.delta!==void 0){let e=t.subagentRunId??l.subagentRunId,r=$l({type:j.REASONING_MESSAGE_CONTENT,messageId:l.messageId,delta:t.delta,...e!=null&&{subagentRunId:e}},t);c.push(r),n?.event(`TRANSFORM`,`REASONING_MESSAGE_CONTENT`,r,{messageId:l.messageId})}if(c.length===0&&t.metadata!==void 0){let e=t.subagentRunId??l.subagentRunId;c.push({type:j.REASONING_MESSAGE_CONTENT,messageId:l.messageId,delta:``,metadata:t.metadata,...e!=null&&{subagentRunId:e}})}return c}}return e.type,[]}),os(()=>{a()}))};function tu(e,t=new Date){return e.expiresAt!==void 0&&new Date(e.expiresAt)<=t}var nu=class{runNext(e,t){return t.run(e).pipe(eu(!1))}runNextWithState(e,t){let n=B(e.messages||[]),r=B(e.state||{}),i=new fa;return zl(e,i,t,[]).subscribe(e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)}),this.runNext(e,t).pipe(qo(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:B(n),state:B(r)})))}},ru=class extends nu{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}};function iu(e){let t=e.content;if(Array.isArray(t)){let n=t.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``);return{...e,content:n}}return typeof t==`string`?e:{...e,content:``}}var au=class extends nu{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(iu)};return this.runNext(i,t)}},ou=`THINKING_START`,su=`THINKING_END`,cu=`THINKING_TEXT_MESSAGE_START`,lu=`THINKING_TEXT_MESSAGE_CONTENT`,uu=`THINKING_TEXT_MESSAGE_END`,du=class extends nu{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){typeof process<`u`&&{NODE_ENV:`development`}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is convert
8ing ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe(F(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case ou:{this.currentReasoningId=kl();let{title:t,...n}=e;return this.warnAboutTransformation(ou,j.REASONING_START),{...n,type:j.REASONING_START,messageId:this.currentReasoningId}}case cu:return this.currentMessageId=kl(),this.warnAboutTransformation(cu,j.REASONING_MESSAGE_START),{...e,type:j.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`assistant`};case lu:{let{delta:t,...n}=e;return this.warnAboutTransformation(lu,j.REASONING_MESSAGE_CONTENT),{...n,type:j.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??kl(),delta:t}}case uu:{let t=this.currentMessageId??kl();return this.warnAboutTransformation(uu,j.REASONING_MESSAGE_END),{...e,type:j.REASONING_MESSAGE_END,messageId:t}}case su:{let t=this.currentReasoningId??kl();return this.warnAboutTransformation(su,j.REASONING_END),{...e,type:j.REASONING_END,messageId:t}}default:return e}}};function fu(e){return e.startsWith(`image/`)?`image`:e.startsWith(`audio/`)?`audio`:e.startsWith(`video/`)?`video`:`document`}function pu(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`binary`&&`mimeType`in e&&typeof e.mimeType==`string`}function mu(e){let t=fu(e.mimeType);return e.data?{type:t,source:{type:`data`,value:e.data,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e.url?{type:t,source:{type:`url`,value:e.url,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e}function hu(e){let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>pu(e)?mu(e):e);return{...e,content:n}}var gu=class extends nu{run(e,t){let n={...e,messages:e.messages.map(hu)};return this.runNext(n,t)}},_u=`SUBAGENT_STARTED`,vu=`SUBAGENT_FINISHED`,yu=`SUBAGENT_ERROR`;function bu(e){if(e&&typeof e==`object`&&`subagentRunId`in e){let{subagentRunId:t,...n}=e;return n}return e}function xu(e){return e.map(e=>bu(e))}var Su=class extends nu{warnDroppedLifecycleEvent(e){typeof process<`u`&&{NODE_ENV:`development`}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${e} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){let n={...e,messages:(e.messages??[]).map(e=>bu(e))};return this.runNext(n,t).pipe(ps(e=>{let t=e.type;(t===_u||t===vu||t===yu)&&this.warnDroppedLifecycleEvent(t)}),Wo(e=>{let t=e.type;return t!==_u&&t!==vu&&t!==yu}),F(e=>{let t=bu(e);if(t.type===j.MESSAGES_SNAPSHOT){let e=t;if(Array.isArray(e.messages))return{...e,messages:xu(e.messages)}}if(t.type===j.RUN_FINISHED){let e=t;if(e.outcome&&Array.isArray(e.outcome.interrupts))return{...e,outcome:{...e.outcome,interrupts:e.outcome.interrupts.map(e=>bu(e))}}}if(t.type===j.RUN_STARTED){let e=t;if(e.input&&Array.isArray(e.input.messages))return{...e,input:{...e.input,messages:xu(e.input.messages)}}}return t}))}},Cu=`0.0.59`,wu=class{get maxVersion(){return Cu}get debug(){return this._debug}set debug(e){this._debug=Nl(e),this._debugLogger=Il(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(e){this._debugLogger=typeof e==`boolean`?e?Il(Nl(!0)):void 0:e}constructor({agentId:e,description:t,threadId:n,initialMessages:i,initialState:a,debug:o}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=e,this.description=t??``,this.threadId=n??r(),this.messages=B(i??[]),this.state=B(a??{}),this._debug=Nl(o),this._debugLogger=Il(this._debug),Ol(this.maxVersion,`0.0.39`)<=0&&this.middlewares.unshift(new au),Ol(this.maxVersion,`0.0.45`)<=0&&this.middlewares.unshift(new du),Ol(this.maxVersion,`0.0.47`)<=0&&this.middlewares.unshift(new gu),Ol(this.maxVersion,`0.0.57`)<=0&&this.middlewares.unshift(new Su)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(e=>typeof e==`function`?new ru(e):e);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??r();let n=this.prepareRunAgentInput(e);this.debugLogger?.lifecycle(`LIFECYCLE`,`Run started:`,{agentId:this.agentId,threadId:this.threadId});let i,a=new Set(this.messages.map(e=>e.id)),o=[{onRunFinishedEvent:e=>{e.outcome===`success`&&(i=e.result)}},...this.subscribers,t??{}];await this.onInitialize(n,o),this.activeRunDetach$=new ca;let s;this.activeRunCompletionPromise=new Promise(e=>{s=e}),await go(Zi(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(n),eu(this.debugLogger),Bl(this.debugLogger),e=>e.pipe(fs(this.activeRunDetach$)),e=>this.apply(n,e,o),e=>this.processApplyEvents(n,e,o),Go(e=>(this.debugLogger?.lifecycle(`LIFECYCLE`,`Run errored:`,{agentId:this.agentId,error:e instanceof Error?e.message:String(e)}),this.isRunning=!1,this.onError(n,e,o))),os(()=>{this.debugLogger?.lifecycle(`LIFECYCLE`,`Run finished:`,{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(N(null)));let c=B(this.messages).filter(e=>!a.has(e.id));return{result:i,newMessages:c}}finally{this.isRunning=!1}}connect(e){throw new Dn}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??r();let n=this.prepareRunAgentInput(e),i,a=new Set(this.messages.map(e=>e.id)),o=[{onRunFinishedEvent:e=>{e.outcome===`success`&&(i=e.result)}},...this.subscribers,t??{}];await this.onInitialize(n,o),this.activeRunDetach$=new ca;let s;this.activeRunCompletionPromise=new Promise(e=>{s=e}),await go(Zi(()=>Bo(()=>this.connect(n)),eu(this.debugLogger),Bl(this.debugLogger),e=>e.pipe(fs(this.activeRunDetach$)),e=>this.apply(n,e,o),e=>this.processApplyEvents(n,e,o),Go(e=>(this.isRunning=!1,e instanceof Dn?Aa:this.onError(n,e,o))),os(()=>{this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(N(null)),{defaultValue:void 0});let c=B(this.messages).filter(e=>!a.has(e.id));return{result:i,newMessages:c}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}apply(e,t,n){return zl(e,t,this,n,this.debugLogger)}
vendor: 1,850 bytes, line 8
8processApplyEvents(e,t,n){return t.pipe(ps(t=>{t.messages&&(this.messages=t.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),t.state&&(this.state=t.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=B(this.messages);for(let e of t)e.subagentRunId===null&&delete e.subagentRunId;let n=t.filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:e?.runId||r(),tools:B(e?.tools??[]),context:B(e?.context??[]),forwardedProps:B(e?.forwardedProps??{}),state:B(this.state),messages:n,...e?.resume===void 0?{}:{resume:B(e.resume)}}}async onInitialize(e,t){if(this.pendingInterrupts.length>0){let t=new Set((e.resume??[]).map(e=>e.interruptId)),n=this.pendingInterrupts.map(e=>e.id).filter(e=>!t.has(e));if(n.length>0)throw new A(`Thread has ${n.length} pending interrupt(s) not addressed by resume: ${n.join(`, `)}`);for(let e of this.pendingInterrupts)if(tu(e))throw new A(`Interrupt ${e.id} expired at ${e.expiresAt}`)}let n=await V(t,this.messages,this.state,(t,n,r)=>t.onRunInitialized?.({messages:n,state:r,agent:this,input:e}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let e of n.messages)e.subagentRunId===null&&delete e.subagentRunId;e.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})}n.state&&(this.state=n.state,e.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}}onError(e,t,n){return uo(V(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe(F(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEac
8h(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),i.state!==void 0&&(this.state=i.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),i.stopPropagation!==!0){let e=String(t);if(t.name!==`AbortError`&&t.message!==`Fetch is aborted`&&t.message!==`signal is aborted without reason`&&t.message!==`component unmounted`&&e!==`component unmounted`)throw console.error(`Agent execution failed:`,t),t}return{}}))}async onFinalize(e,t){let n=await V(t,this.messages,this.state,(t,n,r)=>t.onRunFinalized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=B(this.messages),e.state=B(this.state),e._debug=this._debug,e._debugLogger=this._debugLogger,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e.pendingInterrupts=B(this.pendingInterrupts),e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role===`assistant`&&e.toolCalls)for(let t of e.toolCalls)for(let e of this.subscribers)await e.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)for(let t of this.subscribers)await t.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=B(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=B(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??r();let t=this.prepareRunAgentInput(e);return(this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(t)).pipe(eu(this.debugLogger),Bl(this.debugLogger),Yl(this.threadId,t.runId,this.agentId),e=>e.pipe(F(e=>(this.debugLogger?.event(`LEGACY`,`Event:`,e,{type:e.type}),e))))}};function Tu(e){if(!Array.isArray(e.messages))return e;let t=!1,n=e.messages.map(e=>{if(e.subagentRunId===null){t=!0;let n={...e};return delete n.subagentRunId,n}return e});return t?{...e,messages:n}:e}var Eu=class extends wu{requestInit(e){return{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify(Tu(e)),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=B(e.headers??{}),this.fetch=e.fetch??((e,t)=>fetch(e,t))}run(e){return Gl(Hl(()=>this.fetch(this.url,this.requestInit(e))),this.debugLogger)}clone(){let e=super.clone();e.url=this.url,e.headers=B(this.headers??{}),e.fetch=this.fetch;let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};function Du(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return!1}}function Ou(e,t){try{let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&`value`in n?n.value:void 0}catch{return}}function ku(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Au(e){if(!Du(e))return;let t=ku(e.organizationName),n=ku(e.projectName);if(t!==void 0&&n!==void 0)return{organizationName:t,projectName:n}}function ju(e){if(!Du(e))return;let t=ku(e.code),n=ku(e.label);if(t!==void 0&&n!==void 0)return{code:t,label:n}}function Mu(e){if(Du(e))switch(e.state){case`valid`:case`none`:case`expired`:case`unknown`:return{state:e.state};default:return}}function Nu(e){switch(e){case`manage_plan`:case`renew`:case`enable_intelligence`:return e;default:return}}function Pu(e){let t=ku(e);if(t===void 0||t.includes(`?`)||t.includes(`#`))return;let n=t.indexOf(`://`);if(n<1)return;let r=t.slice(n+3),i=r.indexOf(`/`);if((i===-1?r:r.slice(0,i)).includes(`@`))return;let a;try{a=new URL(t)}catch{return}if(a.hostname.length===0||a.username||a.password)return;if(a.protocol===`https:`)return t;let o=a.hostname===`localhost`||a.hostname===`127.0.0.1`||a.hostname===`[::1]`;if(a.protocol===`http:`&&o)return t}function Fu(e){if(!Du(e))return;let t=Nu(e.kind),n=Pu(e.url);if(t!==void 0&&n!==void 0)return{kind:t,url:n}}function Iu(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Lu(e){if(Du(e)){if(e.kind===`finite`)return typeof e.value!=`number`||!Number.isSafeInteger(e.value)||e.value<1?void 0:{kind:`finite`,value:e.value};if(e.kind===`unlimited`)return{kind:`unlimited`};
8if(e.kind===`unknown`)return{kind:`unknown`}}}function Ru(e){if(!Du(e))return;let t=Lu(e.limit),n=e.used;if(!Iu(n)||t===void 0)return;let r=Ou(e,`expiringSoonCount`),i=Iu(r)?r:void 0;return{used:n,limit:t,...i===void 0?{}:{expiringSoonCount:i}}}function zu(e){if(!Du(e)||e.schemaVersion!==1)return;let t=Au(e.identity),n=ju(e.plan),r=Mu(e.license),i=Fu(e.action),a=Ru(e.usage);return{schemaVersion:1,...t===void 0?{}:{identity:t},...n===void 0?{}:{plan:n},...r===void 0?{}:{license:r},...i===void 0?{}:{action:i},...a===void 0?{}:{usage:a}}}var Bu=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),Vu=e(n((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var r=Bu();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(Bu(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;var s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&` 
9\r	`.includes(e[o]);)o++};return l()};e.parse=o}))(),1);function Hu(e){try{let t=Vu.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function Uu(e,t){return n=>Math.min(e*2**(n-1),t)}
9var Wu={enabled:!1,events:!1,lifecycle:!1,verbose:!1};function Gu(e){if(!e)return Wu;if(e===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!1};let t=e.events??!0,n=e.lifecycle??!0,r=t||n;return{enabled:r,events:t,lifecycle:n,verbose:r&&(e.verbose??!1)}}function Ku(e){let t=e[`~standard`];return typeof t==`object`&&!!t&&`jsonSchema`in t&&t.jsonSchema!=null&&typeof t.jsonSchema==`object`&&`input`in t.jsonSchema&&typeof t.jsonSchema.input==`function`}function qu(e,t){if(Ku(e))return e[`~standard`].jsonSchema.input({target:`draft-07`});if(typeof e.toJSONSchema==`function`)return e.toJSONSchema();let n=e[`~standard`].vendor;if(n===`zod`&&t?.zodToJsonSchema)return t.zodToJsonSchema(e,{$refStrategy:`none`});throw Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${n}") does not implement Standard JSON Schema V1 and no zodToJsonSchema fallback is available. Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) or pass a zodToJsonSchema function in options.`)}var Ju=console,Yu=e=>typeof e==`function`?e:function(){return e},Xu=typeof self<`u`?self:null,Zu=typeof window<`u`?window:null,Qu=Xu||Zu||globalThis,$u=`2.0.0`,ed={connecting:0,open:1,closing:2,closed:3},td=100,nd=1e4,rd=1e3,id={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},ad={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`},od={longpoll:`longpoll`,websocket:`websocket`},sd={complete:4},cd=`base64url.bearer.phx.`,ld=class{constructor(e,t,n,r){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived(`timeout`)||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger(`timeout`,{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},ud=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},dd=class{constructor(e,t,n){this.state=id.closed,this.topic=e,this.params=Yu(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ld(this,ad.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ud(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive(`ok`,()=>{this.state=id.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive(`error`,()=>{this.state=id.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log(`channel`,`close ${this.topic} ${this.joinRef()}`),this.state=id.closed,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=id.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive(`timeout`,()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new ld(this,ad.leave,Yu({}),this.timeout).send(),this.state=id.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(ad.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(this.joinedOnce)throw Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`);return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(ad.close,e)}onError(e){return this.on(ad.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>n.event!==e||t!==void 0&&t!==n.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t||={},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new ld(this,e,function(){return t},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=id.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`leave ${this.topic}`),this.trigger(ad.close,`leave`)},n=new ld(this,ad.leave,Yu({}),e);return n.receive(`ok`,()=>t()).receive(`timeout`,()=>t()),n.send(),this.canPush()||n.trigger(`ok`,{}),n}onMessage(e,t,n){return t}isMember(e,t,n,r){return this.topic===e?r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log(`channel`,`dropping outdated message`,{topic:e,event:t,payload:n,joinRef:r}),!1):!0:!1}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=id.joining,this.joinPush.resend(e))}trigger(e,t,n,r){let i=this.onMessage(e,t,n,r);if(t&&!i)throw Error(`channel onMessage callbacks must return the payload, modified or unmodified`);let a=this.bindings.filter(t=>t.event===e);for(let e=0;e<a.length;e++)a[e].callback(i,n,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===id.closed}isErrored(){return this.state===id.errored}isJoined(){return this.state===id.joined}isJoining(){return this.state===id.joining}isLeaving(){return this.state===id.leaving}},fd=class{static request(e,t,n,r,i,a,o){if(Qu.XDomainRequest){let n=new Qu.XDomainRequest;return this.xdomainRequest(n,e,t,r,i,a,o)}if(Qu.XMLHttpRequest){let s=new Qu.XMLHttpRequest;return this.xhrRequest(s,e,t,n,r,i,a,o)}if(Qu.fetch&&Qu.AbortController)return this.fetchRequest(e,t,n,r,i,a,o);throw Error(`No suitable XMLHttpRequest implementation found`)}static fetchRequest(e,t,n,r,i,a,o){let s={method:e,headers:n,body:r},c=null;return i&&(c=new AbortController,setTimeout(()=>c.abort(),i),s.signal=c.signal),Qu.fetch(t,s).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>o&&o(e)).catch(e=>{e.name===`AbortError`&&a?a():o&&o(null)}),c}static xdomainRequest(e,t,n,r,i,a,o){return e.timeout=i,e.open(t,n),e.onload=()=>{let t=this.parseJSON(e.responseText);o&&o(t)},a&&(e.ontimeout=a),e.onprogress=()=>{},e.send(r),e}
vendor: 9,148 bytes, lines 9-10
9static xhrRequest(e,t,n,r,i,a,o,s){e.open(t,n,!0),e.timeout=a;for(let[t,n]of Object.entries(r))e.setRequestHeader(t,n);return e.onerror=()=>s&&s(null),e.onreadystatechange=()=>{e.readyState===sd.complete&&s&&s(this.parseJSON(e.responseText))},o&&(e.ontimeout=o),e.send(i),e}static parseJSON(e){if(!e||e===``)return null;try{return JSON.parse(e)}catch{return console&&console.log(`failed to parse JSON response`,e),null}}static serialize(e,t){let n=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t?`${t}[${r}]`:r,a=e[r];typeof a==`object`?n.push(this.serialize(a,i)):n.push(encodeURIComponent(i)+`=`+encodeURIComponent(a))}return n.join(`&`)}static appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${this.serialize(t)}`}},pd=e=>{let t=``,n=new Uint8Array(e),r=n.byteLength;for(let e=0;e<r;e++)t+=String.fromCharCode(n[e]);return btoa(t)},md=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(cd)&&(this.authToken=atob(t[1].slice(cd.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=ed.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace(`ws://`,`http://`).replace(`wss://`,`https://`).replace(RegExp(`(.*)/`+od.websocket),`$1/`+od.longpoll)}endpointURL(){return fd.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n){this.close(e,t,n),this.readyState=ed.connecting}ontimeout(){this.onerror(`timeout`),this.closeAndRetry(1005,`timeout`,!1)}isActive(){return this.readyState===ed.open||this.readyState===ed.connecting}poll(){let e={Accept:`application/json`};this.authToken&&(e[`X-Phoenix-AuthToken`]=this.authToken),this.ajax(`GET`,e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:n,messages:r}=e;if(t===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,`session_gone`,!1);return}this.token=n}else t=0;switch(t){case 200:r.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ed.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,`forbidden`,!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,`internal server error`,500);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){typeof e!=`string`&&(e=pd(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let n=t+td,r=e.slice(t,n);this.ajax(`POST`,{"Content-Type":`application/x-ndjson`},r.join(`
10`),()=>this.onerror(`timeout`),t=>{!t||t.status!==200?(this.awaitingBatchAck=!1,this.onerror(t&&t.status),this.closeAndRetry(1011,`internal server error`,!1)):n<e.length?this.batchSend(e,n):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,n){for(let e of this.reqs)e.abort();this.readyState=ed.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<`u`?this.onclose(new CloseEvent(`close`,r)):this.onclose(r)}ajax(e,t,n,r,i){let a;a=fd.request(e,this.endpointURL(),t,n,this.timeout,()=>{this.reqs.delete(a),r()},e=>{this.reqs.delete(a),this.isActive()&&i(e)}),this.reqs.add(a)}},hd={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}},binaryEncode(e){let{join_ref:t,ref:n,event:r,topic:i,payload:a}=e,o=new TextEncoder,s=o.encode(t),c=o.encode(n),l=o.encode(i),u=o.encode(r);this.assertFieldSize(s.byteLength,`join_ref`),this.assertFieldSize(c.byteLength,`ref`),this.assertFieldSize(l.byteLength,`topic`),this.assertFieldSize(u.byteLength,`event`);let d=this.META_LENGTH+s.byteLength+c.byteLength+l.byteLength+u.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+d),p=new Uint8Array(f),m=new DataView(f),h=0;m.setUint8(h++,this.KINDS.push),m.setUint8(h++,s.byteLength),m.setUint8(h++,c.byteLength),m.setUint8(h++,l.byteLength),m.setUint8(h++,u.byteLength),p.set(s,h),h+=s.byteLength,p.set(c,h),h+=c.byteLength,p.set(l,h),h+=l.byteLength,p.set(u,h),h+=u.byteLength;var g=new Uint8Array(f.byteLength+a.byteLength);return g.set(p,0),g.set(new Uint8Array(a),f.byteLength),g.buffer},assertFieldSize(e,t){if(e>255)throw Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,s=n.decode(e.slice(o,o+r));o+=r;let c=n.decode(e.slice(o,o+i));o+=i;let l=n.decode(e.slice(o,o+a));return o+=a,{join_ref:s,ref:null,topic:c,event:l,payload:e.slice(o,e.byteLength)}},decodeReply(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=n.decode(e.slice(s,s+o));s+=o;let f={status:d,response:e.slice(s,e.byteLength)};return{join_ref:c,ref:l,topic:u,event:ad.reply,payload:f}},decodeBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,o=n.decode(e.slice(a,a+r));a+=r;let s=n.decode(e.slice(a,a+i));return a+=i,{join_ref:null,ref:null,topic:o,event:s,payload:e.slice(a,e.byteLength)}}},gd=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||nd,this.transport=t.transport||Qu.WebSocket||md,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||Qu&&Qu.sessionStorage,this.establishedConnections=0,this.defaultEncoder=hd.encode.bind(hd),this.defaultDecoder=hd.decode.bind(hd),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||`arraybuffer`,this.connectClock=1,this.pageHidden=!1,this.transport===md?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let n=null;Zu&&Zu.addEventListener&&(Zu.addEventListener(`pagehide`,e=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Zu.addEventListener(`pageshow`,e=>{n===this.connectClock&&(n=null,this.connect())}),Zu.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,n)=>{console.log(`${e}: ${t}`,n)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Yu(t.params||{}),this.endPoint=`${e}/${od.websocket}`,this.vsn=t.vsn||$u,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ud(()=>{if(this.pageHidden){this.log(`Not reconnecting as page is hidden!`),this.teardown();return}this.teardown(()=>this.connect())},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return md}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&=(this.conn.close(),null),this.transport=e}protocol(){return location.protocol.match(/^https/)?`wss`:`ws`}endPointURL(){let e=fd.appendParams(fd.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)===`/`?e.charAt(1)===`/`?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`:e}disconnect(e,t,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,n)}connect(e){e&&(console&&console.log(`passing params to connect is deprecated. Instead pass :params to the Socket constructor`),this.params=Yu(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==md?this.connectWithF
vendor: 4,271 bytes, line 10
10allback(md,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:t});let r=this.onMessage(i=>{i.ref===t&&(this.off([r]),e(Date.now()-n))});return!0}transportName(e){switch(e){case md:return`LongPoll`;default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=[`phoenix`,`${cd}${btoa(this.authToken).replace(/=/g,``)}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let n=!1,r=!0,i,a,o=this.transportName(e),s=t=>{this.log(`transport`,`falling back to ${o}...`,t),this.off([i,a]),r=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return s(`memorized`);this.fallbackTimer=setTimeout(s,t),a=this.onError(e=>{this.log(`transport`,`error`,e),r&&!n&&(clearTimeout(this.fallbackTimer),s(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!r){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,`true`),this.log(`transport`,`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(s,t),this.ping(e=>{this.log(`transport`,`connected to primary after`,e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log(`transport`,`${this.transportName(this.transport)} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,e])=>e())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),rd,`heartbeat timeout`))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,n){if(!this.conn)return e&&e();let r=this.conn;this.waitForBufferDone(r,()=>{t?r.close(t,n||``):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,n=1){if(n===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){if(n===5||e.readyState===ed.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{});let t=e&&e.code;this.hasLogger()&&this.log(`transport`,`close`,e),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&t!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(e))}onConnError(e){this.hasLogger()&&this.log(`transport`,`error`,e);let t=this.transport,n=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,r])=>{r(e,t,n)}),(t===this.transport||n>0)&&this.triggerChanError()}
10triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(ad.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case ed.connecting:return`connecting`;case ed.open:return`open`;case ed.closing:return`closing`;default:return`closed`}}isConnected(){return this.connectionState()===`open`}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>e.indexOf(t)===-1)}channel(e,t={}){let n=new dd(e,t,this);return this.channels.push(n),n}push(e){if(this.hasLogger()){let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;this.log(`push`,`${t} ${n} (${a}, ${i})`,r)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return this.ref=e===this.ref?0:e,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;i&&i===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log(`receive`,`${r.status||``} ${t} ${n} ${i&&`(`+i+`)`||``}`,r);for(let e=0;e<this.channels.length;e++){let o=this.channels[e];o.isMember(t,n,r,a)&&o.trigger(n,r,i,a)}for(let t=0;t<this.stateChangeCallbacks.message.length;t++){let[,n]=this.stateChangeCallbacks.message[t];n(e)}})}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log(`transport`,`leaving duplicate topic "${e}"`),t.leave())}},_d=Symbol(`Let zodToJsonSchema decide on which parser to use`),vd={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},yd=e=>typeof e==`string`?{...vd,name:e}:{...vd,...e},bd=e=>{let t=yd(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function xd(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Sd(e,t,n,r,i){e[t]=n,xd(e,t,r,i)}var Cd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},H;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(H||={});var wd;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(wd||={});var U=H.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Td=e=>{switch(typeof e){case`undefined`:return U.undefined;
10case`string`:return U.string;case`number`:return Number.isNaN(e)?U.nan:U.number;case`boolean`:return U.boolean;case`function`:return U.function;case`bigint`:return U.bigint;case`symbol`:return U.symbol;case`object`:return Array.isArray(e)?U.array:e===null?U.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?U.promise:typeof Map<`u`&&e instanceof Map?U.map:typeof Set<`u`&&e instanceof Set?U.set:typeof Date<`u`&&e instanceof Date?U.date:U.object;default:return U.unknown}},W=H.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`]),Ed=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ed.create=e=>new Ed(e);var Dd=(e,t)=>{let n;switch(e.code){case W.invalid_type:n=e.received===U.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case W.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,H.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:n=`Unrecognized key(s) in object: ${H.joinValues(e.keys,`, `)}`;break;case W.invalid_union:n=`Invalid input`;break;case W.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${H.joinValues(e.options)}`;break;case W.invalid_enum_value:n=`Invalid enum value. Expected ${H.joinValues(e.options)}, received '${e.received}'`;break;case W.invalid_arguments:n=`Invalid function arguments`;break;case W.invalid_return_type:n=`Invalid function return type`;break;case W.invalid_date:n=`Invalid date`;break;case W.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:H.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case W.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case W.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case W.custom:n=`Invalid input`;break;case W.invalid_intersection_types:n=`Intersection results could not be merged`;break;case W.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case W.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,H.assertNever(e)}return{message:n}},Od=Dd;function kd(){return Od}var Ad=e=>
vendor: 6,954 bytes, line 10
10{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function G(e,t){let n=kd(),r=Ad({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Dd?void 0:Dd].filter(e=>!!e)});e.common.issues.push(r)}var jd=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return K;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return K;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},K=Object.freeze({status:`aborted`}),Md=e=>({status:`dirty`,value:e}),Nd=e=>({status:`valid`,value:e}),Pd=e=>e.status===`aborted`,Fd=e=>e.status===`dirty`,Id=e=>e.status===`valid`,Ld=e=>typeof Promise<`u`&&e instanceof Promise,q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(q||={});var Rd=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},zd=(e,t)=>{if(Id(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Ed(e.common.issues);return this._error=t,this._error}}};function J(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var Y=class{get description(){return this._def.description}_getType(e){return Td(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Td(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new jd,ctx:{common:e.parent.common,data:e.data,parsedType:Td(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ld(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Td(e)};return zd(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Td(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Id(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Id(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Td(e)},r=this._parse({data:e,path:n.path,parent:n});return zd(n,await(Ld(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:W.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Uf({schema:this,typeName:X.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:e=>this[`~validate`](e)}}optional(){return Wf.create(this,this._def)}nullable(){return Gf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wf.create(this)}promise(){return Hf.create(this,this._def)}or(e){return Df.create([this,e],this._def)}and(e){return jf.create(this,e,this._def)}transform(e){return new Uf({...J(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Kf({...J(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new Yf({typeName:X.ZodBranded,type:this,...J(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new qf({...J(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xf.create(this,e)}readonly(){return Zf.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Bd=/^c[^\s-]{8,}
vendor: 20,014 bytes, line 10
10$/i,Vd=/^[0-9a-z]+$/,Hd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ud=/^[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,Wd=/^[a-z0-9_-]{21}$/i,Gd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Kd=/^[-+]?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)?)??$/,qd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Jd=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,Yd,Xd=/^(?:(?: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])$/,Zd=/^(?:(?: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])$/,Qd=/^(([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]))$/,$d=/^(([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])$/,ef=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nf=`((\\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])))`,rf=RegExp(`^${nf}$`);function af(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function of(e){return RegExp(`^${af(e)}$`)}function sf(e){let t=`${nf}T${af(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function cf(e,t){return!!((t===`v4`||!t)&&Xd.test(e)||(t===`v6`||!t)&&Qd.test(e))}function lf(e,t){if(!Gd.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function uf(e,t){return!!((t===`v4`||!t)&&Zd.test(e)||(t===`v6`||!t)&&$d.test(e))}var df=class e extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.string,received:t.parsedType}),K}let t=new jd,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)qd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`email`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Yd||=new RegExp(Jd,`u`),Yd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`emoji`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Ud.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`uuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Wd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`nanoid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Bd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Vd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid2`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Hd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ulid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),G(n,{validation:`url`,code:W.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`regex`,code:W.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?sf(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?rf.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?of(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Kd.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`duration`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?cf(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ip`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?lf(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`jwt`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?uf(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cidr`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?ef.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?tf.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64url`,code:W.invalid_string,message:r.message}),t.dirty()):H.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:W.invalid_string,...q.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...q.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:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...q.errToObj(t)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...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(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};df.create=e=>new df({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...J(e)});function ff(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var pf=class e extends Y{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)!==U.number){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.number,received:t.parsedType}),K}let t,n=new jd;for(let r of this._def.checks)r.kind===`int`?H.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?ff(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_finite,message:r.message}),n.dirty()):H.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:q.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let 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`&&H.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};pf.create=e=>new pf({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...J(e)});var mf=class e extends Y{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)!==U.bigint)return this._getInvalidInput(e);let t,n=new jd;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):H.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.bigint,received:t.parsedType}),K}gte(e,t){return this.setLimit(`min`,e,!0,q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:q.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};mf.create=e=>new mf({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...J(e)});var hf=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.boolean,received:t.parsedType}),K}return Nd(e.data)}};hf.create=e=>new hf({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...J(e)});var gf=class e extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.date,received:t.parsedType}),K}if(Number.isNaN(e.data.getTime()))return G(this._getOrReturnCtx(e),{code:W.invalid_date}),K;let t=new jd,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):H.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:q.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};gf.create=e=>new gf({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...J(e)});var _f=class extends Y{_parse(e){if(this._getType(e)!==U.symbol){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.symbol,received:t.parsedType}),K}return Nd(e.data)}};_f.create=e=>new _f({typeName:X.ZodSymbol,...J(e)});var vf=class extends Y{_parse(e){if(this._getType(e)!==U.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.undefined,received:t.parsedType}),K}return Nd(e.data)}};vf.create=e=>new vf({typeName:X.ZodUndefined,...J(e)});var yf=class extends Y{_parse(e){if(this._getType(e)!==U.null){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.null,received:t.parsedType}),K}return Nd(e.data)}};yf.create=e=>new yf({typeName:X.ZodNull,...J(e)});var bf=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return Nd(e.data)}};bf.create=e=>new bf({typeName:X.ZodAny,...J(e)});var xf=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Nd(e.data)}};xf.create=e=>new xf({typeName:X.ZodUnknown,...J(e)});var Sf=class extends Y{_parse(e){let t=this._getOrReturnCtx(e);
vendor: 19,564 bytes, line 10
10return G(t,{code:W.invalid_type,expected:U.never,received:t.parsedType}),K}};Sf.create=e=>new Sf({typeName:X.ZodNever,...J(e)});var Cf=class extends Y{_parse(e){if(this._getType(e)!==U.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.void,received:t.parsedType}),K}return Nd(e.data)}};Cf.create=e=>new Cf({typeName:X.ZodVoid,...J(e)});var wf=class e extends Y{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return G(t,{code:W.invalid_type,expected:U.array,received:t.parsedType}),K;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(G(t,{code:e?W.too_big:W.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(G(t,{code:W.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(G(t,{code:W.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Rd(t,e,t.path,n)))).then(e=>jd.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Rd(t,e,t.path,n)));return jd.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:q.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:q.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:q.toString(n)}})}nonempty(e){return this.min(1,e)}};wf.create=(e,t)=>new wf({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...J(t)});function Tf(e){if(e instanceof Ef){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Wf.create(Tf(r))}return new Ef({...e._def,shape:()=>t})}return e instanceof wf?new wf({...e._def,type:Tf(e.element)}):e instanceof Wf?Wf.create(Tf(e.unwrap())):e instanceof Gf?Gf.create(Tf(e.unwrap())):e instanceof Mf?Mf.create(e.items.map(e=>Tf(e))):e}var Ef=class e extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=H.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==U.object){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.object,received:t.parsedType}),K}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Sf&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Rd(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Sf){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(G(n,{code:W.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Rd(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>jd.mergeObjectSync(t,e)):jd.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return q.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:q.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of H.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of H.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Tf(this)}partial(t){let n={};for(let e of H.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of H.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Wf;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return zf(H.objectKeys(this.shape))}};Ef.create=(e,t)=>new Ef({shape:()=>e,unknownKeys:`strip`,catchall:Sf.create(),typeName:X.ZodObject,...J(t)}),Ef.strictCreate=(e,t)=>new Ef({shape:()=>e,unknownKeys:`strict`,catchall:Sf.create(),typeName:X.ZodObject,...J(t)}),Ef.lazycreate=(e,t)=>new Ef({shape:e,unknownKeys:`strip`,catchall:Sf.create(),typeName:X.ZodObject,...J(t)});var Df=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Ed(e.ctx.common.issues));return G(t,{code:W.invalid_union,unionErrors:n}),K}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Ed(e));return G(t,{code:W.invalid_union,unionErrors:i}),K}}get options(){return this._def.options}};Df.create=(e,t)=>new Df({options:e,typeName:X.ZodUnion,...J(t)});var Of=e=>e instanceof Lf?Of(e.schema):e instanceof Uf?Of(e.innerType()):e instanceof Rf?[e.value]:e instanceof Bf?e.options:e instanceof Vf?H.objectValues(e.enum):e instanceof Kf?Of(e._def.innerType):e instanceof vf?[void 0]:e instanceof yf?[null]:e instanceof Wf?[void 0,...Of(e.unwrap())]:e instanceof Gf?[null,...Of(e.unwrap())]:e instanceof Yf||e instanceof Zf?Of(e.unwrap()):e instanceof qf?Of(e._def.innerType):[],kf=class e extends Y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.object)return G(t,{code:W.invalid_type,expected:U.object,received:t.parsedType}),K;let n=this.discriminator,r=t.data[n],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}):(G(t,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Of(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...J(r)})}};function Af(e,t){let n=Td(e),r=Td(t);if(e===t)return{valid:!0,data:e};if(n===U.object&&r===U.object){let n=H.objectKeys(t),r=H.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Af(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===U.array&&r===U.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Af(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===U.date&&r===U.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var jf=class extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Pd(e)||Pd(r))return K;let i=Af(e.value,r.value);return i.valid?((Fd(e)||Fd(r))&&t.dirty(),{status:t.value,value:i.data}):(G(n,{code:W.invalid_intersection_types}),K)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};jf.create=(e,t,n)=>new jf({left:e,right:t,typeName:X.ZodIntersection,...J(n)});var Mf=class e extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.array)return G(n,{code:W.invalid_type,expected:U.array,received:n.parsedType}),K;if(n.data.length<this._def.items.length)return G(n,{code:W.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),K;!this._def.rest&&n.data.length>this._def.items.length&&(G(n,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Rd(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>jd.mergeArray(t,e)):jd.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Mf.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Mf({items:e,typeName:X.ZodTuple,rest:null,...J(t)})};var Nf=class e extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.object)return G(n,{code:W.invalid_type,expected:U.object,received:n.parsedType}),K;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Rd(n,e,n.path,e)),value:a._parse(new Rd(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?jd.mergeObjectAsync(t,r):jd.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Y?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...J(r)}):new e({keyType:df.create(),valueType:t,typeName:X.ZodRecord,...J(n)})}},Pf=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.map)return G(n,{code:W.invalid_type,expected:U.map,received:n.parsedType}),K;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Rd(n,e,n.path,[a,`key`])),value:i._parse(new Rd(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return K;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return K;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Pf.create=(e,t,n)=>new Pf({valueType:t,keyType:e,typeName:X.ZodMap,...J(n)});var Ff=class e extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.set)return G(n,{code:W.invalid_type,expected:U.set,received:n.parsedType}),K;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(G(n,{code:W.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(G(n,{code:W.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return K;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Rd(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:q.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:q.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ff.create=(e,t)=>new Ff({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...J(t)});var If=class e extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.function)return G(t,{code:W.invalid_type,expected:U.function,received:t.parsedType}),K;function n(e,n){return Ad({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kd(),Dd].filter(e=>!!e),issueData:{code:W.invalid_arguments,argumentsError:n}})}function r(e,n){return Ad({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kd(),Dd].filter(e=>!!e),issueData:{code:W.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Hf){let e=this;return Nd(async function(...t){let o=new Ed([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return Nd(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Ed([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Ed([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Mf.create(t).rest(xf.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Mf.create([]).rest(xf.create()),returns:n||xf.create(),typeName:X.ZodFunction,...J(r)})}},Lf=class extends Y{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Lf.create=(e,t)=>new Lf({getter:e,typeName:X.ZodLazy,...J(t)});var Rf=class extends Y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:W.invalid_literal,expected:this._def.value}),K}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Rf.create=(e,t)=>new Rf({value:e,typeName:X.ZodLiteral,...J(t)});function zf(e,t){return new Bf({values:e,typeName:X.ZodEnum,...J(t)})}var Bf=class e extends Y{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{expected:H.joinValues(n),received:t.parsedType,code:W.invalid_type}),K}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{received:t.data,code:W.invalid_enum_value,options:n}),K}return Nd(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Bf.create=zf;var Vf=class extends Y{_parse(e){let t=H.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==U.string&&n.parsedType!==U.number){let e=H.objectValues(t);return G(n,{expected:H.joinValues(e),received:n.parsedType,code:W.invalid_type}),K}if(this._cache||=new Set(H.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=H.objectValues(t);return G(n,{received:n.data,code:W.invalid_enum_value,options:e}),K}return Nd(e.data)}get enum(){return this._def.values}};Vf.create=(e,t)=>new Vf({values:e,typeName:X.ZodNativeEnum,...J(t)});var Hf=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==U.promise&&t.common.async===!1?(G(t,{code:W.invalid_type,expected:U.promise,received:t.parsedType}),K):Nd((t.parsedType===U.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Hf.create=(e,t)=>new Hf({type:e,typeName:X.ZodPromise,...J(t)});var Uf=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{G(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return K;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?K:r.status===`dirty`||t.value===`dirty`?Md(r.value):r});{if(t.value===`aborted`)return K;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?K:r.status===`dirty`||t.value===`dirty`?Md(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?K:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?K:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Id(e))return K;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Id(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):K)}H.assertNever(r)}};Uf.create=(e,t,n)=>new Uf({schema:e,typeName:X.ZodEffects,effect:t,...J(n)}),Uf.createWithPreprocess=(e,t,n)=>new Uf({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...J(n)});var Wf=class extends Y{_parse(e){return this._getType(e)===U.undefined?Nd(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Wf.create=(e,t)=>
10new Wf({innerType:e,typeName:X.ZodOptional,...J(t)});var Gf=class extends Y{_parse(e){return this._getType(e)===U.null?Nd(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Gf.create=(e,t)=>new Gf({innerType:e,typeName:X.ZodNullable,...J(t)});var Kf=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===U.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Kf.create=(e,t)=>new Kf({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...J(t)});var qf=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ld(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Ed(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Ed(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};qf.create=(e,t)=>new qf({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...J(t)});var Jf=class extends Y{_parse(e){if(this._getType(e)!==U.nan){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.nan,received:t.parsedType}),K}return{status:`valid`,value:e.data}}};Jf.create=e=>new Jf({typeName:X.ZodNaN,...J(e)});var Yf=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Xf=class e extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?K:e.status===`dirty`?(t.dirty(),Md(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?K:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},Zf=class extends Y{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Id(e)&&(e.value=Object.freeze(e.value)),e);return Ld(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Zf.create=(e,t)=>new Zf({innerType:e,typeName:X.ZodReadonly,...J(t)}),Ef.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),df.create,pf.create,Jf.create,mf.create,hf.create,gf.create,_f.create,vf.create,yf.create,bf.create,xf.create,Sf.create,Cf.create,wf.create,Ef.create,Ef.strictCreate,Df.create,kf.create,jf.create,Mf.create,Nf.create,Pf.create,Ff.create,If.create,Lf.create,Rf.create,Bf.create,Vf.create,Hf.create,Uf.create,Wf.create,Gf.create,Uf.createWithPreprocess,Xf.create;function Qf(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Cd(t,e.currentPath):t.join(`/`)}}function $f(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=Z(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&Sd(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&Sd(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Sd(n,`minItems`,e.exactLength.value,e.exactLength.message,t),Sd(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function ep(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?Sd(n,`minimum`,r.value,r.message,t):Sd(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Sd(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Sd(n,`maximum`,r.value,r.message,t):Sd(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Sd(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Sd(n,`multipleOf`,r.value,r.message,t)}return n}function tp(){return{type:`boolean`}}function np(e,t){return Z(e.type._def,t)}var rp=(e,t)=>Z(e.innerType._def,t);
10function ip(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>ip(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return ap(e,t)}}var ap=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:Sd(n,`minimum`,r.value,r.message,t);break;case`max`:Sd(n,`maximum`,r.value,r.message,t)}return n};function op(e,t){return{...Z(e.innerType._def,t),default:e.defaultValue()}}function sp(e,t){return t.effectStrategy===`input`?Z(e.schema._def,t):Qf(t)}function cp(e){return{type:`string`,enum:Array.from(e.values)}}var lp=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function up(e,t){let n=[Z(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Z(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(lp(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function dp(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var fp=void 0,pp={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:()=>(fp===void 0&&(fp=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),fp),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function mp(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:Sd(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:Sd(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:vp(n,`email`,r.message,t);break;case`format:idn-email`:vp(n,`idn-email`,r.message,t);break;case`pattern:zod`:yp(n,pp.email,r.message,t)}break;case`url`:vp(n,`uri`,r.message,t);break;case`uuid`:vp(n,`uuid`,r.message,t);break;case`regex`:yp(n,r.regex,r.message,t);break;case`cuid`:yp(n,pp.cuid,r.message,t);break;case`cuid2`:yp(n,pp.cuid2,r.message,t);break;case`startsWith`:yp(n,RegExp(`^${hp(r.value,t)}`),r.message,t);break;case`endsWith`:yp(n,RegExp(`${hp(r.value,t)}$`),r.message,t);break;case`datetime`:vp(n,`date-time`,r.message,t);break;case`date`:vp(n,`date`,r.message,t);break;case`time`:vp(n,`time`,r.message,t);break;case`duration`:vp(n,`duration`,r.message,t);break;case`length`:Sd(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),Sd(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:yp(n,RegExp(hp(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&vp(n,`ipv4`,r.message,t),r.version!==`v4`&&vp(n,`ipv6`,r.message,t);break;case`base64url`:yp(n,pp.base64url,r.message,t);break;case`jwt`:yp(n,pp.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&yp(n,pp.ipv4Cidr,r.message,t),r.version!==`v4`&&yp(n,pp.ipv6Cidr,r.message,t);break;case`emoji`:yp(n,pp.emoji(),r.message,t);break;case`ulid`:yp(n,pp.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:vp(n,`binary`,r.message,t);break;case`contentEncoding:base64`:Sd(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:yp(n,pp.base64,r.message,t)}break;case`nanoid`:yp(n,pp.nanoid,r.message,t)}return n}function hp(e,t){return t.patternStrategy===`escape`?_p(e):e}var gp=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function _p(e){let t=``;for(let n=0;n<e.length;
10n++)gp.has(e[n])||(t+=`\\`),t+=e[n];return t}function vp(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Sd(e,`format`,t,n,r)}function yp(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:bp(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Sd(e,`pattern`,bp(t,r),n,r)}function bp(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
11]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
12]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function xp(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Qf(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=mp(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=np(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Sp(e,t){return t.mapStrategy===`record`?xp(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Z(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Qf(t),Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Qf(t)],minItems:2,maxItems:2}}}function Cp(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function wp(e){return e.target===`openAi`?void 0:{not:Qf({...e,currentPath:[...e.currentPath,`not`]})}}function Tp(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var Ep={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Dp(e,t){if(t.target===`openApi3`)return Op(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Ep&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Ep[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>
12{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Op(e,t)}var Op=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function kp(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Ep[e.innerType._def.typeName],nullable:!0}:{type:[Ep[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Ap(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,xd(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?Sd(n,`minimum`,r.value,r.message,t):Sd(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Sd(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Sd(n,`maximum`,r.value,r.message,t):Sd(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Sd(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Sd(n,`multipleOf`,r.value,r.message,t)}return n}function jp(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Np(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Z(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Mp(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Mp(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Z(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Np(e){try{return e.isOptional()}catch{return!0}}var Pp=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Z(e.innerType._def,t);let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Qf(t)},n]}:Qf(t)},Fp=(e,t)=>{if(t.pipeStrategy===`input`)return Z(e.in._def,t);if(t.pipeStrategy===`output`)return Z(e.out._def,t);let n=Z(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Z(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Ip(e,t){return Z(e.type._def,t)}function Lp(e,t){let n={type:`array`,uniqueItems:!0,items:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&Sd(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&Sd(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Rp(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Z(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>
12t===void 0?e:[...e,t],[])}}function zp(e){return{not:Qf(e)}}function Bp(e){return Qf(e)}var Vp=(e,t)=>Z(e.innerType._def,t),Hp=(e,t,n)=>{switch(t){case X.ZodString:return mp(e,n);case X.ZodNumber:return Ap(e,n);case X.ZodObject:return jp(e,n);case X.ZodBigInt:return ep(e,n);case X.ZodBoolean:return tp();case X.ZodDate:return ip(e,n);case X.ZodUndefined:return zp(n);case X.ZodNull:return Tp(n);case X.ZodArray:return $f(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return Dp(e,n);case X.ZodIntersection:return up(e,n);case X.ZodTuple:return Rp(e,n);case X.ZodRecord:return xp(e,n);case X.ZodLiteral:return dp(e,n);case X.ZodEnum:return cp(e);case X.ZodNativeEnum:return Cp(e);case X.ZodNullable:return kp(e,n);case X.ZodOptional:return Pp(e,n);case X.ZodMap:return Sp(e,n);case X.ZodSet:return Lp(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return Ip(e,n);case X.ZodNaN:case X.ZodNever:return wp(n);case X.ZodEffects:return sp(e,n);case X.ZodAny:return Qf(n);case X.ZodUnknown:return Bp(n);case X.ZodDefault:return op(e,n);case X.ZodBranded:return np(e,n);case X.ZodReadonly:return Vp(e,n);case X.ZodCatch:return rp(e,n);case X.ZodPipeline:return Fp(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function Z(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==_d)return i}if(r&&!n){let e=Up(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Hp(e,e.typeName,t),o=typeof a==`function`?Z(a(),t):a;if(o&&Wp(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Up=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Cd(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Qf(t)):t.$refStrategy===`seen`?Qf(t):void 0}},Wp=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Gp=(e,t)=>{let n=bd(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Z(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Qf(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Z(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Qf(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};async function Kp(e,t,n){let r=e;try{e.isRunning=!0,e.agentId=e.agentId??kl();let i=r.prepareRunAgentInput(t),a,o=new Set(e.messages.map(e=>e.id)),s=[{onRunFinishedEvent:e=>{e.outcome===`success`&&(a=e.result)}},...e.subscribers,n??{}];await r.onInitialize(i,s),r.activeRunDetach$=new ca;let c;r.activeRunCompletionPromise=new Promise(e=>{c=e});
12let l=Bo(()=>r.connect(i)).pipe(eu(r.debugLogger),fs(r.activeRunDetach$)),u=r.apply(i,l,s);await go(r.processApplyEvents(i,u,s).pipe(Go(t=>(e.isRunning=!1,t instanceof Dn?Aa:r.onError(i,t,s))),os(()=>{e.isRunning=!1,r.onFinalize(i,s),c?.(),c=void 0,r.activeRunCompletionPromise=void 0,r.activeRunDetach$=void 0})),{defaultValue:void 0});let d=B(e.messages).filter(e=>!o.has(e.id));return{result:a,newMessages:d}}finally{e.isRunning=!1}}function qp(e){return new $i(t=>{e.onOpen(()=>t.next({type:`open`})),e.onError(e=>t.next({type:`error`,error:e}))})}function Jp(e){return new $i(t=>{e.join().receive(`ok`,()=>{t.next({type:`joined`}),t.complete()}).receive(`error`,e=>{t.next({type:`error`,response:e}),t.complete()}).receive(`timeout`,()=>{t.next({type:`timeout`}),t.complete()})})}function Yp(e){return Bo(()=>{let t=new gd(e.url,e.options),n=qp(t).pipe(us({bufferSize:1,refCount:!0}));return t.connect(),zo(N({socket:t,signals$:n}),Uo).pipe(os(()=>t.disconnect()))})}function Xp(e){return e.socket$.pipe(ds(({socket:t})=>Bo(()=>{let n=t.channel(e.topic,e.params);return zo(N({channel:n,joinOutcome$:Jp(n).pipe(us({bufferSize:1,refCount:!0}))}),Uo).pipe(os(()=>{e.leaveOnUnsubscribe!==!1&&n.leave()}))})))}function Zp(e,t){return new $i(n=>{let r=e.on(t,e=>n.next(e));return()=>{e.off(t,r)}})}function Qp(e){return e.pipe(ds(e=>e.joinOutcome$))}function $p(e){return Qp(e).pipe(Zo(1),Io(e=>{if(e.type===`joined`)return Aa;throw e.type===`timeout`?Error(`Timed out joining channel`):Error(`Failed to join channel: ${JSON.stringify(e.response)}`)}))}function em(e){return e.pipe(ds(e=>e.signals$))}function tm(e,t){return e.pipe(ss((e,t)=>t.type===`open`?0:e+1,0),Wo(e=>e>=t),Zo(1),Io(e=>P(()=>Error(`WebSocket connection failed after ${e} consecutive errors`))))}var nm=(...e)=>fetch(...e),rm=`ag_ui_event`,im=`replay_complete`,am=`stream_idle`,om=`stop_run`,sm=100,cm=class extends Error{constructor(e){super(e?`Thread ${e} is locked`:`Thread is locked`),this.name=`AgentThreadLockedError`}};function lm(e){return typeof e==`object`&&!!e&&`activeRunCompletionPromise`in e}var um=class e extends wu{config;socket=null;activeChannel=null;canonicalRunId=null;sharedState;constructor(e,t={lastSeenEventIds:new Map}){super(),this.config=e,this.sharedState=t}get headers(){return this.config.headers}set headers(e){this.config={...this.config,headers:e}}get credentials(){return this.config.credentials}set credentials(e){this.config={...this.config,credentials:e}}clone(){return new e(this.config,this.sharedState)}async connectAgent(e,t){let n=e?.runId||!this.canonicalRunId?e:{...e,runId:this.canonicalRunId};return Kp(this,n,t)}abortRun(){if(this.activeChannel&&this.canonicalRunId){let e=setTimeout(()=>t(),5e3),t=()=>{clearTimeout(e),this.detachActiveRun(),this.cleanup()};this.activeChannel.push(om,{run_id:this.canonicalRunId}).receive(`ok`,t).receive(`error`,t).receive(`timeout`,t)}else this.detachActiveRun(),this.cleanup()}run(e){return this.threadId=e.threadId,this.canonicalRunId=e.runId,Bo(()=>this.requestJoinCredentials$(`run`,e)).pipe(ds(t=>{if(t===null)return P(()=>Error(`REST run request returned no credentials`));let n=this.applyCanonicalRunIdentity(e,t,{fallbackToInputRunId:!0});return this.observeThread$(n,t,{completeOnRunError:!1,streamMode:`run`})}))}connect(e){this.threadId=e.threadId,this.canonicalRunId=null;let t=this.getReconnectCursor(e);return Bo(()=>this.requestJoinCredentials$(`connect`,e,t)).pipe(ds(n=>{if(n===null)return Aa;let r=this.applyCanonicalRunIdentity(e,n,{fallbackToInputRunId:!1});return this.observeThread$(r,n,{completeOnRunError:!1,streamMode:`connect`,replayCursor:t})}))}cleanupOwned(e,t){e&&(e.leave(),this.activeChannel===e&&(this.activeChannel=null)),t&&(t.disconnect(),this.socket===t&&(this.socket=null)),this.canonicalRunId=null}cleanup(){this.cleanupOwned(this.activeChannel,this.socket)}requestJoinCredentials$(e,t,n){return Bo(async()=>{try{let r=await(this.config.fetch??nm)(this.buildRuntimeUrl(e),{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers},body:JSON.stringify({...t,...e===`connect`?{lastSeenEventId:n===void 0?this.getReconnectCursor(t):n}:{}}),...this.credentials?{credentials:this.credentials}:{}});if(r.status===204&&e===`connect`)return null;if(r.status===409&&e===`run`)throw new cm(t.threadId);if(!r.ok){let e=await r.text().catch(()=>``);throw Error(e||r.statusText||String(r.status))}return this.normalizeJoinCredentials(await r.json(),t)}catch(t){throw t instanceof cm?t:Error(`REST ${e} request failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}})}normalizeJoinCredentials(e,t){let n=e&&typeof e==`object`?e:null,r=n?.realtime&&typeof n.realtime==`object`?n.realtime:null;if(typeof n?.joinToken!=`string`||!n.joinToken)throw Error(`missing joinToken`);if(typeof r?.clientUrl!=`string`||!r.clientUrl)throw Error(`missing realtime.clientUrl`);if(typeof r.topic!=`string`||!r.topic)throw Error(`missing realtime.topic`);return{threadId:typeof n.threadId==`string`&&n.threadId?n.threadId:t.threadId,runId:typeof n.runId==`string`&&n.runId?n.runId:null,joinToken:n.joinToken,realtime:{clientUrl:r.clientUrl,topic:r.topic}}}observeThread$(e,t,n){return this.observeThreadSession$(e,t,n).pipe(Go(t=>{if(!this.isSocketReconnectExhaustedError(t))return P(()=>t);let r=this.getReconnectCursor(e);return this.requestJoinCredentials$(`connect`,e,r).pipe(ds(t=>t===null?Aa:this.observeThread$(this.applyCanonicalRunIdentity(e,t,{fallbackToInputRunId:n.streamMode===`run`}),t,{...n,channelMode:`connect`,replayCursor:r}
12)))}))}observeThreadSession$(e,t,n){return Bo(()=>{let r=null,i=null,a=Yp({url:t.realtime.clientUrl,options:{params:{...this.config.socketParams,join_token:t.joinToken},reconnectAfterMs:Uu(100,1e4),rejoinAfterMs:Uu(1e3,3e4)}}).pipe(ps(({socket:e})=>{r=e,this.socket=r}),us({bufferSize:1,refCount:!0})),o=this.createThreadChannelParams(e,n.channelMode??n.streamMode,n.replayCursor),s=Xp({socket$:a,topic:t.realtime.topic,params:o}).pipe(ps(({channel:e})=>{i=e,this.activeChannel=i}),us({bufferSize:1,refCount:!0})),c=this.readDurableEventId(n.replayCursor??this.getReconnectCursor(e)),l=null,u=this.observeThreadEvents$(e.threadId,s,n).pipe(ps(e=>{l=this.readEventId(e)??l}),cs()),d=this.observeControlEvent$(e.threadId,s,im).pipe(us({bufferSize:1,refCount:!0})),f=this.observeControlEvent$(e.threadId,s,am).pipe(us({bufferSize:1,refCount:!0})),p=n.streamMode===`connect`?Ho(Mo([d.pipe(Zo(1)),f.pipe(Zo(1))]),f.pipe(Zo(1),Wo(e=>this.canFallbackCompleteConnect(e,c,l)),ts(sm))).pipe(Zo(1)):Aa,m=u.pipe(Qo(),as(null),Zo(1)),h=Ho(m,p);return Ho(this.joinThreadChannel$(s),this.observeSocketHealth$(a).pipe(fs(h)),u.pipe(fs(p)),d.pipe(Qo(),fs(h)),p.pipe(Qo(),fs(m))).pipe(os(()=>this.cleanupOwned(i,r)))})}joinThreadChannel$(e){return $p(e)}observeSocketHealth$(e){return tm(em(e),5)}observeThreadEvents$(e,t,n){return t.pipe(ds(({channel:e})=>this.observeChannelEvent$(e,rm)),ps(t=>{this.updateLastSeenEventId(e,t)}),Io(e=>this.createThreadNotifications(e,{completeOnRunError:n.completeOnRunError,completeOnRunFinished:n.streamMode===`run`,errorOnRunError:n.streamMode===`run`})),ns())}observeControlEvent$(e,t,n){return t.pipe(ds(({channel:e})=>this.observeChannelEvent$(e,n)),ps(t=>this.updateLastSeenEventIdFromControl(e,t)))}observeChannelEvent$(e,t){return Zp(e,t)}createThreadNotifications(e,t){if(e.type===j.RUN_FINISHED)return t.completeOnRunFinished?[po.createNext(e),po.createComplete()]:[po.createNext(e)];if(e.type===j.RUN_ERROR){let n=e.message??`Run error`;return t.completeOnRunError?[po.createNext(e),po.createComplete()]:t.errorOnRunError?[po.createNext(e),po.createError(Error(n))]:[po.createNext(e)]}return[po.createNext(e)]}buildRuntimeUrl(e){let t=`${this.config.runtimeUrl}/agent/${encodeURIComponent(this.config.agentId)}/${e}`,n=typeof window<`u`&&window.location?window.location.origin:`http://localhost`;return new URL(t,new URL(this.config.runtimeUrl,n)).toString()}
12createThreadChannelParams(e,t,n){return t===`run`?{stream_mode:`run`,run_id:e.runId}:{stream_mode:`connect`,last_seen_event_id:n===void 0?this.getReconnectCursor(e):n}}getLastSeenEventId(e){return this.sharedState.lastSeenEventIds.get(e)??null}getReconnectCursor(e){return this.getLastSeenEventId(e.threadId)}clearReconnectCursor(e){this.sharedState.lastSeenEventIds.delete(e)}updateLastSeenEventId(e,t){let n=this.readEventId(t);n&&this.advanceLastSeenEventId(e,n)}updateLastSeenEventIdFromControl(e,t){let n=this.readControlEventId(t);n&&this.advanceLastSeenEventId(e,n)}advanceLastSeenEventId(e,t){this.sharedState.lastSeenEventIds.set(e,t)}readEventId(e){let t=e.metadata;if(!t||typeof t!=`object`)return null;let n=t;return this.readDurableEventId(n.cpki_event_id)}readControlEventId(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.latestEventId??t.latest_event_id;return this.readDurableEventId(n)}readDurableEventId(e){return typeof e!=`string`||e.trim()===``||e.startsWith(`cpki_ingested`)?null:e}canFallbackCompleteConnect(e,t,n){let r=this.readControlEventId(e);return!r||r===t||r===n}applyCanonicalRunIdentity(e,t,n){this.threadId=t.threadId;let r=t.runId??(n.fallbackToInputRunId?e.runId:null);return this.canonicalRunId=r,{...e,threadId:t.threadId,...r===null?{}:{runId:r}}}isSocketReconnectExhaustedError(e){return e instanceof Error&&e.message.includes(`WebSocket connection failed after`)}};async function dm(e){let t=`Runtime info request failed with status ${e.status}`,n;try{let t=(await e.clone().json())?.message;typeof t==`string`&&t.trim().length>0&&(n=t.trim())}catch{}let r=Error(n?`${t}: ${n}`:t);return r.runtimeInfoStatus=e.status,r}function fm(e){return typeof e==`object`&&!!e&&typeof e.runtimeInfoStatus==`number`}function pm(e){return`headers`in e}function mm(e){return`credentials`in e}function hm(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`}function gm(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}function _m(e){return e.pipe(Go(e=>{if(hm(e)||gm(e))return Aa;throw e}))}var vm=class e extends Eu{runtimeUrl;credentials;runtimeAgentId;transport;singleEndpointUrl;runtimeMode;intelligence;_capabilities;delegate;runtimeInfoPromise;constructor(e){let t=e.runtimeUrl?e.runtimeUrl.replace(/\/$/,``):void 0,n=e.transport??`auto`,r=e.runtimeAgentId??e.agentId??``,i=n===`single`?t??e.runtimeUrl??``:`${t??e.runtimeUrl}/agent/${encodeURIComponent(r)}/run`;if(!i)throw Error(`ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.`);super({...e,url:i}),this.runtimeUrl=t??e.runtimeUrl,this.credentials=e.credentials,this.runtimeAgentId=e.runtimeAgentId,this.transport=n,this.runtimeMode=e.runtimeMode??`sse`,this.intelligence=e.intelligence,this._capabilities=e.capabilities,e.debug&&(this.debug=e.debug),this.transport===`single`&&(this.singleEndpointUrl=this.runtimeUrl)}routedAgentId(){let e=this.runtimeAgentId??this.agentId;if(!e)throw Error(`ProxiedCopilotRuntimeAgent: cannot make a runtime request without an agentId or runtimeAgentId.`);return e}get capabilities(){return this._capabilities}requestInit(e){return{...super.requestInit(e),...this.credentials?{credentials:this.credentials}:{}}}async getCapabilities(){return this._capabilities??{}}async detachActiveRun(){this.delegate&&await this.delegate.detachActiveRun(),await super.detachActiveRun()}abortRun(){if(this.delegate){this.syncDelegate(this.delegate),this.delegate.abortRun(),this.detachActiveRun();return}if(!this.agentId||!this.threadId||typeof fetch>`u`)return;let e=this.routedAgentId();if(this.transport===`single`){if(!this.singleEndpointUrl)return;let t=new Headers({...this.headers,"Content-Type":`application/json`});fetch(this.singleEndpointUrl,{method:`POST`,headers:t,body:JSON.stringify({method:`agent/stop`,params:{agentId:e,threadId:this.threadId}}),...this.credentials?{credentials:this.credentials}:{}}).catch(e=>{console.error(`ProxiedCopilotRuntimeAgent: stop request failed`,e)});return}if(!this.runtimeUrl)return;let t=`${this.runtimeUrl}/agent/${encodeURIComponent(e)}/stop/${encodeURIComponent(this.threadId)}`,n=typeof window<`u`&&window.location?window.location.origin:`http://localhost`,r=new URL(this.runtimeUrl,n),i=new URL(t,r);fetch(i.toString(),{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers},...this.credentials?{credentials:this.credentials}:{}}).catch(e=>{console.error(`ProxiedCopilotRuntimeAgent: stop request failed`,e)})}async connectAgent(e,t){if(this.runtimeMode!==`intelligence`)return Kp(this,e,t);this.delegate&&await this.delegate.detachActiveRun(),await this.resolveDelegate();let n=this.delegate,r=n.subscribe({onMessagesChanged:()=>{this.setMessages([...n.messages])},onStateChanged:()=>{this.setState({...n.state})},onRunInitialized:()=>{this.isRunning=!0},onRunFinalized:()=>{this.isRunning=!1},onRunFailed:()=>{this.isRunning=!1},onRunErrorEvent:()=>{this.isRunning=!1}}),i=this.subscribers.map(e=>n.subscribe(e));try{let r=await n.connectAgent(e,t);return this.setMessages([...n.messages]),this.setState({...n.state}),r}finally{this.isRunning=!1,r.unsubscribe();for(let e of i)e.unsubscribe()}}connect(e){return this.runtimeMode===`pending`||this.transport===`auto`&&this.runtimeMode!==`intelligence`?Bo(()=>uo(this.ensureRuntimeConfiguration())).pipe(ds(()=>this.connect(e))):this.runtimeMode===`intelligence`?this.#e(e):this.#t(e)}run(e){return this.runtimeMode===`pending`||this.transport===`auto`&&this.runtimeMode!==`intelligence`?Bo(()=>uo(this.ensureRuntimeConfiguration())).pipe(ds(()=>this.run(e))):this.runtimeMode===`intelligence`?this.#n(e):this.#r(e)}#e(e){return Bo(()=>uo(this.resolveDelegate())).pipe(ds(t=>_m(t.connect(e))))}#t(e){let t=this.routedAgentId();if(this.transport===`single`){if(!this.singleEndpointUrl)throw Error(`Single endpoint transport requires a runtimeUrl`);let n=this.createSingleRouteRequestInit(e,`agent/connect`,{agentId:t});return _m(Gl(Hl(()=>this.fetch(this.singleEndpointUrl,n))))}let n=`${this.runtimeUrl}/agent/${t}/connect`,r=this.requestInit(e);return _m(Gl(Hl(()=>this.fetch(n,r))))}#n(e){return Bo(()=>uo(this.resolveDelegate())).pipe(ds(t=>_m(t.run(e))))}#r(e){if(this.transport===`single`){if(!this.singleEndpointUrl)throw Error(`Single endpoint transport requires a runtimeUrl`);let t=this.createSingleRouteRequestInit(e,`agent/run`,{agentId:this.routedAgentId()});return _m(Gl(Hl(()=>this.fetch(this.singleEndpointUrl,t))))}return _m(super.run(e))}clone(){let t=new e({runtimeUrl:this.runtimeUrl,agentId:this.agentId,runtimeAgentId:this.runtimeAgentId,description:this.description,headers:{...this.headers},credentials:this.credentials,transport:this.transport,runtimeMode:this.runtimeMode,intelligence:this.intelligence,capabilities:this._capabilities,debug:this.debug,fetch:this.fetch});if(t.threadId=this.threadId,t.setState(this.state),t.setMessages(this.messages),this.delegate){let e=this.delegate.clone();t.delegate=e,t.syncDelegate(e)}return t}clearReplayCursor(e){this.runtimeMode===`intelligence`&&this.delegate?.clearReconnectCursor?.(e)}async resolveDelegate(){if(await this.ensureRuntimeConfiguration(),!this.delegate){if(this.runtimeMode!==`intelligence`)throw Error(`A delegate is only created for Intelligence mode`);this.delegate=this.createIntelligenceDelegate()}return this.syncDelegate(this.delegate),this.delegate}async ensureRuntimeConfiguration(){if(this.runtimeMode===`intelligence`||this.runtimeMode!==`pending`&&this.transport!==`auto`)return;if(!this.runtimeUrl)throw Error(`Runtime URL is not set`);let e=this.runtimeInfoPromise??this.fetchRuntimeInfo().then(e=>{this.runtimeMode=e.mode??`sse`,this.intelligence=e.intelligence});this.runtimeInfoPromise=e;try{await e}catch(t){throw this.runtimeInfoPromise===e&&(this.runtimeInfoPromise=void 0),t}}async fetchRuntimeInfo(){let e={...this.headers};if(this.transport===`auto`)return this.fetchRuntimeInfoAutoDetect(e);let t,n;if(this.transport===`single`){if(!this.singleEndpointUrl)throw Error(`Single endpoint transport requires a runtimeUrl`);e[`Content-Type`]||=`application/json`,n=this.runtimeUrl,t={method:`POST`,body:JSON.stringify({method:`info`})}}else n=`${this.runtimeUrl}/info`,t={};let r=await this.fetch(n,{...t,headers:e,...this.credentials?{credentials:this.credentials}:{}});if(!r.ok)throw await dm(r);return await r.json()}async fetchRuntimeInfoAutoDetect(e){try{let t=await this.fetch(`${this.runtimeUrl}/info`,{headers:{...e},...this.credentials?{credentials:this.credentials}:{}});if(t.status>=200&&t.status<300)return this.transport=`rest`,await t.json()}catch{}let t={...e};t[`Content-Type`]||=`application/json`;let n=await this.fetch(this.runtimeUrl,{method:`POST`,headers:t,body:JSON.stringify({method:`info`}),...this.credentials?{credentials:this.credentials}:{}});if(!n.ok)throw await dm(n);return this.transport=`single`,this.singleEndpointUrl=this.runtimeUrl,await n.json()}createSingleRouteRequestInit(e,t,n){if(!this.agentId)throw Error(`ProxiedCopilotRuntimeAgent requires agentId to make runtime requests`);let r=super.requestInit(e),i=new Headers(r.headers??{});i.set(`Content-Type`,`application/json`),i.set(`Accept`,i.get(`Accept`)??`text/event-stream`);let a;if(typeof r.body==`string`)try{a=JSON.parse(r.body)}catch(e){console.warn(`ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport`,e)}let o={method:t};return n&&Object.keys(n).length>0&&(o.params=n),a!==void 0&&(o.body=a),{...r,headers:i,body:JSON.stringify(o),...this.credentials?{credentials:this.credentials}:{}}}createIntelligenceDelegate(){let e=this.routedAgentId();if(!this.runtimeUrl||!e||!this.intelligence?.wsUrl)throw Error(`Intelligence mode requires runtimeUrl, agentId, and intelligence websocket metadata`);return new um({url:this.intelligence.wsUrl,runtimeUrl:this.runtimeUrl,agentId:e,headers:{...this.headers},credentials:this.credentials,fetch:this.fetch})}syncDelegate(e){e.agentId=this.routedAgentId(),e.description=this.description,e.threadId=this.threadId,e.setMessages(this.messages),e.setState(this.state),pm(e)&&(e.headers={...this.headers}),mm(e)&&(e.credentials=this.credentials)}},ym=new Set([`Fetch is aborted`,`signal is aborted without reason`,`component unmounted`]);function bm(e){if(typeof e!=`object`||!e)return!1;let{name:t,message:n}=e;return t===`AbortError`||typeof n==`string`&&ym.has(n)}var xm=1e4;function Sm(e){return e?.ɵruntimeRequest}function Cm(e){return e===`/threads`||e.startsWith(`/threads/`)||e===`/memories`||e.startsWith(`/memories/`)||e===`/annotate`}async function wm(e,t,n,r){if(r===`GET`||r===`HEAD`)return;let i;if(t?.body==null?e instanceof Request&&(i=await e.clone().text()):i=await new Response(t.body).text(),i){if(n.get(`content-type`)?.toLowerCase().includes(`application/json`))try{return JSON.parse(i)}catch{return i}return i}}async function Tm(e,t,n){let r=typeof window<`u`&&window.location?.href?window.location.href:`http://localhost`,i=new URL(n,r),a=e instanceof Request?e.url:e instanceof URL?e.href:e,o=new URL(a,r),s=i.pathname.replace(/\/$/,``);if(o.origin!==i.origin||!o.pathname.startsWith(`${s}/`))return null;
12let c=o.pathname.slice(s.length);if(!Cm(c))return null;let l=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase(),u=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),d=await wm(e,t,u,l);return u.set(`content-type`,`application/json`),u.delete(`content-length`),{input:n,init:{...e instanceof Request?{cache:e.cache,credentials:e.credentials,integrity:e.integrity,keepalive:e.keepalive,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}:{},...t,method:`POST`,headers:u,body:JSON.stringify({method:`resource/request`,params:{path:`${c}${o.search}`,httpMethod:l},...d===void 0?{}:{body:d}})}}}var Em=5e3,Dm=5e3;function Om(e,t){return t?.nonCritical?`ignored`:bm(e)&&!t?.timedOut?`aborted`:`failed`}function km(e){let t=new Headers(e);return t.has(`content-type`)||t.set(`content-type`,`application/json`),t}var Am=5e3,jm=class{_agents={};localAgents={};remoteAgents={};mintedThreadIds=new WeakMap;_runtimeUrl;_connectionInFlight;_runtimeConnectionGeneration=0;_activeRuntimeConnectionAttempt;_runtimeEntitlementRetryTimer;_runtimeEntitlementRetryAttemptedKey;_runtimeEntitlementRetryPendingKey;_runtimeVersion;_runtimeConnectionStatus=tg.Disconnected;_runtimeTransport=`auto`;_requestedTransport=`auto`;_audioFileTranscriptionEnabled=!1;_runtimeMode=`sse`;_intelligence;_threadEndpoints;_singleRouteResourceOperations=!1;_suggestions;_inspectorLearning=!1;_inspectorMetadata;_inspectorMetadataSupported=!1;inspectorMetadataRefreshReady=!1;inspectorMetadataConnectionGeneration=0;inspectorMetadataGeneration=0;inspectorMetadataHeadersGeneration=0;inspectorMetadataCredentialsGeneration=0;inspectorMetadataAbortController;inspectorMetadataNotificationQueue=Promise.resolve();_a2uiEnabled=!1;_a2uiAgents;_openGenerativeUIEnabled=!1;_licenseStatus;_runtimeEntitlements;_telemetryDisabled=!1;remoteAgentConnections=new WeakMap;runtimeFetch;runtimeProbeInFlight=!1;runtimeProbeToken=0;runtimeProbeAbortController;runtimeRecoveryRunning=!1;runtimeRecoveryPending=!1;runtimeHealthGeneration=0;agentOwnHeaders=new WeakMap;constructor(e){this.core=e}get agents(){return this._agents}get runtimeUrl(){return this._runtimeUrl}get runtimeVersion(){return this._runtimeVersion}get runtimeConnectionStatus(){return this._runtimeConnectionStatus}get runtimeTransport(){return this._runtimeTransport}get audioFileTranscriptionEnabled(){return this._audioFileTranscriptionEnabled}get runtimeMode(){return this._runtimeMode}get intelligence(){return this._intelligence}get threadEndpoints(){return this._threadEndpoints}get suggestions(){return this._suggestions}get inspectorLearning(){return this._inspectorLearning}get inspectorMetadata(){return this._inspectorMetadata}get a2uiEnabled(){return this._a2uiEnabled}get a2uiAgents(){return this._a2uiAgents}get openGenerativeUIEnabled(){return this._openGenerativeUIEnabled}get licenseStatus(){return this._licenseStatus}get runtimeEntitlements(){return this._runtimeEntitlements}get runtimeEntitlementRetryPending(){return this._runtimeEntitlementRetryPendingKey===this.runtimeConnectionKey()}get telemetryDisabled(){return this._telemetryDisabled}initialize(e){this.localAgents=this.assignAgentIds(e),this.applyHeadersToAgents(this.localAgents),this.applyCredentialsToAgents(this.localAgents),this.applyRuntimeFetchToAgents(this.localAgents),this._agents=this.localAgents}setRuntimeUrl(e,t){let n=e?e.replace(/\/$/,``):void 0;this._runtimeUrl!==n&&(this.invalidateInspectorMetadataConnection(),this.abandonRuntimeHealthProbe(),this.resetRuntimeEntitlementRetry(),this._licenseStatus=void 0,this._runtimeEntitlements=void 0,this._singleRouteResourceOperations=!1,this._runtimeUrl=n,!t?.deferConnection&&this.updateRuntimeConnection({preserveOnFailure:this.hasLiveRuntimeKnowledgeToProtect()}))}connectRuntime(){typeof window>`u`||this._runtimeUrl&&this._runtimeConnectionStatus===tg.Disconnected&&this.updateRuntimeConnection()}setRuntimeTransport(e){this._requestedTransport!==e&&(this.invalidateInspectorMetadataConnection(),this.abandonRuntimeHealthProbe(),this.resetRuntimeEntitlementRetry(),this._requestedTransport=e,this._runtimeTrans
12port=e,this._singleRouteResourceOperations=!1,this.updateRuntimeConnection({preserveOnFailure:this.hasLiveRuntimeKnowledgeToProtect()}))}hasLiveRuntimeKnowledgeToProtect(){return Object.keys(this.remoteAgents).length!==0&&this._runtimeConnectionStatus!==tg.Connected}reconcileRecoveredAgents(e){let t={...this.remoteAgents,...e};if(Object.keys(e).length===0)return t;for(let[n,r]of Object.entries(t))Object.prototype.hasOwnProperty.call(e,n)||this.carriesConversationState(r)||delete t[n];return t}carriesConversationState(e){if(e.messages.length>0)return!0;let t=this.mintedThreadIds.get(e);return t===void 0||e.threadId!==t}abandonRuntimeHealthProbe(){this.runtimeProbeToken+=1,this.runtimeProbeInFlight=!1,this.runtimeHealthGeneration+=1,this.runtimeProbeAbortController?.abort(),this.runtimeProbeAbortController=void 0}setAgents__unsafe_dev_only(e){Object.entries(e).forEach(([e,t])=>{t&&this.validateAndAssignAgentId(e,t)}),this.localAgents=e,this._agents={...this.localAgents,...this.remoteAgents},this.applyHeadersToAgents(this._agents),this.applyCredentialsToAgents(this._agents),this.applyRuntimeFetchToAgents(this._agents),this.notifyAgentsChanged()}addAgent__unsafe_dev_only({id:e,agent:t}){this.validateAndAssignAgentId(e,t),this.localAgents[e]=t,this.applyHeadersToAgent(t),this.applyCredentialsToAgent(t),this.applyRuntimeFetchToAgent(t),this._agents={...this.localAgents,...this.remoteAgents},this.notifyAgentsChanged()}removeAgent__unsafe_dev_only(e){delete this.localAgents[e],this._agents={...this.localAgents,...this.remoteAgents},this.notifyAgentsChanged()}registerProxiedAgent({agentId:e,runtimeAgentId:t}){if(Object.prototype.hasOwnProperty.call(this._agents,e))throw Error(`CopilotKitCore.registerProxiedAgent: agentId "${e}" is already registered. Pick a different agentId, or unregister the existing agent first.`);let n=this.core,r=n.debug,i=new vm({runtimeUrl:this._runtimeUrl,agentId:e,runtimeAgentId:t,transport:this._runtimeTransport,credentials:n.credentials,runtimeMode:this._runtimeUrl?this._runtimeConnectionStatus===tg.Connected?this._runtimeMode:`pending`:`sse`,intelligence:this._intelligence,debug:r?Gu(r):void 0});return this.applyHeadersToAgent(i),this.applyRuntimeFetchToAgent(i),this.localAgents[e]=i,this._agents={...this.localAgents,...this.remoteAgents},this.notifyAgentsChanged(),{agent:i,unregister:()=>{this.localAgents[e]===i&&(delete this.localAgents[e],this._agents={...this.localAgents,...this.remoteAgents},this.notifyAgentsChanged())}}}getAgent(e){if(e in this._agents)return this._agents[e];(this.runtimeUrl===void 0||this.runtimeConnectionStatus!==tg.Disconnected&&this.runtimeConnectionStatus!==tg.Connecting)&&console.warn(`Agent ${e} not found`)}applyHeadersToAgent(e){e instanceof Eu&&(this.agentOwnHeaders.has(e)||this.agentOwnHeaders.set(e,{...e.headers}),e.headers={...this.agentOwnHeaders.get(e),...this.core.headers})}applyHeadersToAgents(e){Object.values(e).forEach(e=>{this.applyHeadersToAgent(e)})}applyCredentialsToAgent(e){e instanceof vm&&(e.credentials=this.core.credentials)}applyCredentialsToAgents(e){Object.values(e).forEach(e=>{this.applyCredentialsToAgent(e)})}createRuntimeFetch(){return this.runtimeFetch||=(async(e,t)=>{let n=()=>Sm(t),r=this.armRuntimeRequestWatchdog(n());try{let i=this._runtimeTransport===`single`&&this._singleRouteResourceOperations&&this._runtimeUrl?await Tm(e,t,this._runtimeUrl):null,a=i?await fetch(i.input,i.init):await fetch(e,t);return r.clear(),this.handleRuntimeRequestOutcome(a.ok?`ok`:n()?.nonCritical?`ignored`:`failed`,r.checked),a}catch(e){throw r.clear(),this.handleRuntimeRequestOutcome(Om(e,n()),r.checked),e}}),this.runtimeFetch}armRuntimeRequestWatchdog(e){if(typeof window>`u`||e?.nonCritical||e?.selfBounded)return{clear:()=>{},checked:()=>!1};let t=!1,n=setTimeout(()=>{t=this.handleRuntimeRequestOutcome(`failed`)},xm);return{clear:()=>clearTimeout(n),checked:()=>t}}applyRuntimeFetchToAgent(e){e instanceof vm&&(e.fetch=this.createRuntimeFetch())}applyRuntimeFetchToAgents(e){Object.values(e).forEach(e=>{this.applyRuntimeFetchToAgent(e)})}handleHeadersChanged(){this.inspectorMetadataHeadersGeneration+=1,this.setInspectorMetadata(void 0),this.refreshInspectorMetadata()}handleCredentialsChanged(){this.inspectorMetadataCredentialsGeneration+=1,this.setInspectorMetadata(void 0),this.refreshInspectorMetadata()}async refreshInspectorMetadata(){let e=++this.inspectorMetadataGeneration;if(this.inspectorMetadataAbortController?.abort(),this.inspectorMetadataAbortController=void 0,!this._inspectorMetadataSupported||!this.inspectorMetadataRefreshReady||!this.runtimeUrl||this._runtimeConnectionStatus!==tg.Connected){this.setInspectorMetadata(void 0);return}let t=this.runtimeUrl,n=this._requestedTransport,r=this._runtimeTrans
12port,i=this.inspectorMetadataHeadersGeneration,a=this.inspectorMetadataCredentialsGeneration,o=this.core,s={...o.headers},c=o.credentials,l=new AbortController;this.inspectorMetadataAbortController=l;let u=!1,d,f,p=new Promise((e,t)=>{f=t}),m=()=>{f?.(Error(`Inspector metadata request aborted`))};l.signal.addEventListener(`abort`,m,{once:!0});let h=new Promise((e,t)=>{d=setTimeout(()=>{u=!0,t(Error(`Inspector metadata request timed out`)),l.abort()},Em)}),g;try{let e=(async()=>{let e=r===`single`?await this.fetchInspectorMetadataSingle({runtimeUrl:t,headers:s,credentials:c,signal:l.signal}):await this.fetchInspectorMetadataRest({runtimeUrl:t,headers:s,credentials:c,signal:l.signal});if(!(e.status===204||!e.ok))return zu(await e.json())})();g=await Promise.race([e,p,h])}catch{g=void 0}finally{d!==void 0&&clearTimeout(d),l.signal.removeEventListener(`abort`,m)}this.isInspectorMetadataRequestCurrent({generation:e,runtimeUrl:t,requestedTransport:n,resolvedTransport:r,headersGeneration:i,credentialsGeneration:a,signal:l.signal,allowAbortedSignal:u})&&(this.inspectorMetadataAbortController=void 0,this.setInspectorMetadata(g))}async fetchInspectorMetadataRest({runtimeUrl:e,headers:t,credentials:n,signal:r}){return fetch(`${e}/inspector-metadata`,{method:`GET`,headers:t,...n?{credentials:n}:{},signal:r})}async fetchInspectorMetadataSingle({runtimeUrl:e,headers:t,credentials:n,signal:r}){return fetch(e,{method:`POST`,headers:km(t),body:JSON.stringify({method:`inspector/metadata`}),...n?{credentials:n}:{},signal:r})}isInspectorMetadataRequestCurrent({generation:e,runtimeUrl:t,requestedTransport:n,resolvedTransport:r,headersGeneration:i,credentialsGeneration:a,signal:o,allowAbortedSignal:s=!1}){return(s||!o.aborted)&&e===this.inspectorMetadataGeneration&&t===this.runtimeUrl&&n===this._requestedTransport&&r===this._runtimeTransport&&i===this.inspectorMetadataHeadersGeneration&&a===this.inspectorMetadataCredentialsGeneration&&this._inspectorMetadataSupported&&this.inspectorMetadataRefreshReady&&this._runtimeConnectionStatus===tg.Connected}invalidateInspectorMetadataConnection(){this._inspectorMetadataSupported=!1,this._inspectorLearning=!1,this.inspectorMetadataRefreshReady=!1,this.inspectorMetadataConnectionGeneration+=1,this.inspectorMetadataGeneration+=1,this.inspectorMetadataAbortController?.abort(),this.inspectorMetadataAbortController=void 0,this.setInspectorMetadata(void 0)}setInspectorMetadata(e){if(JSON.stringify(this._inspectorMetadata)===JSON.stringify(e))return;this._inspectorMetadata=e;let t=e;this.inspectorMetadataNotificationQueue=this.inspectorMetadataNotificationQueue.then(()=>this.notifyInspectorMetadataChanged(t)).catch(e=>{console.error(`Subscriber onInspectorMetadataChanged queue error:`,e)})}setRuntimeConnectionStatus(e){this._runtimeConnectionStatus=e,this.runtimeHealthGeneration+=1}handleRuntimeRequestOutcome(e,t=()=>!1){return e===`aborted`||e===`ignored`||e===`failed`&&t()||typeof window>`u`||!this._runtimeUrl?!1:e===`ok`?(this.runtimeHealthGeneration+=1,this.runtimeRecoveryRunning&&(this.runtimeRecoveryPending=!0),this._runtimeConnectionStatus===tg.Error&&this.recoverRuntimeConnection(),!1):this._runtimeConnectionStatus!==tg.Connected||this.runtimeProbeInFlight?!1:(this.probeRuntimeReachability(),!0)}async fetchRuntimeInfoWithTimeout(e,t=this.runtimeUrl,n=this._runtimeTransport){if(!t)throw Error(`Runtime URL is not set`);let r,i=this.fetchRuntimeInfo(t,n,e.signal);i.catch(()=>{});try{let t=new Promise((t,n)=>{r=setTimeout(()=>{e.abort(),n(Error(`Runtime did not answer within ${Dm}ms`))},Dm)});return await Promise.race([i,t])}finally{r!==void 0&&clearTimeout(r)}}async probeRuntimeReachability(){let e=this.runtimeHealthGeneration,t=++this.runtimeProbeToken;this.runtimeProbeInFlight=!0;let n=new AbortController;this.runtimeProbeAbortController=n;try{await this.fetchRuntimeInfoWithTimeout(n)}catch(t){if(e!==this.runtimeHealthGeneration)return;await this.markRuntimeUnreachable(t instanceof Error?t:Error(String(t)))}finally{this.runtimeProbeAbortController===n&&(this.runtimeProbeAbortController=void 0),this.runtimeProbeToken===t&&(this.runtimeProbeInFlight=!1)}}async markRuntimeUnreachable(e){this.setRuntimeConnectionStatus(tg.Error),await this.notifyRuntimeStatusChanged(tg.Error);let t=fm(e)?e.runtimeInfoStatus:void 0;Ju.warn(t===void 0?`Runtime did not answer the identification request (${this._runtimeUrl}/info): ${e.message}. The runtime appears to be unreachable.`:`Runtime answered the identification request with status ${t} (${this._runtimeUrl}/info): ${e.message}. The runtime is reachable but refused the request — check credentials and authorisation before addresses and ports.`),await this.core.emitError({error:e,code:$h.RUNTIME_INFO_FETCH_FAILED,context:{runtimeUrl:this._runtimeUrl,reason:t===void 0?`no-answer`:`answered`,...t===void 0?{}:{runtimeStatus:t}}})}async recoverRuntimeConnection(){if(this.runtimeRecoveryRunning){this.runtimeRecoveryPending=!0;return}this.runtimeRecoveryRunning=!0;try{do this.runtimeRecoveryPending=!1,await this.updateRuntimeConnection({preserveOnFailure:!0,recovery:!0});while(this.runtimeRecoveryPending&&this._runtimeConnectionStatus!==tg.Connected)}finally{this.runtimeRecoveryRunning=!1,this.runtimeRecoveryPending=!1}}async updateRuntimeConnection(e){if(typeof window>`u`)return;let t=this.runtimeConnectionKey(),n=this._connectionInFlight;if(n&&n.attempt.key===t&&this.isCurrentRuntimeConnection(n.attempt))return n.promise;let r={key:t,generation:++this._runtimeConnectionGeneration};this._activeRuntimeConnectionAttempt=r;let i=this.performRuntimeConnection({attempt:r,runtimeUrl:this._runtimeUrl,transport:this._runtimeTrans
12port,options:e});return this._connectionInFlight={attempt:r,promise:i},i.finally(()=>{this._connectionInFlight?.promise===i&&(this._connectionInFlight=void 0)}),i}runtimeConnectionKey(){return`${this._runtimeUrl??``}::${this._requestedTransport}`}canReuseRuntimeAgent(e,t,n){if(!t)return!1;let r=this.remoteAgentConnections.get(e);return r?.runtimeUrl===t.replace(/\/$/,``)&&r.transport===n}isCurrentRuntimeConnection(e){return this._activeRuntimeConnectionAttempt?.generation===e.generation&&this.runtimeConnectionKey()===e.key}resetRuntimeEntitlementRetry(){this._runtimeEntitlementRetryTimer!==void 0&&(clearTimeout(this._runtimeEntitlementRetryTimer),this._runtimeEntitlementRetryTimer=void 0),this._runtimeEntitlementRetryAttemptedKey=void 0,this._runtimeEntitlementRetryPendingKey=void 0}updateRuntimeEntitlementRetry(e,t){if(!this.isCurrentRuntimeConnection(t))return;let{key:n}=t;if(e?.status===`ready`||e?.error.retryable!==!0){this.resetRuntimeEntitlementRetry();return}if(this._runtimeEntitlementRetryTimer===void 0){if(this._runtimeEntitlementRetryAttemptedKey===n){this._runtimeEntitlementRetryPendingKey=void 0;return}this._runtimeEntitlementRetryAttemptedKey=n,this._runtimeEntitlementRetryPendingKey=n,this._runtimeEntitlementRetryTimer=setTimeout(()=>{this._runtimeEntitlementRetryTimer=void 0,this.executeRuntimeEntitlementRetry(t).catch(e=>{let t=e instanceof Error?e.message:JSON.stringify(e);Ju.warn(`Failed to retry runtime info (${this.runtimeUrl}/info): ${t}`)})},Am)}}async executeRuntimeEntitlementRetry(e){let t=this._connectionInFlight;t?.attempt.generation===e.generation&&await t.promise,!(!this._runtimeUrl||!this.isCurrentRuntimeConnection(e))&&await this.updateRuntimeConnection()}async performRuntimeConnection({attempt:e,runtimeUrl:t,transport:n,options:r}){let{key:i}=e;if(!t){if(this.invalidateInspectorMetadataConnection(),this.setRuntimeConnectionStatus(tg.Disconnected),this._runtimeVersion=void 0,this._audioFileTranscriptionEnabled=!1,this._runtimeMode=`sse`,this._intelligence=void 0,this._threadEndpoints=void 0,this._singleRouteResourceOperations=!1,this._suggestions=void 0,this._inspectorLearning=!1,this._a2uiEnabled=!1,this._a2uiAgents=void 0,this._openGenerativeUIEnabled=!1,this._licenseStatus=void 0,this._runtimeEntitlements=void 0,this.remoteAgents={},this._agents=this.localAgents,await this.notifyRuntimeStatusChanged(tg.Disconnected),!this.isCurrentRuntimeConnection(e))return;await this.notifyAgentsChanged();return}let a=this.inspectorMetadataConnectionGeneration;this.setRuntimeConnectionStatus(tg.Connecting);let o=this.runtimeHealthGeneration;if(await this.notifyRuntimeStatusChanged(tg.Connecting),this.isCurrentRuntimeConnection(e))try{if(a!==this.inspectorMetadataConnectionGeneration)return;let{runtimeInfo:i,resolvedTransport:o}=r?.recovery?await this.fetchRuntimeInfoWithTimeout(new AbortController,t,n):await this.fetchRuntimeInfo(t,n);if(!this.isCurrentRuntimeConnection(e)||a!==this.inspectorMetadataConnectionGeneration)return;this._runtimeTransport=o;let{version:s,...c}=i,l=this.core.credentials,u=this.core.debug,d=Object.fromEntries(Object.entries(c.agents).map(([e,{description:n,capabilities:a}])=>{let o=Object.prototype.hasOwnProperty.call(this.remoteAgents,e)?this.remoteAgents[e]:void 0;if(o instanceof vm&&this.canReuseRuntimeAgent(o,t,this._runtimeTransport))return this.applyHeadersToAgent(o),this.applyCredentialsToAgent(o),this.applyRuntimeFetchToAgent(o),[e,o];let s=new vm({runtimeUrl:t,agentId:e,description:n,transport:this._runtimeTransport,credentials:l,runtimeMode:i.mode??`sse`,intelligence:i.intelligence,capabilities:a,debug:u?Gu(u):void 0});return this.applyHeadersToAgent(s),this.applyRuntimeFetchToAgent(s),this.mintedThreadIds.set(s,s.threadId),r?.preserveOnFailure===!0&&o&&(s.threadId=o.threadId,s.setState(o.state),s.setMessages([...o.messages])),this.remoteAgentConnections.set(s,{runtimeUrl:t,transport:this._runtimeTransport}),[e,s]}));this.remoteAgents=r?.recovery?this.reconcileRecoveredAgents(d):d,this._agents={...this.localAgents,...this.remoteAgents},this.setRuntimeConnectionStatus(tg.Connected),this._runtimeVersion=s,this._audioFileTranscriptionEnabled=i.audioFileTranscriptionEnabled??!1,this._runtimeMode=i.mode??`sse`,this._intelligence=i.intelligence,this._singleRouteResourceOperations=o===`single`&&i.singleRoute?.resourceOperations===!0,this._threadEndpoints=this._singleRouteResourceOperations?i.singleRoute?.threadEndpoints:i.threadEndpoints,this._suggestions=i.suggestions,this._inspectorLearning=i.inspectorLearning===!0,this._inspectorMetadataSupported=i.inspectorMetadata===!0,this.inspectorMetadataRefreshReady=!1,this._inspectorMetadataSupported||this.setInspectorMetadata(void 0);let f=i.a2ui;if(this._a2uiEnabled=f?.enabled??i.a2uiEnabled??!1,this._a2uiAgents=f?.enabled?f.agents:void 0,this._openGenerativeUIEnabled=i.openGenerativeUIEnabled??!1,this._licenseStatus=i.licenseStatus,this._runtimeEntitlements=i.runtimeEntitlements,this.updateRuntimeEntitlementRetry(i.runtimeEntitlements,e),this._telemetryDisabled=i.telemetryDisabled??!1,await this.notifyRuntimeStatusChanged(tg.Connected),!this.isCurrentRuntimeConnection(e)||(await this.notifyAgentsChanged(),a!==this.inspectorMetadataConnectionGeneration||this._runtimeConnectionStatus!==tg.Connected))return;this.inspectorMetadataRefreshReady=!0,this._inspectorMetadataSupported&&this.refreshInspectorMetadata()}catch(n){if(!this.isCurrentRuntimeConnection(e)||a!==this.inspectorMetadataConnectionGeneration)return;let s=this._runtimeEntitlementRetryTimer===void 0&&this._runtimeEntitlementRetryAttemptedKey===i&&this._runtimeEntitlementRetryPendingKey===i;if(s&&(this._runtimeEntitlementRetryPendingKey=void 0),r?.preserveOnFailure){if(r?.recovery&&o!==this.runtimeHealthGeneration)return;this.setRuntimeConnectionStatus(tg.Error),await this.notifyRuntimeStatusChanged(tg.Error)}else this.invalidateInspectorMetadataConnection(),this.setRuntimeConnectionStatus(tg.Error),this._runtimeVersion=void 0,this._audioFileTranscriptionEnabled=!1,this._runtimeMode=`sse`,this._intelligence=void 0,this._threadEndpoints=void 0,this._singleRouteResourceOperations=!1,this._suggestions=void 0,this._inspectorLearning=!1,this._a2uiEnabled=!1,this._a2uiAgents=void 0,this._openGenerativeUIEnabled=!1,s||(this._licenseStatus=void 0,this._runtimeEntitlements=void 0),this.remoteAgents={},this._agents=this.localAgents,await this.notifyRuntimeStatusChanged(tg.Error),await this.notifyAgentsChanged();let c=n instanceof Error?n.message:JSON.stringify(n);Ju.warn(`Failed to load runtime info (${t}/info): ${c}`);let l=n instanceof Error?n:Error(String(n));await this.core.emitError({error:l,code:$h.RUNTIME_INFO_FETCH_FAILED,context:{runtimeUrl:t}})}}async fetchRuntimeInfo(e,t,n){let r=this.core.headers,i=this.core.credentials,a={...r};if(t===`single`)return{runtimeInfo:await this.fetchRuntimeInfoSingle(e,a,i,n),resolvedTransport:`single`};if(t===`auto`)return this.fetchRuntimeInfoAutoDetect(e,a,i,n);let o=await fetch(`${e}/info`,{headers:a,...i?{credentials:i}:{},...n?{signal:n}:{}});if(!o.ok)throw await dm(o);return{runtimeInfo:await o.json(),resolvedTransport:`rest`}}async fetchRuntimeInfoSingle(e,t,n,r){let i=await fetch(e,{method:`POST`,headers:km(t),body:JSON.stringify({method:`info`}),...n?{credentials:n}:{},...r?{signal:r}:{}});if(!i.ok)throw await dm(i);return await i.json()}async fetchRuntimeInfoAutoDetect(e,t,n,r){try{let i=await fetch(`${e}/info`,{headers:{...t},...n?{credentials:n}:{},...r?{signal:r}:{}});if(i.status>=200&&i.status<300)return{runtimeInfo:await i.json(),resolvedTransport:`rest`}}catch{}return{runtimeInfo:await this.fetchRuntimeInfoSingle(e,{...t},n,r),resolvedTransport:`single`}}assignAgentIds(e){return Object.entries(e).forEach(([e,t])=>{t&&this.validateAndAssignAgentId(e,t)}),e}validateAndAssignAgentId(e,t){if(t.agentId&&t.agentId!==e)throw Error(`Agent registration mismatch: Agent with ID "${t.agentId}" cannot be registered under key "${e}". The agent ID must match the registration key or be undefined.`);t.agentId||=e}async notifyRuntimeStatusChanged(e){await this.core.notifySubscribers(t=>t.onRuntimeConnectionStatusChanged?.({copilotkit:this.core,status:e}),`Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):`)}async notifyAgentsChanged(){await this.core.notifySubscribers(e=>e.onAgentsChanged?.({copilotkit:this.core,agents:this._agents}),`Subscriber onAgentsChanged error:`)}async notifyInspectorMetadataChanged(e){await this.core.notifySubscribers(t=>t.onInspectorMetadataChanged?.({copilotkit:this.core,inspectorMetadata:e}),`Subscriber onInspectorMetadataChanged error:`)}},Mm=class{_context={};constructor(e){this.core=e}get context(){return this._context}addContext({description:e,value:t,agentIds:n}){let r=i();return this._context[r]={description:e,value:t,...n?{agentIds:n}:{}},this.notifySubscribers(),r}getContextForAgent(e){return Object.values(this._context).filter(t=>!t.agentIds||e!==void 0&&t.agentIds.includes(e)).map(({description:e,value:t})=>({description:e,value:t}))}
12removeContext(e){delete this._context[e],this.notifySubscribers()}async notifySubscribers(){await this.core.notifySubscribers(e=>e.onContextChanged?.({copilotkit:this.core,context:this._context}),`Subscriber onContextChanged error:`)}},Nm=class{_suggestionsConfig={};_suggestions={};_runningSuggestions={};constructor(e){this.core=e}initialize(e){for(let t of e)this._suggestionsConfig[i()]=t}addSuggestionsConfig(e){let t=i();return this._suggestionsConfig[t]=e,this.notifySuggestionsConfigChanged(),t}removeSuggestionsConfig(e){delete this._suggestionsConfig[e],this.notifySuggestionsConfigChanged()}reloadSuggestions(e){this.clearSuggestions(e);let t=this.core.getAgent(e),n=t?.messages?.length??0,r=!1;for(let a of Object.values(this._suggestionsConfig)){if(a.consumerAgentId!==void 0&&a.consumerAgentId!==`*`&&a.consumerAgentId!==e||!this.shouldShowSuggestions(a,n))continue;let o=i();if(Fm(a)){if(!t)continue;r||(r=!0,this.notifySuggestionsStartedLoading(e)),this.generateSuggestions(o,a,e)}else Im(a)&&this.addStaticSuggestions(o,a,e)}}clearSuggestions(e){let t=this._runningSuggestions[e];if(t){for(let e of t)e.abortRun();delete this._runningSuggestions[e]}this._suggestions[e]={},this.notifySuggestionsChanged(e,[])}getSuggestions(e){return{suggestions:Object.values(this._suggestions[e]??{}).flat(),isLoading:(this._runningSuggestions[e]?.length??0)>0}}async generateSuggestions(e,t,n){let r,i=!1;try{let a=this.core,o=t.providerAgentId??`default`,s=a.getAgent(o);if(!s)throw Error(`Suggestions provider agent not found: ${o}`);let c=a.getAgent(n);if(!c)throw Error(`Suggestions consumer agent not found: ${n}`);let l=["Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the `copilotkitSuggest` tool.",`Provide at least ${t.minSuggestions??1} and at most ${t.maxSuggestions??3} suggestions.`,`The user has the following tools available: ${JSON.stringify(a.buildFrontendTools(n))}.`,` ${t.instructions}`].join(`
13`);this._suggestions[n]={...this._suggestions[n],[e]:[]};let u=JSON.parse(JSON.stringify(c.messages)),d=JSON.parse(JSON.stringify(c.state??{})),f=this.core.suggestions===!0&&this.core.runtimeTransport!==`single`,p;if(f){let e=`${this.core.runtimeUrl}/agent/${encodeURIComponent(o)}/suggest`,t=this.core.credentials;p=new Eu({agentId:o,url:e,headers:{...this.core.headers},...t?{fetch:(e,n)=>fetch(e,{...n,credentials:t})}:{}})}else p=s.clone();p.threadId=e,p.setMessages(u),p.setState(d),r={abortRun:()=>{i=!0,p.abortRun()}},this._runningSuggestions[n]=[...this._runningSuggestions[n]??[],r],p.addMessage({id:e,role:`user`,content:l}),await p.runAgent({context:a.getContextForAgent(n),forwardedProps:{...a.properties,toolChoice:{type:`function`,function:{name:`copilotkitSuggest`}}},tools:[Lm]},{onMessagesChanged:({messages:t})=>{this.extractSuggestions(t,e,n,!0)}})}catch(e){!Pm(e)&&!i&&console.warn(`Error generating suggestions:`,e)}finally{this.finalizeSuggestions(e,n);let t=this._runningSuggestions[n],i=r?(t??[]).filter(e=>e!==r):t??[];i.length===0?(delete this._runningSuggestions[n],await this.notifySuggestionsFinishedLoading(n)):this._runningSuggestions[n]=i}}finalizeSuggestions(e,t){let n=this._suggestions[t],r=n?.[e];if(n&&r&&r.length>0){let i=r.filter(e=>e.title!==``||e.message!==``).map(e=>({...e,isLoading:!1}));i.length>0?n[e]=i:delete n[e];let a=Object.values(this._suggestions[t]??{}).flat();this.notifySuggestionsChanged(t,a,`finalized`)}}extractSuggestions(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(i==-1)return;let a=[],o=e.slice(i+1);for(let e of o)if(e.role===`assistant`&&e.toolCalls){for(let t of e.toolCalls)if(t.function.name===`copilotkitSuggest`){let e=Hu(Array.isArray(t.function.arguments)?t.function.arguments.join(``):t.function.arguments);if(e&&typeof e==`object`&&`suggestions`in e){let t=e.suggestions;if(Array.isArray(t))for(let e of t)e&&typeof e==`object`&&`title`in e&&a.push({title:e.title??``,message:e.message??``,isLoading:!1})}}}r&&a.length>0&&(a[a.length-1].isLoading=!0);let s=this._suggestions[n];if(s){s[t]=a;let e=Object.values(this._suggestions[n]??{}).flat();this.notifySuggestionsChanged(n,e,`suggestions changed`)}}async notifySuggestionsConfigChanged(){await this.core.notifySubscribers(e=>e.onSuggestionsConfigChanged?.({copilotkit:this.core,suggestionsConfig:this._suggestionsConfig}),`Subscriber onSuggestionsConfigChanged error:`)}async notifySuggestionsChanged(e,t,n=``){await this.core.notifySubscribers(n=>n.onSuggestionsChanged?.({copilotkit:this.core,agentId:e,suggestions:t}),`Subscriber onSuggestionsChanged error: ${n}`)}async notifySuggestionsStartedLoading(e){await this.core.notifySubscribers(t=>t.onSuggestionsStartedLoading?.({copilotkit:this.core,agentId:e}),`Subscriber onSuggestionsStartedLoading error:`)}async notifySuggestionsFinishedLoading(e){await this.core.notifySubscribers(t=>t.onSuggestionsFinishedLoading?.({copilotkit:this.core,agentId:e}),`Subscriber onSuggestionsFinishedLoading error:`)}shouldShowSuggestions(e,t){let n=e.available;if(!n)return Fm(e)?t>0:t===0;switch(n){case`disabled`:return!1;case`before-first-message`:return t===0;case`after-first-message`:return t>0;case`always`:return!0;default:return!1}}addStaticSuggestions(e,t,n){let r=t.suggestions.map(e=>({...e,isLoading:!1}));this._suggestions[n]={...this._suggestions[n],[e]:r};let i=Object.values(this._suggestions[n]??{}).flat();this.notifySuggestionsChanged(n,i,`static suggestions added`)}};function Pm(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`}function Fm(e){return`instructions`in e}function Im(e){return`suggestions`in e}var Lm={name:`copilotkitSuggest`,description:`Suggest what the user could say next`,parameters:{type:`object`,properties:{suggestions:{type:`array`,description:`List of suggestions shown to the user as buttons.`,items:{type:`object`,properties:{title:{type:`string`,description:`The title of the suggestion. This is shown as a button and should be short.`},message:{type:`string`,description:`The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.`}},required:[`title`,`message`]}}},required:[`suggestions`]}},Rm=`Forwarded to client`;function zm(e){if(typeof e==`string`)return e.trim();if(Array.isArray(e)){let t=e.flatMap(e=>typeof e==`string`?[e]:e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`?[e.text]:[]).join(``).trim();return t.length>0?t:null}return e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`?e.text.trim():null}function Bm(e){return zm(e)===Rm}var Vm={type:`object`,properties:{}};function Hm(e){if(!e.parameters)return{...Vm};let t=qu(e.parameters,{zodToJsonSchema:(e,t)=>Gp(e,t)});if(!t||typeof t!=`object`)return{...Vm};let{$schema:n,...r}=t;return typeof r.type!=`string`&&(r.type=`object`),(typeof r.properties!=`object`||r.properties===null)&&(r.properties={}),Um(r),r}function Um(e){if(!e||typeof e!=`object`)return;if(Array.isArray(e)){e.forEach(Um);return}let t=e;t.additionalProperties!==void 0&&delete t.additionalProperties;for(let e of Object.values(t))Um(e)}function Wm(){return typeof document>
13`u`?null:document.modelContext??null}var Gm=class{entries=new Map;warnedNames=new Set;get registeredNames(){return[...this.entries.keys()]}sync(e){let t=Wm();if(t){for(let[t,n]of[...this.entries])e.get(t)!==n.tool&&(n.controller.abort(),this.entries.delete(t));for(let[n,r]of e){if(this.entries.has(n))continue;if(!r.description){this.warnOnce(n,`Skipping WebMCP registration for tool '${n}': WebMCP requires a description.`);continue}let e=new AbortController;this.entries.set(n,{tool:r,controller:e}),t.registerTool(this.buildModelContextTool(r),{signal:e.signal}).catch(t=>{if(this.entries.get(n)?.controller!==e)return;this.entries.delete(n);let r=t instanceof Error?t.message:String(t);this.warnOnce(n,`WebMCP registration failed for tool '${n}': ${r}`)})}}}buildModelContextTool(e){let t=typeof e.webmcp==`object`?e.webmcp.annotations:void 0;return{name:e.name,description:e.description,inputSchema:Hm(e),execute:async(t,n)=>{if(!e.handler)return``;let r={id:i(),type:`function`,function:{name:e.name,arguments:JSON.stringify(t??{})}};return await e.handler(t,{toolCall:r,signal:n?.signal})},...t?{annotations:t}:{}}}warnOnce(e,t){this.warnedNames.has(e)||(this.warnedNames.add(e),Ju.warn(`[CopilotKit] ${t}`))}},Km=100,qm=`*`,Jm=class{_propTools=[];_hookTools=new Map;_cachedMergedTools=null;_catalogComponents=[];_disabledCatalogComponents=new Set;_disabledToolKeys=new Set;_runAbortController=null;_runDepth=0;_webmcpRegistry=new Gm;_lastConnectedThreadIdsByAgent=new Map;_anonymousAgentIds=new WeakMap;_nextAnonymousAgentId=0;constructor(e){this.core=e}abortCurrentRun(){this._runAbortController?.abort()}get _internal(){return this.core}getConnectRestoreKey(e){if(e.agentId)return`agent:${e.agentId}`;let t=this._anonymousAgentIds.get(e);if(t)return t;let n=`anonymous:${this._nextAnonymousAgentId}`;return this._nextAnonymousAgentId+=1,this._anonymousAgentIds.set(e,n),n}get tools(){if(this._hookTools.size===0)return this._propTools;if(this._cachedMergedTools)return this._cachedMergedTools;let e=new Map;for(let t of this._propTools)e.set(this.capabilityKey(t.name,t.agentId),t);for(let[t,n]of this._hookTools)e.set(t,n);return this._cachedMergedTools=Array.from(e.values()),this._cachedMergedTools}initialize(e){this._propTools=[...e],this._cachedMergedTools=null,this.syncWebMCP()}addTool(e){let t=this.capabilityKey(e.name,e.agentId);if(this._hookTools.has(t)){Ju.warn(`Tool already exists: '${e.name}' for agent '${e.agentId||`global`}', skipping.`);return}this._hookTools.set(t,e),this._cachedMergedTools=null,this.syncWebMCP()}removeTool(e,t){this._hookTools.delete(this.capabilityKey(e,t)),this._propTools=this._propTools.filter(n=>t===void 0?!(n.name===e&&!n.agentId):n.name!==e||n.agentId!==t),this._cachedMergedTools=null,this.syncWebMCP()}getTool(e){let{toolName:t,agentId:n}=e,r=this.tools;if(n){let e=r.find(e=>e.name===t&&e.agentId===n);if(e)return e}return r.find(e=>e.name===t&&!e.agentId)}setTools(e){this._propTools=[...e],this._cachedMergedTools=null,this.syncWebMCP()}get catalogComponents(){return this._catalogComponents}setCatalogComponents(e){this._catalogComponents=[...e]}setCatalogComponentEnabled(e,t){t?this._disabledCatalogComponents.delete(e):this._disabledCatalogComponents.add(e)}isCatalogComponentEnabled(e){return!this._disabledCatalogComponents.has(e)}async connectAgent({agent:e}){let t=e.threadId??null;try{let n=this.getConnectRestoreKey(e),r=t!==(this._lastConnectedThreadIdsByAgent.get(n)??null);if(this._lastConnectedThreadIdsByAgent.set(n,t),await e.detachActiveRun(),r){e.setMessages([]),e.setState({});let n=e;t&&(typeof n.clearReplayCursor==`function`&&n.clearReplayCursor(t),typeof n.clearReconnectCursor==`function`&&n.clearReconnectCursor(t))}this._internal.applyHeadersToAgent(e),await this._internal.notifySubscribers(t=>t.onAgentRunStarted?.({copilotkit:this.core,agent:e}),`Subscriber onAgentRunStarted error:`);let i=await e.connectAgent({forwardedProps:this._internal.properties,tools:this.buildFrontendTools(e.agentId),context:this._internal.getContextForAgent(e.agentId)},this.createAgentErrorSubscriber(e));return this.processAgentResult({runAgentResult:i,agent:e,executeFrontendTools:!1})}catch(n){let r=n instanceof Error?n:Error(String(n));if(!bm(r)){let n={};e.agentId&&(n.agentId=e.agentId),t&&(n.threadId=t),await this._internal.emitError({error:r,code:$h.AGENT_CONNECT_FAILED,context:n})}return{result:void 0,newMessages:[]}}}async runAgent({agent:e,forwardedProps:t,resume:n,runId:r}
13,i){if(e.agentId&&this._internal.suggestionEngine.clearSuggestions(e.agentId),this._internal.applyHeadersToAgent(e),e.detachActiveRun)try{await e.detachActiveRun()}catch(e){throw i?.cancel(),e}let a=this._runDepth===0,o;if(a){this._runAbortController=new AbortController;let t=this._runAbortController;o=e.abortRun.bind(e),e.abortRun=()=>{t.abort(),o()},await this._internal.notifySubscribers(t=>t.onAgentRunStarted?.({copilotkit:this.core,agent:e}),`Subscriber onAgentRunStarted error:`)}this._runDepth++;try{let a=r,o=this.createAgentErrorSubscriber(e),s=!1,c=o.onRunStartedEvent,l=o.onRunInitialized;o.onRunInitialized=async e=>(i?.bind(e.input),l?.(e)),o.onRunStartedEvent=async e=>(s=!0,i||(a=e.input.runId),c?.(e));let u=r!==void 0&&!i,d={forwardedProps:{...this._internal.properties,...t},...n===void 0?{}:{resume:n},...u?{runId:r}:{},tools:this.buildFrontendTools(e.agentId),context:this._internal.getContextForAgent(e.agentId)},f=await e.runAgent(d,o);return s||i?.cancel(),await this.processAgentResult({runAgentResult:f,agent:e,runId:a})}catch(t){i?.cancel();let n=t instanceof Error?t:Error(String(t)),r={};return e.agentId&&(r.agentId=e.agentId),await this._internal.emitError({error:n,code:$h.AGENT_RUN_FAILED,context:r}),{result:void 0,newMessages:[]}}finally{this._runDepth--,a&&o&&(e.abortRun=o)}}async processAgentResult({runAgentResult:e,agent:t,runId:n,executeFrontendTools:r=!0}){let{newMessages:i}=e,a=t.agentId,o=!1;if(r){for(let e of i)if(e.role===`assistant`)for(let n of e.toolCalls||[]){let r=this.getTool({toolName:n.function.name,agentId:t.agentId}),s,c=()=>(r||s||(s=this.getTool({toolName:qm,agentId:t.agentId})),s),l=i.findIndex(e=>e.role===`tool`&&e.toolCallId===n.id),u=l===-1?void 0:i[l],d=r??c();if(u&&d?.handler&&this.isFrontendPlaceholderResult(u)){i.splice(l,1),l=-1;let e=t.messages.findIndex(e=>e.role===`tool`&&e.toolCallId===n.id);e!==-1&&t.messages.splice(e,1)}if(l===-1){if(r)await this.executeSpecificTool(r,n,e,t,a)&&(o=!0);else{let r=c();r&&await this.executeWildcardTool(r,n,e,t,a)&&(o=!0)}}}}if(o&&!this._runAbortController?.signal.aborted){if(this._runDepth>=Km)Ju.warn(`[CopilotKit] Follow-up depth limit (${Km}) reached for agent "${a}". Stopping recursive follow-up runs to prevent an infinite loop. This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly calling the same tool). Consider setting "followUp: false" on the offending tool.`);else{await this._internal.waitForPendingFrameworkUpdates();let e=this._internal.stateManager.markNextRunAsContinuation(t,n);return await this.runAgent({agent:t,...n===void 0?{}:{runId:n}},e)}}return this._internal.suggestionEngine.reloadSuggestions(a),e}isFrontendPlaceholderResult(e){return e.role===`tool`&&Bm(e.content)}async executeToolHandler({tool:e,toolCall:t,agent:n,agentId:r,handlerArgs:i,toolType:a,messageId:o}){let s=``,c,l=!1,u;try{u=Xm(i,t.function.name)}catch(e){let n=e instanceof Error?e:Error(String(e));c=n.message,l=!0,await this._internal.emitError({error:n,code:$h.TOOL_ARGUMENT_PARSE_FAILED,context:{agentId:r,toolCallId:t.id,toolName:t.function.name,rawArguments:i,toolType:a,...o?{messageId:o}:{}}})}if(await this._internal.notifySubscribers(e=>e.onToolExecutionStart?.({copilotkit:this.core,toolCallId:t.id,agentId:r,toolName:t.function.name,args:u}),`Subscriber onToolExecutionStart error:`),!c)try{let r=await e.handler(u,{toolCall:t,agent:n,signal:this._runAbortController?.signal});s=r==null?``:typeof r==`string`?r:JSON.stringify(r)}catch(e){let n=e instanceof Error?e:Error(String(e));c=n.message,await this._internal.emitError({error:n,code:$h.TOOL_HANDLER_FAILED,context:{agentId:r,toolCallId:t.id,toolName:t.function.name,parsedArgs:u,toolType:a,...o?{messageId:o}:{}}})}return c&&(s=`Error: ${c}`),await this._internal.notifySubscribers(e=>e.onToolExecutionEnd?.({copilotkit:this.core,toolCallId:t.id,agentId:r,toolName:t.function.name,result:c?``:s,error:c}),`Subscriber onToolExecutionEnd error:`),{result:s,error:c,isArgumentError:l}}async executeSpecificTool(e,t,n,r,a){if(e?.agentId&&e.agentId!==r.agentId)return!1;let o={result:``,error:void 0,isArgumentError:!1};e?.handler&&(o=await this.executeToolHandler({tool:e,toolCall:t,agent:r,agentId:a,handlerArgs:t.function.arguments,toolType:`specific`,messageId:n.id}));{let a=r.messages.findIndex(e=>e.id===n.id);if(a===-1)return!1;let s=a+1;for(;s<r.messages.length&&r.messages[s]?.role===`tool`;)s++;let c={id:i(),role:`tool`,toolCallId:t.id,content:o.result};if(r.messages.splice(s,0,c),!o.error&&e?.followUp!==!1)return!0}return!1}async executeWildcardTool(e,t,n,r,a){if(e?.agentId&&e.agentId!==r.agentId)return!1;let o=``,s;if(e?.handler){let i;try{i=Xm(t.function.arguments,t.function.name)}catch(e){let r=e instanceof Error?e:Error(String(e));s=r.message,await this._internal.emitError({error:r,code:$h.TOOL_ARGUMENT_PARSE_FAILED,context:{agentId:a,toolCallId:t.id,toolName:t.function.name,rawArguments:t.function.arguments,toolType:`wildcard`,messageId:n.id}})}let c={toolName:t.function.name,args:i};if(await this._internal.notifySubscribers(e=>e.onToolExecutionStart?.({copilotkit:this.core,toolCallId:t.id,agentId:a,toolName:t.function.name,args:c}),`Subscriber onToolExecutionStart error:`),!s)try{let n=await e.handler(c,{toolCall:t,agent:r});o=n==null?``:typeof n==`string`?n:JSON.stringify(n)}catch(e){let r=e instanceof Error?e:Error(String(e));s=r.message,await this._internal.emitError({error:r,code:$h.TOOL_HANDLER_FAILED,context:{agentId:a,toolCallId:t.id,toolName:t.function.name,parsedArgs:c,toolType:`wildcard`,messageId:n.id}})}s&&(o=`Error: ${s}`),await this._internal.notifySubscribers(e=>e.onToolExecutionEnd?.({copilotkit:this.core,toolCallId:t.id,agentId:a,toolName:t.function.name,result:s?``:o,error:s}),`Subscriber onToolExecutionEnd error:`)}{let a=r.messages.findIndex(e=>e.id===n.id);if(a===-1)return!1;let c=a+1;for(;c<r.messages.length&&r.messages[c]?.role===`tool`;)c++;let l={id:i(),role:`tool`,toolCallId:t.id,content:o};if(r.messages.splice(c,0,l),!s&&e?.followUp!==!1)return!0}return!1}async runTool(e){let{name:t,agentId:n,parameters:r={},followUp:a=!1}=e,o=this.getTool({toolName:t,agentId:n});if(!o){let e=Error(`Tool not found: ${t}`);throw await this._internal.emitError({error:e,code:$h.TOOL_NOT_FOUND,context:{toolName:t,agentId:n}}),e}let s=n??`default`,c=this._internal.getAgent(s);if(!c){let e=Error(`Agent not found: ${s}`);throw await this._internal.emitError({error:e,code:$h.AGENT_NOT_FOUND,context:{agentId:s}}),e}let l=i(),u={id:l,type:`function`,function:{name:t,arguments:JSON.stringify(r)}},d={id:i(),role:`assistant`,content:``,toolCalls:[u]};c.messages.push(d);let f={result:``,error:void 0,isArgumentError:!1};o.handler&&(f=await this.executeToolHandler({tool:o,toolCall:u,agent:c,agentId:s,handlerArgs:r,toolType:`runTool`}));let p={id:i(),role:`tool`,toolCallId:l,content:f.result},m=c.messages.findIndex(e=>e.id===d.id);if(m===-1?c.messages.push(p):c.messages.splice(m+1,0,p),!f.error&&a!==!1){if(typeof a==`string`&&a!==`generate`){let e={
13id:i(),role:`user`,content:a};c.messages.push(e)}await this._internal.waitForPendingFrameworkUpdates(),await this.runAgent({agent:c})}return{toolCallId:l,result:f.result,error:f.error}}capabilityKey(e,t){return`${t??``}\u0000${e}`}setToolEnabled(e,t,n){let r=this.capabilityKey(e,n);t?this._disabledToolKeys.delete(r):this._disabledToolKeys.add(r),this.syncWebMCP()}isToolEnabled(e,t){return!this._disabledToolKeys.has(this.capabilityKey(e,t))}buildFrontendTools(e){return this.tools.filter(t=>t.name!==qm&&t.available!==!1&&t.available!==`disabled`&&(!t.agentId||t.agentId===e)&&this.isToolEnabled(t.name,t.agentId)).map(e=>({name:e.name,description:e.description??``,parameters:Hm(e)}))}syncWebMCP(){let e=new Map,t=new Set;for(let n of this.tools)if(n.webmcp&&n.name!==qm&&n.available!==!1&&n.available!==`disabled`&&this.isToolEnabled(n.name,n.agentId)){if(e.has(n.name)){t.has(n.name)||(t.add(n.name),Ju.warn(`[CopilotKit] Multiple WebMCP tools share the name '${n.name}'. Only the first registration is exposed to browser agents.`));continue}e.set(n.name,n)}this._webmcpRegistry.sync(e)}createAgentErrorSubscriber(e){let t=async(t,n,r={})=>{let i={...r};e.agentId&&(i.agentId=e.agentId),await this._internal.emitError({error:t,code:n,context:i})};return{onRunFailed:async({error:e})=>{await t(e,e instanceof cm?$h.AGENT_THREAD_LOCKED:$h.AGENT_RUN_FAILED_EVENT,{source:`onRunFailed`})},onRunErrorEvent:async({event:e})=>{if(this._runAbortController?.signal.aborted===!0||e?.code===`abort`)return;let n=e?.rawEvent instanceof Error?e.rawEvent:e?.rawEvent?.error instanceof Error?e.rawEvent.error:void 0,r=typeof e?.rawEvent?.error==`string`?e.rawEvent.error:e?.message??`Agent run error`,i=n??Error(r);e?.code&&!i.code&&(i.code=e.code),await t(i,$h.AGENT_RUN_ERROR_EVENT,{source:`onRunErrorEvent`,event:e,runtimeErrorCode:e?.code})}}}};function Ym(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Tool arguments for ${t} parsed to non-object (${typeof e})`)}function Xm(e,t){return e===``||e==null?(Ju.debug(`[parseToolArguments] Tool "${t}" received empty/null/undefined arguments — defaulting to {}`),{}):Ym(typeof e==`string`?JSON.parse(e):e,t)}var Zm=e=>e.resume!==void 0||Object.prototype.hasOwnProperty.call(e.forwardedProps?.command??{},`resume`),Qm=class{stateByRun=new Map;messageToRun=new Map;rawEventByMessage=new Map;activeRun=new Map;agentSubscriptions=new Map;pendingContinuations=new WeakMap;constructor(e){this.core=e}initialize(){}markNextRunAsContinuation(e,t){let n=this.pendingContinuations.get(e);n||(n=new Set,this.pendingContinuations.set(e,n));let r={active:!0,expectedRunId:t,bind:e=>{r.active&&(r.expectedInput=e)},cancel:()=>{r.active&&(r.active=!1,n.delete(r),n.size===0&&this.pendingContinuations.delete(e))}};return n.add(r),r}subscribeToAgent(e){if(!e.agentId)return;let t=e.agentId,n=this.agentSubscriptions.get(t);if(n){if(n.agent===e)return;n.unsubscribe(),this.agentSubscriptions.delete(t)}let r=!1,i,a=!1,o=new WeakMap,s=(e,t)=>{let n=o.get(t);if(!n)return;let r=[...e],i=!1;for(let e of n.values()){let t=r.findIndex(t=>t.role===`assistant`&&t.toolCalls?.some(t=>t.id===e.toolCallId));if(t<0)continue;let n=r.reduce((t,n,r)=>(n.role===`tool`&&n.toolCallId===e.toolCallId&&t.push(r),t),[]),a=n.find(e=>!Bm(r[e]?.content));if(a!==void 0){for(let e of n.filter(e=>e!==a).sort((e,t)=>t-e))r.splice(e,1),i=!0;continue}let o=n.find(e=>Bm(r[e]?.content));if(o!==void 0){if(Bm(e.content)){for(let e of n.slice(1).sort((e,t)=>t-e))r.splice(e,1),i=!0;continue}r[o]={...r[o],id:e.messageId,content:e.content},i=!0;for(let e of n.filter(e=>e!==o&&Bm(r[e]?.content)).sort((e,t)=>t-e))r.splice(e,1);continue}let s={id:e.messageId,role:`tool`,toolCallId:e.toolCallId,content:e.content},c=t+1;for(;r[c]?.role===`tool`;)c++;r.splice(c,0,s),i=!0}return i?{messages:r}:void 0},c=e=>{o.delete(e)},l=e=>({...e,runId:i??e.runId}),{unsubscribe:u}=e.subscribe({onRunStartedEvent:({event:t,input:n,state:o})=>{if(r)return;let s=[...this.pendingContinuations.get(e)??[]].find(e=>e.expectedInput===n);s?.cancel(),i=s?s.expectedRunId??t.runId??n.runId:a&&n.runId===i&&!Zm(n)&&(t.runId==null||t.runId===i)?kl():t.runId||n.runId,a=!1,this.handleRunStarted(e,l(n),o)},onRunFinishedEvent:({input:t,state:n,messages:i})=>{if(r)return;a=!0;let o=l(t),u=s(i,t);return c(t),this.handleRunFinished(e,o,n),u},onRunErrorEvent:({input:t,state:n,messages:i})=>{if(r)return;a=!0;let o=l(t),c=s(i,t);return this.handleRunFinished(e,o,n),c},onRunFailed:({input:e,messages:t})=>{if(!r)return s(t,e)},onRunFinalized:({input:e})=>{r||c(e)},onToolCallResultEvent:({event:e,input:t})=>{if(r)return;let n=o.get(t);n||(n=new Map,o.set(t,n)),n.set(e.toolCallId,e)},onStateSnapshotEvent:({event:t,input:n,state:i})=>{r||this.handleStateSnapshot(e,t,l(n),i)},onStateDeltaEvent:({event:t,input:n,state:i})=>{r||this.handleStateDelta(e,t,l(n),i)},onTextMessageStartEvent:({event:t,input:n})=>{r||this.handleTextMessageStart(e,t,l(n))},onMessagesSnapshotEvent:({event:t,input:n,messages:i})=>{r||(this.handleMessagesSnapshot(e,t,l(n),i),this.pruneRawEvents(e.agentId,n.threadId,t.messages,l(n)))},onNewMessage:({message:t,input:n})=>{r||this.handleNewMessage(e,t,n?l(n):void 0)},onMessagesChanged:({messages:t,input:n})=>{r||n||this.pruneRawEvents(e.agentId,e.threadId,t)}});this.agentSubscriptions.set(t,{agent:e,unsubscribe:()=>{r=!0,this.pendingContinuations.delete(e),u()}})}unsubscribeFromAgent(e){let t=this.agentSubscriptions.get(e);t&&(t.unsubscribe(),this.agentSubscriptions.delete(e)),this.rawEventByMessage.delete(e)}getStateByRun(e,t,n){let r=this.stateByRun.get(e)?.get(t)?.get(n);if(r)return JSON.parse(JSON.stringify(r))}getRunIdForMessage(e,t,n){return this.messageToRun.get(e)?.get(t)?.get(n)}getRawEventForMessage(e,t,n){let r=this.rawEventByMessage.get(e)?.get(t)?.get(n);return r===void 0?void 0:B(r)}getStatesForThread(e,t){return this.stateByRun.get(e)?.get(t)??new Map}getRunIdsForThread(e,t){let n=this.stateByRun.get(e)?.get(t);return n?Array.from(n.keys()):[]}handleRunStarted(e,t,n){if(!e.agentId)return;let{threadId:r,runId:i}=t;this.activeRun.set(`${e.agentId}:${r}`,i),n&&Object.keys(n).length>0&&this.saveState(e.agentId,r,i,n)}handleRunFinished(e,t,n){if(!e.agentId)return;let{threadId:r,runId:i}=t;this.activeRun.delete(`${e.agentId}:${r}`),n&&Object.keys(n).length>0&&this.saveState(e.agentId,r,i,n)}handleStateSnapshot(e,t,n,r){if(!e.agentId)return;let{threadId:i,runId:a}=n,o={...r,...t.snapshot};this.saveState(e.agentId,i,a,o)}handleStateDelta(e,t,n,r){if(!e.agentId)return;let{threadId:i,runId:a}=n;this.saveState(e.agentId,i,a,r)}handleTextMessageStart(e,t,n){if(!e.agentId)return;let{threadId:r}=n;if(t.rawEvent===void 0){let n=this.rawEventByMessage.get(e.agentId)?.get(r);n?.delete(t.messageId),n?.size===0&&this.rawEventByMessage.get(e.agentId)?.delete(r),this.rawEventByMessage.get(e.agentId)?.size===0&&this.rawEventByMessage.delete(e.agentId);return}this.rawEventByMessage.has(e.agentId)||this.rawEventByMessage.set(e.agentId,new Map);let i=this.rawEventByMessage.get(e.agentId);i.has(r)||i.set(r,new Map),i.get(r).set(t.messageId,t.rawEvent)}handleMessagesSnapshot(e,t,n,r){if(!e.agentId)return;let{threadId:i,runId:a}=n;for(let n of t.messages)this.getRunIdForMessage(e.agentId,i,n.id)===void 0&&this.associateMessageWithRun(e.agentId,i,n.id,a)}handleNewMessage(e,t,n){if(!e.agentId)return;if(!n){let n=e.threadId??``,r=this.activeRun.get(`${e.agentId}:${n}`);r&&this.associateMessageWithRun(e.agentId,n,t.id,r);return}let{threadId:r,runId:i}=n;this.associateMessageWithRun(e.agentId,r,t.id,i)}saveState(e,t,n,r){this.stateByRun.has(e)||this.stateByRun.set(e,new Map);let i=this.stateByRun.get(e);i.has(t)||i.set(t,new Map),i.get(t).set(n,JSON.parse(JSON.stringify(r)))}associateMessageWithRun(e,t,n,r){this.messageToRun.has(e)||this.messageToRun.set(e,new Map);let i=this.messageToRun.get(e);i.has(t)||i.set(t,new Map),i.get(t).set(n,r)}pruneRawEvents(e,t,n,r){let i=r?.threadId??t;if(!i)return;let a=this.rawEventByMessage.get(e)?.get(i);if(!a)return;let o=new Set(n.map(e=>e.id));for(let e of a.keys())o.has(e)||a.delete(e);a.size===0&&this.rawEventByMessage.get(e)?.delete(i),this.rawEventByMessage.get(e)?.size===0&&this.rawEventByMessage.delete(e)}clearAgentState(e){this.stateByRun.delete(e),this.messageToRun.delete(e),this.rawEventByMessage.delete(e)}clearThreadState(e,t){this.stateByRun.get(e)?.delete(t),this.messageToRun.get(e)?.delete(t),this.rawEventByMessage.get(e)?.delete(t)}},$m=class{_stores={};_snapshot=null;constructor(e){this.core=e}register(e,t){if(e in this._stores){let t=this._stores[e];delete this._stores[e],this._snapshot=null,this.notifyUnregistered(e,t).catch(e=>{console.error(`ThreadStoreRegistry notifyUnregistered failed:`,e)})}this._stores[e]=t,this._snapshot=null,this.notifyRegistered(e,t).catch(e=>{console.error(`ThreadStoreRegistry notifyRegistered failed:`,e)})}unregister(e){if(!(e in this._stores))return;let t=this._stores[e];delete this._stores[e],this._snapshot=null,this.notifyUnregistered(e,t).catch(e=>{console.error(`ThreadStoreRegistry notifyUnregistered failed:`,e)})}get(e){return this._stores[e]}getAll(){return this._snapshot===null&&(this._snapshot=Object.freeze({...this._stores})),this._snapshot}async notifyRegistered(e,t){await this.core.notifySubscribers(n=>n.onThreadStoreRegistered?.({copilotkit:this.core,agentId:e,store:t}),`Subscriber onThreadStoreRegistered error:`)}async notifyUnregistered(e,t){await this.core.notifySubscribers(n=>n.onThreadStoreUnregistered?.({copilotkit:this.core,agentId:e,prevStore:t}),`Subscriber onThreadStoreUnregistered error:`)}},eh={boot:`@@micro-redux/boot`,init:`@@micro-redux/init`,stop:`@@micro-redux/stop`},th={type:eh.boot};function nh(e,t){let n=((...n)=>({...t(...n),type:e}));return n.type=e,n.match=t=>t.type===e,n}function Q(){return{kind:`props`}}function rh(){return{kind:`empty`}}function ih(e,t){let n={};for(let r of Object.keys(t)){let i=t[r];
13if(!i)continue;let a=`[${e}] ${r}`;if(i.kind===`props`){n[r]=nh(a,e=>({...e}));continue}n[r]=nh(a,()=>({}))}return n}function ah(...e){if(e.length<2)throw Error(`on requires at least one action creator and one reducer`);let t=e[e.length-1];return{creators:e.slice(0,-1),reducer:t}}function oh(e,...t){let n=new Map;for(let e of t)for(let t of e.creators){let r=n.get(t.type)??[];r.push(e.reducer),n.set(t.type,r)}return(t,r)=>{let i=t??e,a=n.get(r.type);if(!a||a.length===0)return i;let o=i;for(let e of a)o=e(o,r);return o}}function sh(...e){if(e.length===1){let t=e[0],n=!1,r,i;return e=>n&&e===r?i:(r=e,i=t(e),n=!0,i)}let t=e[e.length-1],n=e.slice(0,-1),r=!1,i=[],a;return e=>{let o=n.map(t=>t(e));return r&&o.length===i.length&&o.every((e,t)=>e===i[t])?a:(i=o,a=t(...o),r=!0,a)}}function ch(e){return t=>t.pipe(F(e),rs())}function lh(...e){if(e.length===0)throw Error(`ofType requires at least one action creator`);let t=new Set(e.map(e=>e.type));return e=>e.pipe(Wo(e=>t.has(e.type)))}function uh(e,t={}){return t.dispatch===!1?{run:e,dispatch:!1}:{run:e,dispatch:!0}}function dh(e){let t=e.reducer,n=e.effects??[],r=!1,i=!1,a=new Ti,o=t(void 0,th),s=new ua(o),c=new ca,l=e=>{if(r)throw Error(`Store is in a failed state due to an effect error`);o=t(o,e),s.next(o),c.next(e)},u=e=>{r||(r=!0,i=!1,a.unsubscribe(),a=new Ti,c.error(e),s.error(e))},d=()=>{for(let e of n){let t=c.asObservable().pipe(to(Da)),n=s.asObservable();if(e.dispatch){let i=e.run(t,n).subscribe({next:e=>{r||l(e)},error:e=>{u(e)}});a.add(i);continue}let i=e.run(t,n).subscribe({error:e=>{u(e)}});a.add(i)}};return{dispatch(e){l(e)},getState(){return o},get state$(){return s.asObservable()},get actions$(){return c.asObservable()},select(e){return s.asObservable().pipe(ch(e))},init(){r||i||(i=!0,d(),!r&&l({type:eh.init}))},stop(){r||!i||(l({type:eh.stop}),a.unsubscribe(),a=new Ti,i=!1)}}}var fh=Object.freeze({MEMORY_LIST_FAILED:{code:`MEMORY_LIST_FAILED`,category:`dependency`,retryable:!0,message:`Failed to fetch memories`,docsPath:`docs/errors/memory.md#memory_list_failed`},MEMORY_RECALL_FAILED:{code:`MEMORY_RECALL_FAILED`,category:`dependency`,retryable:!0,message:`Failed to recall memories`,docsPath:`docs/errors/memory.md#memory_recall_failed`},MEMORY_CREDENTIALS_FAILED:{code:`MEMORY_CREDENTIALS_FAILED`,category:`dependency`,retryable:!0,message:`Failed to fetch memory subscribe credentials`,docsPath:`docs/errors/memory.md#memory_credentials_failed`},MEMORY_MUTATION_FAILED:{code:`MEMORY_MUTATION_FAILED`,category:`dependency`,retryable:!0,message:`Memory mutation request failed`,docsPath:`docs/errors/memory.md#memory_mutation_failed`},MEMORY_REQUEST_TIMEOUT:{code:`MEMORY_REQUEST_TIMEOUT`,category:`dependency`,retryable:!0,message:`Request timed out`,docsPath:`docs/errors/memory.md#memory_request_timeout`}}),ph=class e extends Error{code;category;retryable;constructor(t,n){let r=fh[t];super(n?.message??r.message,{cause:n?.cause}),this.name=`MemoryError`,this.code=t,this.category=r.category,this.retryable=n?.retryable??r.retryable,Object.setPrototypeOf(this,e.prototype)}};function mh(e){return!(Number.isInteger(e)&&e>=400&&e<=499)}var hh=`/memories`,gh=`/memories/subscribe`,_h=`/memories/recall`,vh=15e3,yh=5,bh=new Set([404,422,501]),xh=class extends Error{},Sh=Object.freeze({memories:Object.freeze([]),isLoading:!1,inFlightMutationCount:0,error:null,context:null,sessionId:0,available:!0,realtimeStatus:`connecting`}),Ch=ih(`Memory Adapter`,{started:rh(),stopped:rh(),contextChanged:Q(),addRequested:Q(),updateRequested:Q(),removeRequested:Q()}),wh=ih(`Memory REST`,{listRequested:Q(),listSucceeded:Q(),listFailed:Q(),listUnavailable:Q(),mutationFinished:Q(),credentialsRequested:Q(),credentialsSucceeded:Q(),credentialsFailed:Q(),credentialsUnavailable:Q()}),Th=ih(`Memory Domain`,{memoryUpserted:Q(),memoryInvalidated:Q(),realtimeConnecting:Q(),realtimeConnected:Q(),realtimeUnavailable:Q()});function Eh(e){return{id:e.id,kind:e.kind,scope:e.scope,content:e.content,sourceThreadIds:e.sourceThreadIds,invalidatedAt:e.invalidatedAt}}function Dh(e,t){return e.operation===`invalidated`?Th.memoryInvali
13dated({sessionId:t,memoryId:e.invalidated.id}):Th.memoryUpserted({sessionId:t,memory:Eh(e.memory)})}function Oh(e,t){let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[t,...e];let r=[...e];return r[n]=t,r}var kh=oh(Sh,ah(Ch.contextChanged,(e,{context:t})=>({...e,context:t,sessionId:e.sessionId+1,memories:[],isLoading:!!t,inFlightMutationCount:0,error:null,available:!0,realtimeStatus:`connecting`})),ah(Ch.stopped,e=>({...e,memories:[],isLoading:!1,inFlightMutationCount:0,error:null,available:!0,realtimeStatus:`connecting`})),ah(wh.listRequested,(e,{sessionId:t})=>t!==e.sessionId||!e.context?e:{...e,isLoading:!0,error:null,available:!0}),ah(wh.listFailed,(e,{sessionId:t,error:n})=>t===e.sessionId?{...e,isLoading:!1,error:n}:e),ah(wh.listUnavailable,(e,{sessionId:t})=>t===e.sessionId?{...e,memories:[],isLoading:!1,error:null,available:!1}:e),ah(Ch.addRequested,Ch.updateRequested,Ch.removeRequested,e=>({...e,inFlightMutationCount:e.inFlightMutationCount+1})),ah(wh.mutationFinished,(e,{outcome:t})=>t.sessionId===e.sessionId?{...e,inFlightMutationCount:Math.max(0,e.inFlightMutationCount-1),error:t.ok?null:t.error}:e),ah(wh.listSucceeded,(e,{sessionId:t,memories:n})=>t===e.sessionId?{...e,memories:n,isLoading:!1,error:null,available:!0}:e),ah(Th.memoryUpserted,(e,{sessionId:t,memory:n})=>t===e.sessionId?{...e,memories:Oh(e.memories,n)}:e),ah(Th.memoryInvalidated,(e,{sessionId:t,memoryId:n})=>t===e.sessionId?{...e,memories:e.memories.filter(e=>e.id!==n)}:e),ah(Th.realtimeConnecting,(e,{sessionId:t})=>t===e.sessionId?{...e,realtimeStatus:`connecting`}:e),ah(Th.realtimeConnected,(e,{sessionId:t})=>t===e.sessionId?{...e,realtimeStatus:`connected`}:e),ah(Th.realtimeUnavailable,(e,{sessionId:t})=>t===e.sessionId?{...e,realtimeStatus:`unavailable`}:e)),Ah=sh(e=>e.memories),jh=sh(e=>e.isLoading),Mh=sh(e=>e.error);sh(e=>e.inFlightMutationCount>0);var Nh=sh(e=>e.available),Ph=sh(e=>e.realtimeStatus),Fh=`memory_metadata`;function Ih(e,t){let{selector:n,fetch:r,signal:i,...a}=t;return new $i(t=>{let o=new AbortController,s=()=>o.abort();i?.aborted?o.abort():i?.addEventListener(`abort`,s);let c=uo(r(e,{...a,signal:o.signal})).pipe(Io(e=>uo(n(e)))).subscribe(t);return()=>{i?.removeEventListener(`abort`,s),o.abort(),c.unsubscribe()}})}function Lh(e,t,n){return Bo(()=>{let r=t.includeInvalidated?`?includeInvalidated=true`:``;return Ih(`${t.runtimeUrl}${hh}${r}`,{selector:e=>{if(!e.ok)throw bh.has(e.status)?new xh(String(e.status)):new ph(`MEMORY_LIST_FAILED`,{message:`Failed to fetch memories: ${e.status}`,retryable:mh(e.status)});return e.json()},fetch:e.fetch,method:`GET`,headers:{...t.headers}}).pipe(bo({first:vh,with:()=>{throw new ph(`MEMORY_REQUEST_TIMEOUT`)}}),F(e=>wh.listSucceeded({sessionId:n,memories:e.memories})),Go(e=>e instanceof xh?N(wh.listUnavailable({sessionId:n})):N(wh.listFailed({sessionId:n,error:e instanceof Error?e:Error(String(e))}))))})}function Rh(e,t,n){return Bo(()=>Ih(`${t.runtimeUrl}${gh}`,{selector:async e=>{if(!e.ok)throw bh.has(e.status)?new xh(String(e.status)):new ph(`MEMORY_CREDENTIALS_FAILED`,{message:`Failed to fetch memory subscribe credentials: ${e.status}`,retryable:mh(e.status)});return e.json()},fetch:e.fetch,method:`POST`,headers:{...t.headers,"Content-Type":`application/json`},body:JSON.stringify({})}).pipe(bo({first:vh,with:()=>{throw new ph(`MEMORY_REQUEST_TIMEOUT`)}}),F(e=>{let t=typeof e.joinToken==`string`&&e.joinToken.length>0&&typeof e.joinCode==`string`&&e.joinCode.length>0,r=typeof e.projectJoinToken==`string`&&e.projectJoinToken.length>0&&typeof e.projectJoinCode==`string`&&e.projectJoinCode.length>0;if(!t&&!r)throw Error(`missing memory realtime credentials`);return wh.credentialsSucceeded({sessionId:n,...t?{joinToken:e.joinToken,joinCode:e.joinCode}:{},...r?{projectJoinToken:e.projectJoinToken,projectJoinCode:e.projectJoinCode}:{}})}),Go(e=>e instanceof xh?N(wh.credentialsUnavailable({sessionId:n})):N(wh.credentialsFailed({sessionId:n,error:e instanceof Error?e:Error(String(e))})))))}function zh(e){return{id:e.id,kind:e.kind,scope:e.scope,content:e.content,sourceThreadIds:e.sourceThreadIds,invalidatedAt:e.invalidatedAt}}function Bh(e){return{id:e.id,kind:e.kind,scope:e.scope,content:e.content,sourceThreadIds:e.sourceThreadIds,invalidatedAt:e.invalidatedAt,...typeof e.score==`number`?{score:e.score}:{}}}var Vh=new Set([`topical`,`episodic`,`operational`]),Hh=new Set([`user`,`project`]);function Uh(e){return!e||typeof e!=`object`?Error(`memory mutation response missing/invalid body`):typeof e.id!=`string`||e.id.length===0?Error(`memory mutation response missing/invalid id`):typeof e.kind!=`string`||!Vh.has(e.kind)?Error(`memory mutation response missing/invalid kind`):typeof e.scope!=`string`||!Hh.has(e.scope)?Error(`memory mutation response missing/invalid scope`):typeof e.content==`string`?!Array.isArray(e.sourceThreadIds)||!e.sourceThreadIds.every(e=>typeof e==`string`)?Error(`memory mutation response missing/invalid sourceThreadIds`):e.invalidatedAt!==null&&typeof e.invali
13datedAt!=`string`?Error(`memory mutation response missing/invalid invalidatedAt`):null:Error(`memory mutation response missing/invalid content`)}function Wh(e){return{content:e.content,kind:e.kind,...e.scope===void 0?{}:{scope:e.scope},sourceThreadIds:e.sourceThreadIds??[]}}function Gh(e,t){let{requestId:n,sessionId:r}=e;if(e.kind===`remove`)return[Th.memoryInvalidated({sessionId:r,memoryId:e.id}),wh.mutationFinished({outcome:{requestId:n,sessionId:r,ok:!0,memory:null}})];let i=Uh(t);if(i)return[wh.mutationFinished({outcome:{requestId:n,sessionId:r,ok:!1,error:i}})];let a=zh(t);if(e.kind===`update`){let e=t.retiredId;return typeof e!=`string`||e.length===0?[wh.mutationFinished({outcome:{requestId:n,sessionId:r,ok:!1,error:Error(`supersede response missing retiredId`)}})]:[Th.memoryInvalidated({sessionId:r,memoryId:e}),Th.memoryUpserted({sessionId:r,memory:a}),wh.mutationFinished({outcome:{requestId:n,sessionId:r,ok:!0,memory:a}})]}return[Th.memoryUpserted({sessionId:r,memory:a}),wh.mutationFinished({outcome:{requestId:n,sessionId:r,ok:!0,memory:a}})]}function Kh(e,t,n){let r=n.kind===`add`?`POST`:n.kind===`update`?`PATCH`:`DELETE`,i=n.kind===`add`?hh:`${hh}/${encodeURIComponent(n.id)}`;return Bo(()=>Ih(`${t.runtimeUrl}${i}`,{selector:async e=>{if(!e.ok)throw new ph(`MEMORY_MUTATION_FAILED`,{message:`Request failed: ${e.status}`,retryable:mh(e.status)});return n.kind===`remove`?null:await e.json()},fetch:e.fetch,method:r,headers:{...t.headers,"Content-Type":`application/json`},body:n.kind===`remove`?void 0:JSON.stringify(n.body)}).pipe(bo({first:vh,with:()=>{throw new ph(`MEMORY_REQUEST_TIMEOUT`)}}),Io(e=>N(...Gh(n,e))),Go(e=>N(wh.mutationFinished({outcome:{requestId:n.requestId,sessionId:n.sessionId,ok:!1,error:e instanceof Error?e:Error(String(e))}})))))}function qh(e){let t=0,n=()=>(t+=1,`memory-request-${t}`),r=uh((e,t)=>e.pipe(lh(Ch.contextChanged),ms(t),Wo(([,e])=>!!e.context),F(([,e])=>wh.listRequested({sessionId:e.sessionId})))),i=uh((e,t)=>e.pipe(lh(Ch.contextChanged),ms(t),Wo(([,e])=>!!e.context),F(([,e])=>wh.credentialsRequested({sessionId:e.sessionId})))),a=uh((t,n)=>t.pipe(lh(wh.credentialsRequested),ds(r=>n.pipe(F(e=>e.context),Wo(e=>!!e),Zo(1),F(e=>({action:r,context:e})),fs(t.pipe(lh(Ch.contextChanged,Ch.stopped))),ds(({action:t,context:n})=>Rh(e,n,t.sessionId)))))),o=dh({reducer:kh,effects:[r,i,uh((t,n)=>t.pipe(lh(wh.listRequested),ds(r=>n.pipe(F(e=>e.context),Wo(e=>!!e),Zo(1),F(e=>({action:r,context:e})),fs(t.pipe(lh(Ch.contextChanged,Ch.stopped))),ds(({action:t,context:n})=>Lh(e,n,t.sessionId)))))),a,uh((t,n)=>t.pipe(lh(Ch.addRequested,Ch.updateRequested,Ch.removeRequested),ms(n),Io(([t,n])=>{let r=n.context,i=n.sessionId;return r?.runtimeUrl?Ch.addRequested.match(t)?Kh(e,r,{requestId:t.requestId,sessionId:i,kind:`add`,body:Wh(t.input)}):Ch.updateRequested.match(t)?Kh(e,r,{requestId:t.requestId,sessionId:i,kind:`update`,id:t.id,body:Wh(t.changes)}):Kh(e,r,{requestId:t.requestId,sessionId:i,kind:`remove`,id:t.id}):N(wh.mutationFinished({outcome:{requestId:t.requestId,sessionId:i,ok:!1,error:Error(`Runtime URL is not configured`)}}))}))),uh((e,t)=>e.pipe(lh(wh.credentialsSucceeded),ms(t),Wo(([e,t])=>e.sessionId===t.sessionId&&!!t.context?.wsUrl),ds(([t,n])=>{let r=n.context,{joinToken:i,joinCode:a,projectJoinToken:o,projectJoinCode:s}=t,c=i??o,l=i&&a?`user_meta:memories:${a}`:`project_meta:memories:${s}`,u=t.sessionId,d=e.pipe(lh(Ch.contextChanged,Ch.stopped)),f=(e,t)=>{let n=Xp({socket$:Yp({url:r.wsUrl,options:{params:{join_token:e},reconnectAfterMs:Uu(100,1e4),rejoinAfterMs:Uu(1e3,3e4)}}).pipe(us({bufferSize:1,refCount:!0})),topic:t}).pipe(us({bufferSize:1,refCount:!0}));return Ho(n.pipe(ds(({channel:e})=>Zp(e,Fh)),F(e=>Dh(e,u))),$p(n).pipe(Go(e=>(console.warn(`[memory] failed to join ${t}`,e),Aa))))};return Bo(()=>{let e=Yp({url:r.wsUrl,options:{params:{join_token:c},reconnectAfterMs:Uu(100,1e4),rejoinAfterMs:Uu(1e3,3e4)}}).pipe(us({bufferSize:1,refCount:!0})),n=Xp({socket$:e,topic:l}).pipe(us({bufferSize:1,refCount:!0})),p=tm(em(e).pipe(cs()),yh).pipe(Go(()=>(console.warn(`[memory] WebSocket failed after ${yh} attempts, giving up`),N(void 0))),cs()),m=p.pipe(F(()=>Th.realtimeUnavailable({sessionId:u}))),h=n.pipe(ds(({channel:e})=>Zp(e,Fh)),F(e=>Dh(e,t.sessionId))),g=$p(n).pipe(Yo(N(Th.realtimeConnected({sessionId:u}))),Go(e=>(console.warn(`[memory] failed to join ${l}`,e),N(Th.realtimeUnavailable({sessionId:u}))))),ee=i&&a&&o&&s?f(o,`project_meta:memories:${s}`):Aa;return Ho(N(Th.realtimeConnecting({sessionId:u}
13)),h,g,ee,m).pipe(fs(Ho(d,p.pipe(to(Da)))),os(()=>{}))})})))]});function s(e,t){let{requestId:n}=e,r=_o(Ho(o.actions$.pipe(lh(wh.mutationFinished),Wo(e=>e.outcome.requestId===n),F(e=>e.outcome)),o.actions$.pipe(lh(Ch.stopped),F(()=>({requestId:n,sessionId:o.getState().sessionId,ok:!1,error:Error(`Memory store stopped before mutation completed`)})))).pipe(Zo(1))).then(e=>{if(!e.ok)throw e.error;return t(e)});return o.dispatch(e),r}return{start(){o.init(),o.dispatch(Ch.started())},stop(){o.dispatch(Ch.stopped()),o.stop()},setContext(e){o.dispatch(Ch.contextChanged({context:e}))},refresh(){let{sessionId:e,context:t}=o.getState();if(!t)return Promise.resolve();let n=_o(Ho(o.actions$.pipe(lh(wh.listSucceeded,wh.listFailed,wh.listUnavailable),Wo(t=>t.sessionId===e)),o.actions$.pipe(lh(Ch.stopped)),o.actions$.pipe(lh(Ch.contextChanged))).pipe(Zo(1))).then(e=>{if(wh.listFailed.match(e))throw e.error;if(Ch.stopped.match(e))throw Error(`Memory store stopped before refresh completed`);Ch.contextChanged.match(e)});return o.dispatch(wh.listRequested({sessionId:e})),n},recall(t,n){let{context:r}=o.getState();if(!r?.runtimeUrl)return Promise.reject(Error(`Runtime URL is not configured`));let i={query:t};return n?.limit!==void 0&&(i.limit=n.limit),n?.scope!==void 0&&(i.scope=n.scope),_o(Ih(`${r.runtimeUrl}${_h}`,{selector:async e=>{if(!e.ok)throw new ph(`MEMORY_RECALL_FAILED`,{message:`Failed to recall memories: ${e.status}`,retryable:mh(e.status)});return await e.json()},fetch:e.fetch,method:`POST`,headers:{...r.headers,"Content-Type":`application/json`},body:JSON.stringify(i)}).pipe(bo({first:vh,with:()=>{throw new ph(`MEMORY_REQUEST_TIMEOUT`)}}),F(e=>(e.memories??[]).map(e=>Bh(e)))))},addMemory(e){return s(Ch.addRequested({requestId:n(),input:e}),e=>{if(e.memory==null)throw Error(`add resolved without a memory`);return e.memory})},updateMemory(e,t){return s(Ch.updateRequested({requestId:n(),id:e,changes:t}),e=>{if(e.memory==null)throw Error(`update resolved without a memory`);return e.memory})},removeMemory(e){return s(Ch.removeRequested({requestId:n(),id:e}),()=>void 0)},getState(){return o.getState()},getServerState(){return Sh},select:o.select.bind(o)}}var Jh=Ah,Yh=jh,Xh=Mh,Zh=Nh,Qh=Ph,$h=function(e){return e.RUNTIME_INFO_FETCH_FAILED=`runtime_info_fetch_failed`,e.AGENT_CONNECT_FAILED=`agent_connect_failed`,e.AGENT_RUN_FAILED=`agent_run_failed`,e.AGENT_RUN_FAILED_EVENT=`agent_run_failed_event`,e.AGENT_RUN_ERROR_EVENT=`agent_run_error_event`,e.TOOL_ARGUMENT_PARSE_FAILED=`tool_argument_parse_failed`,e.TOOL_HANDLER_FAILED=`tool_handler_failed`,e.TOOL_NOT_FOUND=`tool_not_found`,e.AGENT_NOT_FOUND=`agent_not_found`,e.AGENT_THREAD_LOCKED=`agent_thread_locked`,e.TRANSCRIPTION_FAILED=`transcription_failed`,e.TRANSCRIPTION_SERVICE_NOT_CONFIGURED=`transcription_service_not_configured`,e.TRANSCRIPTION_INVALID_AUDIO=`transcription_invalid_audio`,e.TRANSCRIPTION_RATE_LIMITED=`transcription_rate_limited`,e.TRANSCRIPTION_AUTH_FAILED=`transcription_auth_failed`,e.TRANSCRIPTION_NETWORK_ERROR=`transcription_network_error`,e.SUBSCRIBER_CALLBACK_FAILED=`subscriber_callback_failed`,e}({}),eg=new Set([`onMessagesChanged`,`onStateChanged`,`onRunInitialized`,`onRunFinalized`,`onRunFailed`,`onRunErrorEvent`]),tg=function(e){return e.Disconnected=`disconnected`,e.Connected=`connected`,e.Connecting=`connecting`,e.Error=`error`,e}({});function ng(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!=null))}var rg=class{_headers;_credentials;_properties;_defaultThrottleMs;_debug;subscribers=new Set;agentRegistry;contextStore;suggestionEngine;runHandler;stateManager;threadStoreRegistry;_memoryStore;previousAgentIds=new Set;constructor({runtimeUrl:e,runtimeTransport:t=`auto`,deferInitialConnection:n=!1,headers:r={},credentials:i,properties:a={},agents__unsafe_dev_only:o={},tools:s=[],suggestionsConfig:c=[],debug:l}){this._headers=ng(r),this._credentials=i,this._properties=a,this._debug=l,this.agentRegistry=new jm(this),this.contextStore=new Mm(this),this.suggestionEngine=new Nm(this),this.runHandler=new Jm(this),this.stateManager=new Qm(this),this.threadStoreRegistry=new $m(this),this.agentRegistry.initialize(o),this.runHandler.initialize(s),this.suggestionEngine.initialize(c),this.stateManager.initialize(),this.agentRegistry.setRuntimeTrans
13port(t),this.agentRegistry.setRuntimeUrl(e,{deferConnection:n}),this.previousAgentIds=new Set(Object.keys(o)),this.subscribe({onRuntimeConnectionStatusChanged:()=>{this._memoryStore&&this.syncMemoryContext()},onAgentsChanged:({agents:e})=>{Object.values(e).forEach(e=>{e.agentId&&this.stateManager.subscribeToAgent(e)});let t=new Set(Object.keys(e));for(let e of Object.keys(this.threadStoreRegistry.getAll()))if(this.previousAgentIds.has(e)&&!t.has(e))try{this.threadStoreRegistry.unregister(e)}catch(t){console.error(`CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for "${e}":`,t)}for(let e of this.previousAgentIds)if(!t.has(e))try{this.stateManager.unsubscribeFromAgent(e)}catch(t){console.error(`CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for "${e}":`,t)}this.previousAgentIds=t}})}async notifySubscribers(e,t){await Promise.all(Array.from(this.subscribers).map(async n=>{try{await e(n)}catch(e){console.error(t,e)}}))}async emitError({error:e,code:t,context:n={}}){await this.notifySubscribers(r=>r.onError?.({copilotkit:this,error:e,code:t,context:n}),`Subscriber onError error:`)}logAndEmitError(e,t,n=`error`){console[n](e,t.error),this.emitError(t).catch(t=>{console.error(e+` — emitError itself failed:`,t)})}get context(){return this.contextStore.context}get agents(){return this.agentRegistry.agents}get tools(){return this.runHandler.tools}get catalogComponents(){return this.runHandler.catalogComponents}get runtimeUrl(){return this.agentRegistry.runtimeUrl}setRuntimeUrl(e){this.agentRegistry.setRuntimeUrl(e)}connect(){this.agentRegistry.connectRuntime()}get runtimeTransport(){return this.agentRegistry.runtimeTransport}setRuntimeTransport(e){this.agentRegistry.setRuntimeTransport(e)}get runtimeVersion(){return this.agentRegistry.runtimeVersion}get headers(){return this._headers}get credentials(){return this._credentials}get properties(){return this._properties}get defaultThrottleMs(){return this._defaultThrottleMs}setDefaultThrottleMs(e){if(e!==void 0&&(!Number.isFinite(e)||e<0)){this.logAndEmitError(`CopilotKitCore.setDefaultThrottleMs: value must be a non-negative finite number or undefined, got ${e}. Keeping current value (${this._defaultThrottleMs}).`,{error:Error(`setDefaultThrottleMs: invalid value (${e}), keeping current value (${this._defaultThrottleMs})`),code:$h.SUBSCRIBER_CALLBACK_FAILED,context:{value:e,currentValue:this._defaultThrottleMs}});return}this._defaultThrottleMs=e}get debug(){return this._debug}setDebug(e){this._debug=e}get runtimeConnectionStatus(){return this.agentRegistry.runtimeConnectionStatus}get ɵruntimeFetch(){return this.agentRegistry.createRuntimeFetch()}get audioFileTranscriptionEnabled(){return this.agentRegistry.audioFileTranscriptionEnabled}get runtimeMode(){return this.agentRegistry.runtimeMode}get intelligence(){return this.agentRegistry.intelligence}get threadEndpoints(){return this.agentRegistry.threadEndpoints}get suggestions(){return this.agentRegistry.suggestions}get inspectorLearning(){return this.agentRegistry.inspectorLearning}get inspectorMetadata(){return this.agentRegistry.inspectorMetadata}async refreshInspectorMetadata(){await this.agentRegistry.refreshInspectorMetadata()}get a2uiEnabled(){return this.agentRegistry.a2uiEnabled}get a2uiAgents(){return this.agentRegistry.a2uiAgents}get openGenerativeUIEnabled(){return this.agentRegistry.openGenerativeUIEnabled}get licenseStatus(){return this.agentRegistry.licenseStatus}get runtimeEntitlements(){return this.agentRegistry.runtimeEntitlements}get runtimeEntitlementRetryPending(){return this.agentRegistry.runtimeEntitlementRetryPending}get telemetryDisabled(){return this.agentRegistry.telemetryDisabled}setHeaders(e){this._headers=ng(e),this._memoryStore&&this.syncMemoryContext(),this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents),this.agentRegistry.handleHeadersChanged(),this.notifySubscribers(e=>e.onHeadersChanged?.({copilotkit:this,headers:this.headers}),`Subscriber onHeadersChanged error:`)}setCredentials(e){this._credentials=e,this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents),this.agentRegistry.handleCredentialsChanged()}setProperties(e){this._properties=e,this.notifySubscribers(e=>e.onPropertiesChanged?.({copilotkit:this,properties:this.properties}),`Subscriber onPropertiesChanged error:`)}setAgents__unsafe_dev_only(e){this.agentRegistry.setAgents__unsafe_dev_only(e)}addAgent__unsafe_dev_only(e){this.agentRegistry.addAgent__unsafe_dev_only(e)}removeAgent__unsafe_dev_only(e){this.agentRegistry.removeAgent__unsafe_dev_only(e)}registerProxiedAgent(e){return this.agentRegistry.registerProxiedAgent(e)}getAgent(e){return this.agentRegistry.getAgent(e)}
13applyHeadersToAgent(e){this.agentRegistry.applyHeadersToAgent(e)}addContext(e){return this.contextStore.addContext(e)}removeContext(e){this.contextStore.removeContext(e)}getContextForAgent(e){return this.contextStore.getContextForAgent(e)}registerThreadStore(e,t){this.threadStoreRegistry.register(e,t)}unregisterThreadStore(e){this.threadStoreRegistry.unregister(e)}getThreadStore(e){return this.threadStoreRegistry.get(e)}getThreadStores(){return this.threadStoreRegistry.getAll()}getMemoryStore(){return this.ensureMemoryStore()}ensureMemoryStore(){return this._memoryStore||(this._memoryStore=qh({fetch:this.ɵruntimeFetch}),this._memoryStore.start(),this.syncMemoryContext()),this._memoryStore}syncMemoryContext(){this._memoryStore&&(this.runtimeConnectionStatus===tg.Connected&&this.intelligence?.wsUrl&&this.runtimeUrl?this._memoryStore.setContext({runtimeUrl:this.runtimeUrl,wsUrl:this.intelligence.wsUrl,headers:{...this.headers}}):this._memoryStore.setContext(null))}addSuggestionsConfig(e){return this.suggestionEngine.addSuggestionsConfig(e)}removeSuggestionsConfig(e){this.suggestionEngine.removeSuggestionsConfig(e)}reloadSuggestions(e){this.suggestionEngine.reloadSuggestions(e)}clearSuggestions(e){this.suggestionEngine.clearSuggestions(e)}getSuggestions(e){return this.suggestionEngine.getSuggestions(e)}addTool(e){this.runHandler.addTool(e)}removeTool(e,t){this.runHandler.removeTool(e,t)}getTool(e){return this.runHandler.getTool(e)}setTools(e){this.runHandler.setTools(e)}setToolEnabled(e,t,n){this.runHandler.setToolEnabled(e,t,n)}isToolEnabled(e,t){return this.runHandler.isToolEnabled(e,t)}setCatalogComponents(e){this.runHandler.setCatalogComponents(e),this.notifySubscribers(e=>e.onCatalogComponentsChanged?.({copilotkit:this,catalogComponents:this.runHandler.catalogComponents}),`Subscriber onCatalogComponentsChanged error:`)}setCatalogComponentEnabled(e,t){this.runHandler.setCatalogComponentEnabled(e,t),this.notifySubscribers(e=>e.onCatalogComponentsChanged?.({copilotkit:this,catalogComponents:this.runHandler.catalogComponents}),`Subscriber onCatalogComponentsChanged error:`)}isCatalogComponentEnabled(e){return this.runHandler.isCatalogComponentEnabled(e)}subscribe(e){return this.subscribers.add(e),{unsubscribe:()=>{this.subscribers.delete(e)}}}subscribeToAgentWithOptions(e,t,n){let r=n?.throttleMs??this._defaultThrottleMs??0,i=0;if(!Number.isFinite(r)||r<0){let t=n?.throttleMs===void 0?`defaultThrottleMs`:`throttleMs`;this.logAndEmitError(`CopilotKitCore.subscribeToAgentWithOptions: ${t} must be a non-negative finite number, got ${r}. Falling back to unthrottled.`,{error:Error(`subscribeToAgentWithOptions: invalid ${t} (${r}), falling back to unthrottled`),code:$h.SUBSCRIBER_CALLBACK_FAILED,context:{agentId:e.agentId,source:t,value:r}})}else i=r;let a=e.agentId||`(unknown agent)`,o=(t,n,...r)=>{let i=(n,r)=>{this.logAndEmitError(`CopilotKitCore.subscribeToAgentWithOptions[${a}]: ${t} callback ${r}:`,{error:n instanceof Error?n:Error(String(n)),code:$h.SUBSCRIBER_CALLBACK_FAILED,context:{agentId:e.agentId,callback:t}})};try{let e=n(...r);return e instanceof Promise?e.catch(e=>{i(e,`rejected`)}):e}catch(e){i(e,`threw`)}},s=e=>{let t={};if(e.onMessagesChanged){let n=e.onMessagesChanged;t.onMessagesChanged=e=>o(`onMessagesChanged`,n,e)}if(e.onStateChanged){let n=e.onStateChanged;t.onStateChanged=e=>o(`onStateChanged`,n,e)}if(e.onRunInitialized){let n=e.onRunInitialized;t.onRunInitialized=e=>o(`onRunInitialized`,n,e)}if(e.onRunFinalized){let n=e.onRunFinalized;t.onRunFinalized=e=>o(`onRunFinalized`,n,e)}if(e.onRunFailed){let n=e.onRunFailed;t.onRunFailed=e=>o(`onRunFailed`,n,e)}if(e.onRunErrorEvent){let n=e.onRunErrorEvent;t.onRunErrorEvent=e=>o(`onRunErrorEvent`,n,e)}return t};for(let n of Object.keys(t))if(typeof t[n]==`function`&&!eg.has(n)){let t=`CopilotKitCore.subscribeToAgentWithOptions[${a}]: callback "${n}" is not supported and was dropped. Supported callbacks: ${Array.from(eg).join(`, `)}. Use agent.subscribe() directly for event handlers and per-item notifications.`;this.logAndEmitError(t,{error:Error(t),code:$h.SUBSCRIBER_CALLBACK_FAILED,context:{agentId:e.agentId,droppedCallback:n}},`warn`)}if(i<=0){let n=e.subscribe(s(t));return{unsubscribe:()=>n.unsubscribe()}}let c=!0,l=null,u=null,d=new be(()=>{if(c&&t.onMessagesChanged&&l){let e=l;l=null,o(`onMessagesChanged`,t.onMessagesChanged,e)}if(c&&t.onStateChanged&&u){let e=u;u=null,o(`onStateChanged`,t.onStateChanged,e)}},{wait:i,leading:!0,trailing:!0}),f={};t.onRunInitialized&&(f.onRunInitialized=t.onRunInitialized),t.onRunFinalized&&(f.onRunFinalized=t.onRunFinalized),t.onRunFailed&&(f.onRunFailed=t.onRunFailed),t.onRunErrorEvent&&(f.onRunErrorEvent=t.onRunErrorEvent);let p=s(f);t.onMessagesChanged&&(p.onMessagesChanged=e=>{l=e,d.maybeExecute()}),t.onStateChanged&&(p.onStateChanged=e=>{u=e,d.maybeExecute()});let m=e.subscribe(p);return{unsubscribe:()=>{c=!1,d.cancel(),m.unsubscribe()}}}async connectAgent(e){return this.runHandler.connectAgent(e)}stopAgent(e){this.runHandler.abortCurrentRun(),e.agent.abortRun()}async runAgent(e){return this.runHandler.runAgent(e)}
13async runTool(e){return this.runHandler.runTool(e)}getStateByRun(e,t,n){return this.stateManager.getStateByRun(e,t,n)}getRunIdForMessage(e,t,n){return this.stateManager.getRunIdForMessage(e,t,n)}getRawEventForMessage(e,t,n){return this.stateManager.getRawEventForMessage(e,t,n)}getRunIdsForThread(e,t){return this.stateManager.getRunIdsForThread(e,t)}buildFrontendTools(e){return this.runHandler.buildFrontendTools(e)}async waitForPendingFrameworkUpdates(){}},ig=function(e){return e.InProgress=`inProgress`,e.Executing=`executing`,e.Complete=`complete`,e}({}),ag=`thread_metadata`,og=`thread_run_activity`,sg=`/threads/subscribe`,cg=5,lg=15e3,ug={threads:[],isLoading:!1,isFetchingNextPage:!1,error:null,fetchMoreError:null,context:null,sessionId:0,metadataCredentialsRequested:!1,metadataJoinCode:null,nextCursor:null,inFlightMutationCount:0,pendingDeletes:{}},$=ih(`Thread Adapter`,{started:rh(),stopped:rh(),contextChanged:Q(),fetchNextPageRequested:rh(),renameRequested:Q(),archiveRequested:Q(),unarchiveRequested:Q(),deleteRequested:Q(),newThreadStarted:rh()}),dg=ih(`Thread REST`,{listRequested:Q(),listSucceeded:Q(),listFailed:Q(),nextPageSucceeded:Q(),nextPageFailed:Q(),metadataCredentialsRequested:Q(),metadataCredentialsSucceeded:Q(),metadataCredentialsFailed:Q(),mutationFinished:Q()}),fg=ih(`Thread Socket`,{opened:Q(),errored:Q(),joinFailed:Q(),joinTimedOut:Q(),metadataReceived:Q(),runActivityReceived:Q()}),pg=ih(`Thread Domain`,{threadUpserted:Q(),threadDeleted:Q()});function mg(e){return[...e].sort((e,t)=>{let n=e.lastRunAt??e.updatedAt??e.createdAt;return(t.lastRunAt??t.updatedAt??t.createdAt).localeCompare(n)})}function hg(e,t){let n=e.findIndex(e=>e.id===t.id);if(n===-1)return mg([...e,t]);let r=[...e];return r[n]=t,mg(r)}function gg(e){return typeof e==`string`&&e.length>0?e:void 0}function _g(e,t){if(!t||e.operation===`deleted`)return!0;let n=gg(e.thread.agentId);return!n||n===t}function vg(e){let t=gg(e.threadId??e.thread_id),n=gg(e.eventType??e.event_type);return!t||!n?null:{type:`thread_run_activity`,threadId:t,agentId:gg(e.agentId??e.agent_id),runId:gg(e.runId??e.run_id),eventType:n,latestEventId:gg(e.latestEventId??e.latest_event_id)}}var yg=oh(ug,ah($.contextChanged,(e,{context:t})=>({...e,context:t,sessionId:e.sessionId+1,threads:[],isLoading:!!t,isFetchingNextPage:!1,error:null,fetchMoreError:null,metadataCredentialsRequested:!1,metadataJoinCode:null,nextCursor:null,inFlightMutationCount:0,pendingDeletes:{}})),ah($.stopped,e=>({...e,threads:[],isLoading:!1,isFetchingNextPage:!1,error:null,fetchMoreError:null,metadataCredentialsRequested:!1,metadataJoinCode:null,nextCursor:null,inFlightMutationCount:0,pendingDeletes:{}})),ah(dg.listRequested,(e,{sessionId:t})=>t!==e.sessionId||!e.context?e:{...e,isLoading:!0,error:null,fetchMoreError:null}),ah(dg.listSucceeded,(e,{sessionId:t,threads:n,joinCode:r,nextCursor:i})=>{if(t!==e.sessionId)return e;let a=r!==e.metadataJoinCode;return{...e,threads:mg(n),isLoading:!1,error:null,fetchMoreError:null,metadataJoinCode:r,metadataCredentialsRequested:!a&&e.metadataCredentialsRequested,nextCursor:i}}),ah(dg.listFailed,(e,{sessionId:t,error:n})=>t===e.sessionId?{...e,isLoading:!1,error:n}:e),ah(dg.nextPageSucceeded,(e,{sessionId:t,threads:n,nextCursor:r})=>{if(t!==e.sessionId)return e;let i=e.threads;for(let e of n)i=hg(i,e);return{...e,threads:i,isFetchingNextPage:!1,fetchMoreError:null,nextCursor:r}}),ah(dg.nextPageFailed,(e,{sessionId:t,error:n})=>t===e.sessionId?{...e,isFetchingNextPage:!1,fetchMoreError:n}:e),ah(dg.metadataCredentialsFailed,(e,{sessionId:t})=>t===e.sessionId?{...e,metadataCredentialsRequested:!1}:e),ah(dg.metadataCredentialsRequested,(e,{sessionId:t})=>t===e.sessionId?{...e,metadataCredentialsRequested:!0}:e),ah($.fetchNextPageRequested,e=>!e.nextCursor||e.isFetchingNextPage?e:{...e,isFetchingNextPage:!0,fetchMoreError:null}),ah($.renameRequested,(e,{threadId:t,name:n})=>{let r=e.threads.find(e=>e.id===t),i=e.inFlightMutationCount+1;return r?{...e,threads:hg(e.threads,{...r,name:n}),inFlightMutationCount:i}:{...e,inFlightMutationCount:i}}),ah($.archiveRequested,(e,{threadId:t})=>{let n=e.threads.find(e=>e.id===t),r=e.inFlightMutationCount+1;return n?e.context?.includeArchived?{...e,threads:hg(e.threads,{...n,archived:!0}),inFlightMutationCount:r}:{...e,threads:e.threads.filter(e=>e.id!==t),inFlightMutationCount:r}:{...e,inFlightMutationCount:r}}),ah($.unarchiveRequested,(e,{threadId:t})=>{let n=e.threads.find(e=>e.id===t),r=e.inFlightMutationCount+1;return n?{...e,threads:hg(e.threads,{...n,archived:!1}),inFlightMutationCount:r}:{...e,inFlightMutationCount:r}}),ah($.deleteRequested,(e,{requestId:t,threadId:n})=>{let r=e.threads.find(e=>e.id===n),i=e.inFlightMutationCount+1;return r?{...e,threads:e.threads.filter(e=>e.id!==n),pendingDeletes:{...e.pendingDeletes,[t]:r},inFlightMutationCount:i}:{...e,inFlightMutationCount:i}}),ah($.newThreadStarted,e=>({...e,error:null})),ah(dg.mutationFinished,(e,{outcome:t})=>{if(t.sessionId!==e.sessionId)return e;let n=Math.max(0,e.inFlightMutationCount-1);if(t.ok){if(e.pendingDeletes[t.requestId]===void 0)return{...e,inFlightMutationCount:n};let{[t.requestId]:r,...i}=e.pendingDeletes;return{...e,inFlightMutationCount:n,pendingDeletes:i}}let r=e.pendingDeletes[t.requestId];if(r===void 0)return{...e,inFlightMutationCount:n,error:t.error};let{[t.requestId]:i,...a}=e.pendingDeletes;return{...e,threads:hg(e.threads,r),pendingDeletes:a,inFlightMutationCount:n,error:t.error}}),ah(pg.threadUpserted,(e,{sessionId:t,thread:n}
13)=>t===e.sessionId?{...e,threads:hg(e.threads,n)}:e),ah(pg.threadDeleted,(e,{sessionId:t,threadId:n})=>t===e.sessionId?{...e,threads:e.threads.filter(e=>e.id!==n)}:e));function bg(){return{threads:sh(e=>e.threads),isLoading:sh(e=>e.isLoading),error:sh(e=>e.error),fetchMoreError:sh(e=>e.fetchMoreError),hasNextPage:sh(e=>e.nextCursor!=null),isFetchingNextPage:sh(e=>e.isFetchingNextPage),isMutating:sh(e=>e.inFlightMutationCount>0)}}var xg=bg(),Sg=xg.threads,Cg=xg.isLoading,wg=xg.error,Tg=xg.fetchMoreError,Eg=xg.hasNextPage,Dg=xg.isFetchingNextPage,Og=xg.isMutating,kg=0;function Ag(){return kg+=1,`thread-request-${kg}`}function jg(e,t){return new $i(n=>{let{fetch:r,selector:i,signal:a,timeoutMs:o,nonCritical:s,...c}=t,l=new AbortController,u={...s?{nonCritical:!0}:{},...o===void 0?{}:{selfBounded:!0}},d=!1,f=()=>l.abort();a?.aborted?f():a?.addEventListener(`abort`,f,{once:!0});let p=o===void 0?void 0:setTimeout(()=>{d=!0,u.timedOut=!0,f()},o);return r(e,{...c,signal:l.signal,ɵruntimeRequest:u}).then(e=>i(e)).then(e=>{n.closed||(n.next(e),n.complete())}).catch(e=>{n.closed||n.error(d?Error(`Request timed out`):e)}),()=>{p!==void 0&&clearTimeout(p),a?.removeEventListener(`abort`,f),f()}})}function Mg(e,t,n){return Bo(()=>{let r={agentId:t.agentId};t.includeArchived&&(r.includeArchived=`true`),t.limit!=null&&(r.limit=String(t.limit));let i=new URLSearchParams(r);return jg(`${t.runtimeUrl}/threads?${i.toString()}`,{selector:e=>{if(!e.ok)throw Error(`Failed to fetch threads: ${e.status}`);return e.json()},fetch:e.fetch,timeoutMs:lg,method:`GET`,headers:{...t.headers}}).pipe(F(e=>dg.listSucceeded({sessionId:n,threads:e.threads,joinCode:typeof e.joinCode==`string`&&e.joinCode.length>0?e.joinCode:null,nextCursor:e.nextCursor??null})),Go(e=>N(dg.listFailed({sessionId:n,error:e instanceof Error?e:Error(String(e))}))))})}function Ng(e,t,n){return Bo(()=>jg(`${t.runtimeUrl}${sg}`,{selector:async e=>{if(!e.ok)throw Error(`Failed to fetch thread metadata credentials: ${e.status}`);return e.json()},fetch:e.fetch,timeoutMs:lg,nonCritical:!0,method:`POST`,headers:{...t.headers,"Content-Type":`application/json`},body:JSON.stringify({})}).pipe(F(e=>{if(typeof e.joinToken!=`string`||e.joinToken.length===0)throw Error(`missing joinToken`);return dg.metadataCredentialsSucceeded({sessionId:n,joinToken:e.joinToken})}),Go(e=>N(dg.metadataCredentialsFailed({sessionId:n,error:e instanceof Error?e:Error(String(e))})))))}function Pg(e,t,n){return Bo(()=>jg(`${t.runtimeUrl}${n.path}`,{selector:async e=>{if(!e.ok)throw Error(`Request failed: ${e.status}`);return null},fetch:e.fetch,method:n.method,headers:{...t.headers,"Content-Type":`application/json`},body:JSON.stringify(n.body)}).pipe(F(()=>dg.mutationFinished({outcome:{requestId:n.requestId,sessionId:n.sessionId,ok:!0}})),Go(e=>N(dg.mutationFinished({outcome:{requestId:n.requestId,sessionId:n.sessionId,ok:!1,error:e instanceof Error?e:Error(String(e))}})))))}function Fg(e){let t=bg(),n=dh({reducer:yg,effects:[uh((e,t)=>e.pipe(lh($.contextChanged),ms(t),Wo(([,e])=>!!e.context),F(([,e])=>dg.listRequested({sessionId:e.sessionId})))),uh((t,n)=>t.pipe(lh(dg.listRequested),ds(r=>n.pipe(F(e=>e.context),Wo(e=>!!e),Zo(1),F(e=>({action:r,context:e})),fs(t.pipe(lh($.contextChanged,$.stopped))),ds(({action:t,context:n})=>Mg(e,n,t.sessionId)))))),uh((e,t)=>e.pipe(lh(dg.listSucceeded),ms(t),Wo(([e,t])=>e.sessionId===t.sessionId&&!t.metadataCredentialsRequested&&!!t.context?.wsUrl&&!!t.metadataJoinCode),F(([e])=>dg.metadataCredentialsRequested({sessionId:e.sessionId})))),uh((t,n)=>t.pipe(lh(dg.metadataCredentialsRequested),ds(r=>n.pipe(F(e=>e.context),Wo(e=>!!e),Zo(1),F(e=>({action:r,context:e})),fs(t.pipe(lh($.contextChanged,$.stopped))),ds(({action:t,context:n})=>Ng(e,n,t.sessionId)))))),uh((e,t)=>e.pipe(lh(dg.metadataCredentialsSucceeded),ms(t),Wo(([e,t])=>e.sessionId===t.sessionId&&!!t.context?.wsUrl),ds(([t,n])=>{let r=n.context,i=t.joinToken,a=n.metadataJoinCode,o=e.pipe(lh($.contextChanged,$.stopped));return Bo(()=>{let e=Yp({url:r.wsUrl,options:{params:{join_token:i},reconnectAfterMs:Uu(100,1e4),rejoinAfterMs:Uu(1e3,3e4)}}).pipe(us({bufferSize:1,refCount:!0})),n=Xp({socket$:e,topic:`user_meta:${a}`}).pipe(us({bufferSize:1,refCount:!0})),s=em(e).pipe(cs()),c=tm(s,cg).pipe(Go(()=>(console.warn(`[threads] WebSocket failed after ${cg} attempts, giving up`),N(void 0))),cs());return Ho(s.pipe(F(e=>e.type===`open`?fg.opened({sessionId:t.sessionId}):fg.errored({sessionId:t.sessionId}))),n.pipe(ds(({channel:e})=>Zp(e,ag)),F(e=>fg.metadataReceived({sessionId:t.sessionId,payload:e}))),n.pipe(ds(({channel:e})=>Zp(e,og)),F(e=>vg(e)),Wo(e=>e!==null),F(e=>fg.runActivityReceived({sessionId:t.sessionId,notification:e}))),Qp(n).pipe(Wo(e=>e.type!==`joined`),F(e=>e.type===`timeout`?fg.joinTimedOut({sessionId:t.sessionId}):fg.joinFailed({sessionId:t.sessionId})))).pipe(fs(Ho(o,c)))})}))),uh((e,t)=>e.pipe(lh(fg.metadataReceived),ms(t),Wo(([e,t])=>e.sessionId===t.sessionId&&_g(e.payload,t.context?.agentId)),F(([e,t])=>e.payload.operation===`deleted`?pg.threadDeleted({sessionId:e.sessionId,threadId:e.payload.deleted.id}):e.payload.operation===`archived`&&!t.context?.includeArchived?pg.threadDeleted({sessionId:e.sessionId,threadId:e.payload.threadId}):pg.threadUpserted({sessionId:e.sessionId,thread:e.payload.thread})))),uh((e,t)=>e.pipe(lh(fg.joinFailed,fg.joinTimedOut,fg.errored,dg.metadataCredentialsFailed),ms(t),Wo(([e,t])=>e.sessionId===t.sessionId),ps(([e])=>{let t=fg.joinTimedOut.match(e)?`channel join timed out`:fg.joinFailed.match(e)?`channel join was rejected`:dg.metadataCredentialsFailed.match(e)?`metadata credentials fetch failed`:`socket errored`;console.warn(`[threads] realtime ${t}; the thread list may be stale until reconnect`)})),{dispatch:!1}),uh((t,n)=>t.pipe(lh($.fetchNextPageRequested),ms(n),Wo(([,e])=>!!e.context&&!!e.nextCursor),ds(([,n])=>{let r=n.context,i={agentId:r.agentId,cursor:n.nextCursor};return r.includeArchived&&(i.includeArchived=`true`),r.limit!=null&&(i.limit=String(r.limit)),jg(`${r.runtimeUrl}/threads?${new URLSearchParams(i).toString()}`,{selector:e=>{if(!e.ok)throw Error(`Failed to fetch next page: ${e.status}`);return e.json()},fetch:e.fetch,timeoutMs:lg,method:`GET`,headers:{...r.headers}}).pipe(F(e=>dg.nextPageSucceeded({sessionId:n.sessionId,threads:e.threads,nextCursor:e.nextCursor??null})),Go(e=>N(dg.nextPageFailed({sessionId:n.sessionId,error:e instanceof Error?e:Error(String(e))}))),fs(t.pipe(lh($.contextChanged,$.stopped))))}))),uh((t,n)=>t.pipe(lh($.renameRequested,$.archiveRequested,$.unarchiveRequested,$.deleteRequested),ms(n),Io(([t,n])=>{let r=n.sessionId,i=n.context;if(!i?.runtimeUrl){let e=t.requestId;return N(dg.mutationFinished({outcome:{requestId:e,sessionId:r,ok:!1,error:Error(`Runtime URL is not configured`)}}))}let a={agentId:i.agentId};return $.renameRequested.match(t)?Pg(e,i,{requestId:t.requestId,sessionId:r,method:`PATCH`,path:`/threads/${encodeURIComponent(t.threadId)}`,body:{...a,name:t.name}}):$.archiveRequested.match(t)?Pg(e,i,{requestId:t.requestId,sessionId:r,method:`POST`,path:`/threads/${encodeURIComponent(t.threadId)}/archive`,body:a}):$.unarchiveRequested.match(t)?Pg(e,i,{requestId:t.requestId,sessionId:r,method:`PATCH`,path:`/threads/${encodeURIComponent(t.threadId)}`,body:{...a,archived:!1}}):Pg(e,i,{requestId:t.requestId,sessionId:r,method:`DELETE`,path:`/threads/${encodeURIComponent(t.threadId)}`,body:a})})))]});function r(e){let t=_o(Ho(n.actions$.pipe(lh(dg.mutationFinished),Wo(t=>t.outcome.requestId===e.requestId),F(e=>e.outcome)),n.actions$.pipe(lh($.stopped),F(()=>({requestId:e.requestId,sessionId:n.getState().sessionId,ok:!1,error:Error(`Thread store stopped before mutation completed`)})))).pipe(Zo(1))).then(e=>{if(!e.ok)throw e.error});return n.dispatch(e),t}let i=null,a=()=>{!e.onError||i||(i=n.actions$.pipe(lh(dg.mutationFinished),Wo(e=>!e.outcome.ok&&e.outcome.sessionId===n.getState().sessionId)).subscribe(t=>{t.outcome.ok||e.onError?.(t.outcome.error)}))};return{start(){n.init(),a(),n.dispatch($.started())},stop(){n.dispatch($.stopped()),i?.unsubscribe(),i=null,n.stop()},setContext(e){n.dispatch($.contextChanged({context:e}))},refresh(){let{sessionId:e,context:t}=n.getState();t&&n.dispatch(dg.listRequested({sessionId:e}))},refetchThreads(){let{sessionId:e,context:t}=n.getState();t&&n.dispatch(dg.listRequested({sessionId:e}))},startNewThread(){n.dispatch($.newThreadStarted())},fetchNextPage(){n.dispatch($.fetchNextPageRequested())},renameThread(e,t){return r($.renameRequested({requestId:Ag(),threadId:e,name:t}))},archiveThread(e){return r($.archiveRequested({requestId:Ag(),threadId:e}))},unarchiveThread(e){return r($.unarchiveRequested({requestId:Ag(),threadId:e}))},deleteThread(e){return r($.deleteRequested({requestId:Ag(),threadId:e}))},subscribeToRunActivity(e){return n.actions$.pipe(lh(fg.runActivityReceived),Wo(e=>e.sessionId===n.getState().sessionId),F(e=>e.notification)).subscribe(e)},getState(){return n.getState()},getServerState(){return ug},select:n.select.bind(n),selectors:t}}
13var Ig=Sg,Lg=Cg,Rg=wg,zg=Tg,Bg=Eg,Vg=Dg,Hg=Og,Ug=Object.freeze([`chat`,`sidebar`,`popup`,`threads`]);new Set(Ug);var Wg=`copilotkit:cpk-inspector-thread`;function Gg(e){return`${Wg}:${e}`}function Kg(){if(typeof window<`u`&&typeof window.addEventListener==`function`)return window;if(typeof EventTarget>`u`)return null;let e=globalThis;return e.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__??=new EventTarget,e.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__}function qg(e,t){if(typeof CustomEvent<`u`)return new CustomEvent(e,{detail:t});let n=new Event(e);return Object.defineProperty(n,"detail",{value:t}),n}function Jg(e){return e.detail}function Yg(){return!1}function Xg(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`inspector-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Zg(e,t){if(!Yg())return;let n=Kg();n&&n.dispatchEvent(qg(Gg(e),t))}function Qg(e,t){if(!Yg())return()=>void 0;let n=Kg();if(!n)return()=>void 0;let r=e=>{t(Jg(e))},i=Gg(e);return n.addEventListener(i,r),()=>n.removeEventListener(i,r)}function $g(e){if(!Yg())return!1;let t=Kg();if(!t)return!1;let n={payload:e,claimed:!1};return t.dispatchEvent(qg(Gg(`view-thread`),n)),n.claimed}function e_(e){Zg(`stop-viewing`,e)}function t_(e){Zg(`active-thread`,e)}function n_(e){Zg(`view-thread-result`,e)}function r_(e){if(!Yg())return()=>void 0;let t=Kg();if(!t)return()=>void 0;let n=t=>{let n=Jg(t);n.claimed||=e(n.payload)},r=Gg(`view-thread`);return t.addEventListener(r,n),()=>t.removeEventListener(r,n)}function i_(e){return Qg(`stop-viewing`,e)}function a_(e){return Qg(`active-thread`,e)}function o_(e){return Qg(`view-thread-result`,e)}var s_=globalThis,c_=s_.ShadowRoot&&(s_.ShadyCSS===void 0||s_.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,l_=Symbol(),u_=new WeakMap,d_=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==l_)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(c_&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=u_.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&u_.set(t,e))}return e}toString(){return this.cssText}},f_=e=>new d_(typeof e==`string`?e:e+``,void 0,l_),p_=(e,...t)=>new d_(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,l_),m_=(e,t)=>{if(c_)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=s_.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},h_=c_?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return f_(t)})(e):e,{is:g_,defineProperty:__,getOwnPropertyDescriptor:v_,getOwnPropertyNames:y_,getOwnPropertySymbols:b_,getPrototypeOf:x_}=Object,S_=globalThis,C_=S_.trustedTypes,w_=C_?C_.emptyScript:``,T_=S_.reactiveElementPolyfillSupport,E_=(e,t)=>e,D_={toAttribute(e,t){switch(t){case Boolean:e=e?w_:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},O_=(e,t)=>!g_(e,t),k_={attribute:!0,type:String,converter:D_,reflect:!1,useDefault:!1,hasChanged:O_};Symbol.metadata??=Symbol(`metadata`),S_.litPropertyMetadata??=new WeakMap;var A_=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=k_){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&__(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=v_(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??k_}static _$Ei(){if(this.hasOwnProperty(E_(`elementProperties`)))return;let e=x_(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(E_(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(E_(`properties`))){let e=this.properties,t=[...y_(e),...b_(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(h_(e))}else e!==void 0&&t.push(h_(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e
vendor: 4,171 bytes, lines 13-14
13=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return m_(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?D_:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?D_:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??O_)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};A_.elementStyles=[],A_.shadowRootOptions={mode:`open`},A_[E_(`elementProperties`)]=new Map,A_[E_(`finalized`)]=new Map,T_?.({ReactiveElement:A_}),(S_.reactiveElementVersions??=[]).push(`2.1.2`);var j_=globalThis,M_=e=>e,N_=j_.trustedTypes,P_=N_?N_.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,F_=`$lit$`,I_=`lit$${Math.random().toFixed(9).slice(2)}$`,L_=`?`+I_,R_=`<${L_}>`,z_=document,B_=()=>z_.createComment(``),V_=e=>e===null||typeof e!=`object`&&typeof e!=`function`,H_=Array.isArray,U_=e=>H_(e)||typeof e?.[Symbol.iterator]==`function`,W_=`[ 	
14\f\r]`,G_=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,K_=/-->/g,q_=/>/g,J_=RegExp(`>|${W_}(?:([^\\s"'>=/]+)(${W_}*=${W_}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Y_=/'/g,X_=/"/g,Z_=/^(?:script|style|textarea|title)$/i,Q_=(e=>(t,...n)=>({_$litType$:e,strings:t,values:n}))(1),$_=Symbol.for(`lit-noChange`),ev=Symbol.for(`lit-nothing`),tv=new WeakMap,nv=z_.createTreeWalker(z_,129);function rv(e,t){if(!H_(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return P_===void 0?t:P_.createHTML(t)}var iv=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=G_;
vendor: 5,319 bytes, line 14
14for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===G_?c[1]===`!--`?o=K_:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=J_):(Z_.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=J_):o=q_:o===J_?c[0]===`>`?(o=i??G_,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?J_:c[3]===`"`?X_:Y_):o===X_||o===Y_?o=J_:o===K_||o===q_?o=G_:(o=J_,i=void 0);let d=o===J_&&e[t+1].startsWith(`/>`)?` `:``;a+=o===G_?n+R_:l>=0?(r.push(s),n.slice(0,l)+F_+n.slice(l)+I_+d):n+I_+(l===-2?t:d)}return[rv(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},av=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=iv(t,n);if(this.el=e.createElement(l,r),nv.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=nv.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(F_)){let t=u[o++],n=i.getAttribute(e).split(I_),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?uv:r[1]===`?`?dv:r[1]===`@`?fv:lv}),i.removeAttribute(e)}else e.startsWith(I_)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Z_.test(i.tagName)){let e=i.textContent.split(I_),t=e.length-1;if(t>0){i.textContent=N_?N_.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],B_()),nv.nextNode(),c.push({type:2,index:++a});i.append(e[t],B_())}}}else if(i.nodeType===8){if(i.data===L_)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(I_,e+1))!==-1;)c.push({type:7,index:a}),e+=I_.length-1}}a++}}static createElement(e,t){let n=z_.createElement(`template`);return n.innerHTML=e,n}};function ov(e,t,n=e,r){if(t===$_)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=V_(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=ov(e,i._$AS(e,t.values),i,r)),t}var sv=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??z_).importNode(t,!0);nv.currentNode=r;let i=nv.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new cv(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new pv(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=nv.nextNode(),a++)}return nv.currentNode=z_,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},cv=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=ev,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=ov(this,e,t),V_(e)?e===ev||e==null||e===``?(this._$AH!==ev&&this._$AR(),this._$AH=ev):e!==this._$AH&&e!==$_&&this._(e):e._$litType$===void 0?e.nodeType===void 0?U_(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==ev&&V_(this._$AH)?this._$AA.nextSibling.data=e:this.T(z_.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=av.createElement(rv(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new sv(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=tv.get(e.strings);return t===void 0&&tv.set(e.strings,t=new av(e)),t}k(t){H_(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(B_()),this.O(B_()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=M_(e).nextSibling;M_(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},lv=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=ev,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=ev}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=ov(this,e,t,0),a=!V_(e)||e!==this._$AH&&e!==$_,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=ov(this,r[n+o],t,o),s===$_&&(s=this._$AH[o]),a||=!V_(s)||s!==this._$AH[o],s===ev?e=ev:e!==ev&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===ev?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},uv=class extends lv{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===ev?void 0:e}},dv=class extends lv{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==ev)}},fv=class extends lv{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}
vendor: 2,481 bytes, line 14
14_$AI(e,t=this){if((e=ov(this,e,t,0)??ev)===$_)return;let n=this._$AH,r=e===ev&&n!==ev||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==ev&&(n===ev||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},pv=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){ov(this,e)}},mv={M:F_,P:I_,A:L_,C:1,L:iv,R:sv,D:U_,V:ov,I:cv,H:lv,N:dv,U:fv,B:uv,F:pv},hv=j_.litHtmlPolyfillSupport;hv?.(av,cv),(j_.litHtmlVersions??=[]).push(`3.3.3`);var gv=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new cv(t.insertBefore(B_(),e),e,void 0,n??{})}return i._$AI(e),i},_v=globalThis,vv=class extends A_{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=gv(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return $_}};vv._$litElement$=!0,vv.finalized=!0,_v.litElementHydrateSupport?.({LitElement:vv});var yv=_v.litElementPolyfillSupport;yv?.({LitElement:vv}),(_v.litElementVersions??=[]).push(`4.2.2`);var bv={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},xv=e=>(...t)=>({_$litDirective$:e,values:t}),Sv=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};export{Zt as $,Bg as A,Lg as B,Yg as C,r_ as D,i_ as E,Xh as F,Eu as G,qu as H,Yh as I,mi as J,di as K,Qh as L,Hg as M,Jh as N,o_ as O,Zh as P,Yt as Q,Ig as R,n_ as S,a_ as T,Hu as U,Gp as V,zu as W,_i as X,fi as Y,T as Z,Xg as _,ev as a,O as at,e_ as b,Q_ as c,E as ct,f_ as d,Ce as dt,D as et,rg as f,ig as g,vm as h,vv as i,Jt as it,Vg as j,zg as k,mv as l,Qt as lt,tg as m,Sv as n,tn as nt,gv as o,rn as ot,$h as p,pi as q,bv as r,k as rt,$_ as s,en as st,xv as t,an as tt,p_ as u,Xt as ut,Fg as v,lm as w,$g as x,t_ as y,Rg as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.